Skip to content

Commit

Permalink
feat: Ability to give WAT to NewModule.
Browse files Browse the repository at this point in the history
  • Loading branch information
Hywan committed Sep 18, 2020
1 parent 6423ad4 commit 5e11202
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions wasmer/module.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
package wasmer

// #include <wasmer_wasm.h>
// #include <stdio.h>
//
// // We can't create a `wasm_byte_vec_t` directly in Go otherwise cgo
// // complains with “Go pointer to Go pointer”. The hack consists at
// // creating the `wasm_byte_vec_t` directly in C.
// own wasm_module_t* go_wasm_module_new(wasm_store_t *store, uint8_t *bytes, size_t bytes_length) {
// own wasm_module_t* to_wasm_module_new(wasm_store_t *store, uint8_t *bytes, size_t bytes_length) {
// wasm_byte_vec_t wasm_bytes;
// wasm_bytes.size = bytes_length;
// wasm_bytes.data = (wasm_byte_t*) bytes;
//
// return wasm_module_new(store, &wasm_bytes);
// return wasm_module_new(store, &wasm_bytes);
// }
import "C"
import (
"runtime"
"unsafe"
)

// A WebAssembly module contains stateless WebAssembly code that has
// already been compiled and can be instantiated multiple times.
// Module contains stateless WebAssembly code that has already been
// compiled and can be instantiated multiple times.
//
// Creates a new WebAssembly Module given the configuration
// in the store.
Expand All @@ -37,25 +38,36 @@ type Module struct {
}

func NewModule(store *Store, bytes []byte) (*Module, error) {
var bytesPtr *C.uint8_t
// If `bytes` contains a Wasm module with the WAT format,
// compile it to Wasm bytes.
// If it does not, it will return the same bytes.
wasmBytes, err := Wat2Wasm(string(bytes))

if len(bytes) > 0 {
bytesPtr = (*C.uint8_t)(unsafe.Pointer(&bytes[0]))
if err != nil {
return nil, err
}

var wasmBytesPtr *C.uint8_t
wasmBytesLength := len(wasmBytes)

if wasmBytesLength > 0 {
wasmBytesPtr = (*C.uint8_t)(unsafe.Pointer(&wasmBytes[0]))
}

module := &Module{
_inner: C.go_wasm_module_new(store.inner(), bytesPtr, C.size_t(len(bytes))),
_inner: C.to_wasm_module_new(store.inner(), wasmBytesPtr, C.size_t(wasmBytesLength)),
}

if module._inner == nil {
return nil, newErrorFromWasmer()
}

runtime.KeepAlive(bytes)
runtime.KeepAlive(wasmBytes)
runtime.SetFinalizer(module, func(module *Module) {
C.wasm_module_delete(module.inner())
})

if module == nil {
return nil, newError()
}

return module, nil
}

Expand Down

0 comments on commit 5e11202

Please sign in to comment.