Skip to content

Commit 070566b

Browse files
committed
wasm: basic String operations
Signed-off-by: Xe Iaso <[email protected]>
1 parent 68276af commit 070566b

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

wasm/malloc_other.go

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
//go:build !wasip1
2+
3+
package wasm
4+
5+
func Malloc(size uint32) Buffer {
6+
panic("don't call this if you're not using WASI")
7+
}

wasm/wasm.go

+12
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,24 @@ import (
66

77
type String uint64
88

9+
func (value String) Address() uint32 {
10+
return uint32(value >> 32)
11+
}
12+
13+
func (value String) Length() uint32 {
14+
return uint32((value << 32) >> 32)
15+
}
16+
917
func FromString(value string) String {
1018
position := uint32(uintptr(unsafe.Pointer(unsafe.StringData(value))))
1119
bytes := uint32(len(value))
1220
return String(uint64(position)<<32 | uint64(bytes))
1321
}
1422

23+
func (value String) String() string {
24+
return unsafe.String((*byte)(unsafe.Pointer(uintptr(value.Address()))), value.Length())
25+
}
26+
1527
type Buffer uint64
1628

1729
func (buffer Buffer) Address() uint32 {

wasm/wasm_host.go

+9
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ func (value String) LoadBytes(module api.Module) []byte {
2121
return data
2222
}
2323

24+
func (value String) Store(ctx context.Context, module api.Module, data string) (String, error) {
25+
buffer, err := Store(ctx, module, []byte(data))
26+
if err != nil {
27+
return 0, err
28+
}
29+
30+
return String(buffer), nil
31+
}
32+
2433
func (buffer Buffer) Load(module api.Module) []byte {
2534
data, ok := module.Memory().Read(buffer.Address(), buffer.Length())
2635
if !ok {

0 commit comments

Comments
 (0)