Skip to content

Commit

Permalink
cleanup: use input/output for host function arguments and results (#5)
Browse files Browse the repository at this point in the history
* cleanup: use input/output for host function arguments and results

* cleanup: keep setResults/getParams

* fix: output pointer index
  • Loading branch information
zshipko authored Sep 21, 2023
1 parent 7dbb890 commit 9565083
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
3 changes: 2 additions & 1 deletion Example.hs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import Extism.HostFunction
import Extism.Manifest(manifest, wasmFile)

hello currPlugin msg = do
putStrLn <$> unwrap <$> input currPlugin 0
putStrLn "Hello from Haskell!"
putStrLn msg
result currPlugin 0 "{\"count\": 999}"
output currPlugin 0 "{\"count\": 999}"

main = do
setLogFile "stdout" LogError
Expand Down
25 changes: 14 additions & 11 deletions src/Extism/HostFunction.hs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{-# LANGUAGE GeneralizedNewtypeDeriving, DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, DerivingStrategies, BangPatterns #-}

module Extism.HostFunction(
CurrentPlugin(..),
Expand All @@ -25,8 +25,8 @@ module Extism.HostFunction(
fromF32,
fromF64,
hostFunction,
param,
result,
input,
output,
getParams,
setResults
) where
Expand Down Expand Up @@ -165,15 +165,18 @@ setResults (CurrentPlugin _ _ res _) = pokeArray res
getParams :: CurrentPlugin -> [Val]
getParams (CurrentPlugin _ params _ _) = params

result :: ToBytes a => CurrentPlugin -> Int -> a -> IO ()
result p index x = do
mem <- alloc p x
let CurrentPlugin _ _ res len = p
if index >= len then return ()
else pokeElemOff res len (toI64 mem)
output :: ToBytes a => CurrentPlugin -> Int -> a -> IO ()
output !p !index !x =
let
CurrentPlugin _ _ !res !len = p
in
do
mem <- alloc p x
if index >= len then return ()
else pokeElemOff res index (toI64 mem)

param :: FromPointer a => CurrentPlugin -> Int -> IO (Result a)
param plugin index =
input :: FromPointer a => CurrentPlugin -> Int -> IO (Result a)
input plugin index =
let (CurrentPlugin _ params _ _) = plugin in
let x = fromI64 (params !! index) :: Maybe Word64 in
case x of
Expand Down
4 changes: 3 additions & 1 deletion test/Test.hs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ pluginCall = do


hello plugin () = do
s <- unwrap <$> input plugin 0
assertEqual "host function input" "{\"count\": 4}" s
putStrLn "Hello from Haskell!"
result plugin 0 "{\"count\": 999}"
output plugin 0 "{\"count\": 999}"

pluginCallHostFunction = do
p <- Extism.pluginFromManifest hostFunctionManifest [] False >>= assertUnwrap
Expand Down

0 comments on commit 9565083

Please sign in to comment.