aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorXe Iaso <me@xeiaso.net>2025-02-28 13:16:25 -0500
committerXe Iaso <me@xeiaso.net>2025-02-28 13:16:35 -0500
commit68276af76b25560fbe9df0fcd15f73242f4b2fab (patch)
treeb5f250bc155d4ed4e385477f43518c8d2d8066b6
parent3745394dfbb261bc25976f8d157c1bb11aec95d7 (diff)
downloadx-68276af76b25560fbe9df0fcd15f73242f4b2fab.tar.xz
x-68276af76b25560fbe9df0fcd15f73242f4b2fab.zip
wasm: split out host-specific bits
Signed-off-by: Xe Iaso <me@xeiaso.net>
-rw-r--r--wasm/wasm.go14
-rw-r--r--wasm/wasm_host.go41
2 files changed, 41 insertions, 14 deletions
diff --git a/wasm/wasm.go b/wasm/wasm.go
index 5981c06..88c1a11 100644
--- a/wasm/wasm.go
+++ b/wasm/wasm.go
@@ -2,24 +2,10 @@ package wasm
import (
"unsafe"
-
- "github.com/tetratelabs/wazero/api"
)
type String uint64
-func (value String) Load(module api.Module) string {
- return string(value.LoadBytes(module))
-}
-
-func (value String) LoadBytes(module api.Module) []byte {
- data, ok := module.Memory().Read(uint32(value>>32), uint32(value))
- if !ok {
- panic("memory read out of bounds")
- }
- return data
-}
-
func FromString(value string) String {
position := uint32(uintptr(unsafe.Pointer(unsafe.StringData(value))))
bytes := uint32(len(value))
diff --git a/wasm/wasm_host.go b/wasm/wasm_host.go
new file mode 100644
index 0000000..64b8654
--- /dev/null
+++ b/wasm/wasm_host.go
@@ -0,0 +1,41 @@
+//go:build !wasip1
+
+package wasm
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/tetratelabs/wazero/api"
+)
+
+func (value String) Load(module api.Module) string {
+ return string(value.LoadBytes(module))
+}
+
+func (value String) LoadBytes(module api.Module) []byte {
+ data, ok := module.Memory().Read(uint32(value>>32), uint32(value))
+ if !ok {
+ panic("memory read out of bounds")
+ }
+ return data
+}
+
+func (buffer Buffer) Load(module api.Module) []byte {
+ data, ok := module.Memory().Read(buffer.Address(), buffer.Length())
+ if !ok {
+ panic("memory read out of bounds")
+ }
+ return data
+}
+
+func Store(ctx context.Context, module api.Module, data []byte) (Buffer, error) {
+ results, err := module.ExportedFunction("malloc").Call(ctx, uint64(len(data)))
+ if err != nil {
+ return 0, fmt.Errorf("wasm: failed to call malloc: %w", err)
+ }
+
+ buffer := Buffer(results[0])
+ module.Memory().Write(buffer.Address(), data)
+ return buffer, nil
+}