Skip to content

Commit

Permalink
Add an Instance method to lookup an exported func (bytecodealliance#69)
Browse files Browse the repository at this point in the history
This avoid having to check both the return from `.GetExport()` and
`.Func()`, and follows after `instance.get_func()` from the Rust API.
  • Loading branch information
fgsch committed Mar 18, 2021
1 parent 295e8ae commit 4d057f4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
12 changes: 12 additions & 0 deletions instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,18 @@ func (i *Instance) GetExport(name string) *Extern {
return i.exports[name]
}

// GetFunc attemps to find a function on this instance by `name`.
//
// May return `nil` if this instance has no function named `name`,
// it is not a function, etc.
func (i *Instance) GetFunc(name string) *Func {
f := i.GetExport(name)
if f == nil {
return nil
}
return f.Func()
}

func (i *Instance) populateExports() {
exports := i.Exports()
for j, ty := range i.Type().Exports() {
Expand Down
40 changes: 40 additions & 0 deletions instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,43 @@ func TestInstanceBad(t *testing.T) {
panic("expected an error")
}
}

func TestInstanceGetFunc(t *testing.T) {
wasm, err := Wat2Wasm(`
(module
(func (export "f") (nop))
(global (export "g") i32 (i32.const 0))
)
`)
if err != nil {
panic(err)
}
store := NewStore(NewEngine())
module, err := NewModule(store.Engine, wasm)
if err != nil {
panic(err)
}
instance, err := NewInstance(store, module, []*Extern{})
if err != nil {
panic(err)
}

f := instance.GetFunc("f")
if f == nil {
panic("expected a function")
}
_, err = f.Call()
if err != nil {
panic(err)
}

f = instance.GetFunc("g")
if f != nil {
panic("expected an error")
}

f = instance.GetFunc("f2")
if f != nil {
panic("expected an error")
}
}

0 comments on commit 4d057f4

Please sign in to comment.