Skip to content

Commit

Permalink
feat: Implement Wat2Wasm.
Browse files Browse the repository at this point in the history
It depends on wasmerio/wasmer#1635. The
`include/` and `wasmer_wasm.h` files are already from this PR.
  • Loading branch information
Hywan committed Sep 18, 2020
1 parent a582161 commit 1dd2c14
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
Binary file modified wasmer/include/libwasmer_c_api.dylib
Binary file not shown.
4 changes: 4 additions & 0 deletions wasmer/wasmer_wasm.h
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,8 @@ int wasmer_last_error_length();
*/
int wasmer_last_error_message(char* buffer, int length);

// Parses in-memory bytes as either the WAT format, or a binary Wasm
// module. This is wasmer-specific.
void wat2wasm(wasm_byte_vec_t* wat, wasm_byte_vec_t* wasm);

#endif /* WASMER_WASM_H */
40 changes: 40 additions & 0 deletions wasmer/wat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package wasmer

// #include <wasmer_wasm.h>
//
// void to_wat2wasm(uint8_t *wat_data, size_t wat_length, wasm_byte_vec_t *wasm) {
// wasm_byte_vec_t wat;
// wat.size = wat_length;
// wat.data = (wasm_byte_t*) wat_data;
//
// wat2wasm(&wat, wasm);
// }
import "C"
import (
"runtime"
"unsafe"
)

func Wat2Wasm(wat string) ([]byte, error) {
watAsBytes := []byte(wat)
var watPtr *C.uint8_t
var watLength = len(wat)

if watLength > 0 {
watPtr = (*C.uint8_t)(unsafe.Pointer(&watAsBytes[0]))
}

wasm := C.wasm_byte_vec_t{}

C.to_wat2wasm(watPtr, C.size_t(watLength), &wasm)
runtime.KeepAlive(wat)

if wasm.data == nil {
return nil, newErrorFromWasmer()
}

wasmBytes := C.GoBytes(unsafe.Pointer(wasm.data), C.int(wasm.size))
C.wasm_byte_vec_delete(&wasm)

return wasmBytes, nil
}
26 changes: 26 additions & 0 deletions wasmer/wat_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package wasmer

import (
"github.com/stretchr/testify/assert"
"testing"
)

func TestWat2Wasm(t *testing.T) {
wasm, err := Wat2Wasm("(module)")

assert.NoError(t, err)
assert.Equal(t, wasm, []byte("\x00asm\x01\x00\x00\x00"))
}

func TestWasm2Wasm(t *testing.T) {
wasm, err := Wat2Wasm(string([]byte("\x00asm\x01\x00\x00\x00")))

assert.NoError(t, err)
assert.Equal(t, wasm, []byte("\x00asm\x01\x00\x00\x00"))
}

func TestBadWat2Wasm(t *testing.T) {
_, err := Wat2Wasm("(module")

assert.EqualError(t, err, "expected `)`\n --> <anon>:1:8\n |\n 1 | (module\n | ^")
}

0 comments on commit 1dd2c14

Please sign in to comment.