diff options
| author | Xe Iaso <me@xeiaso.net> | 2025-02-28 13:27:20 -0500 |
|---|---|---|
| committer | Xe Iaso <me@xeiaso.net> | 2025-02-28 13:27:20 -0500 |
| commit | 070566bce7cc37e12d3dee13fe8334f65341f55f (patch) | |
| tree | 8a045c5cf4126be1a85f80fd7d77aa54f0af6064 | |
| parent | 68276af76b25560fbe9df0fcd15f73242f4b2fab (diff) | |
| download | x-070566bce7cc37e12d3dee13fe8334f65341f55f.tar.xz x-070566bce7cc37e12d3dee13fe8334f65341f55f.zip | |
wasm: basic String operations
Signed-off-by: Xe Iaso <me@xeiaso.net>
| -rw-r--r-- | wasm/malloc_other.go | 7 | ||||
| -rw-r--r-- | wasm/wasm.go | 12 | ||||
| -rw-r--r-- | wasm/wasm_host.go | 9 |
3 files changed, 28 insertions, 0 deletions
diff --git a/wasm/malloc_other.go b/wasm/malloc_other.go new file mode 100644 index 0000000..5d915f8 --- /dev/null +++ b/wasm/malloc_other.go @@ -0,0 +1,7 @@ +//go:build !wasip1 + +package wasm + +func Malloc(size uint32) Buffer { + panic("don't call this if you're not using WASI") +} diff --git a/wasm/wasm.go b/wasm/wasm.go index 88c1a11..68acd17 100644 --- a/wasm/wasm.go +++ b/wasm/wasm.go @@ -6,12 +6,24 @@ import ( type String uint64 +func (value String) Address() uint32 { + return uint32(value >> 32) +} + +func (value String) Length() uint32 { + return uint32((value << 32) >> 32) +} + func FromString(value string) String { position := uint32(uintptr(unsafe.Pointer(unsafe.StringData(value)))) bytes := uint32(len(value)) return String(uint64(position)<<32 | uint64(bytes)) } +func (value String) String() string { + return unsafe.String((*byte)(unsafe.Pointer(uintptr(value.Address()))), value.Length()) +} + type Buffer uint64 func (buffer Buffer) Address() uint32 { diff --git a/wasm/wasm_host.go b/wasm/wasm_host.go index 64b8654..01c644d 100644 --- a/wasm/wasm_host.go +++ b/wasm/wasm_host.go @@ -21,6 +21,15 @@ func (value String) LoadBytes(module api.Module) []byte { return data } +func (value String) Store(ctx context.Context, module api.Module, data string) (String, error) { + buffer, err := Store(ctx, module, []byte(data)) + if err != nil { + return 0, err + } + + return String(buffer), nil +} + func (buffer Buffer) Load(module api.Module) []byte { data, ok := module.Memory().Read(buffer.Address(), buffer.Length()) if !ok { |
