diff options
| author | Xe Iaso <me@xeiaso.net> | 2025-02-21 11:02:14 -0500 |
|---|---|---|
| committer | Xe Iaso <me@xeiaso.net> | 2025-02-21 11:02:27 -0500 |
| commit | fe582b802c6a858fa0ac43ea7b1b64324ac51fe4 (patch) | |
| tree | f10ee87738f9f339ee8918c98e53398cc4a18f0f /wasm/wasm.go | |
| parent | ceff7a09a4ad41bb3b91369e73d93e67d7a78e28 (diff) | |
| download | x-fe582b802c6a858fa0ac43ea7b1b64324ac51fe4.tar.xz x-fe582b802c6a858fa0ac43ea7b1b64324ac51fe4.zip | |
wasm: introduce new package for host->guest buffer passing
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'wasm/wasm.go')
| -rw-r--r-- | wasm/wasm.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/wasm/wasm.go b/wasm/wasm.go new file mode 100644 index 0000000..5981c06 --- /dev/null +++ b/wasm/wasm.go @@ -0,0 +1,53 @@ +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)) + return String(uint64(position)<<32 | uint64(bytes)) +} + +type Buffer uint64 + +func (buffer Buffer) Address() uint32 { + return uint32(buffer >> 32) +} + +func (buffer Buffer) Length() uint32 { + return uint32((buffer << 32) >> 32) +} + +func FromSlice(value []byte) Buffer { + if len(value) == 0 { + return 0 + } + ptr := uint64(uintptr(unsafe.Pointer(&value[0]))) + return Buffer(ptr<<32 | uint64(len(value))) +} + +func (buffer Buffer) Slice() []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(buffer.Address()))), buffer.Length()) +} + +func (buffer Buffer) String() string { + return unsafe.String((*byte)(unsafe.Pointer(uintptr(buffer.Address()))), buffer.Length()) +} |
