diff --git a/engine/engine.go b/engine/engine.go index faf33c0..89098cc 100644 --- a/engine/engine.go +++ b/engine/engine.go @@ -16,30 +16,36 @@ var ( ErrInvalidMemorySize = errors.New("engine: invalid memory size") ) +// Engine is the main struct for the Mechanoid engine. type Engine struct { Interpreter Interpreter FileStore FileStore Devices []Device } +// NewEngine returns a new Engine. func NewEngine() *Engine { return &Engine{ Devices: []Device{}, } } +// UseInterpreter sets the Interpreter for the Engine. func (e *Engine) UseInterpreter(interp Interpreter) { e.Interpreter = interp } +// UseFileStore sets the FileStore for the Engine. func (e *Engine) UseFileStore(fs FileStore) { e.FileStore = fs } +// AddDevice adds a Device to the Engine. func (e *Engine) AddDevice(d Device) { e.Devices = append(e.Devices, d) } +// Init initializes the Engine by initializing the Interpreter and all Devices. func (e *Engine) Init() error { if e.Interpreter == nil { return ErrNoInterpreter @@ -70,3 +76,25 @@ func (e *Engine) Init() error { } return nil } + +// LoadAndRun loads and runs some WASM code using the current Interpreter. +// It returns an error if the Engine has no Interpreter, or if the Interpreter +// fails to load or run the module. +func (e *Engine) LoadAndRun(code Reader) (Instance, error) { + if e.Interpreter == nil { + return nil, ErrNoInterpreter + } + + mechanoid.Debug("loading WASM code") + if err := e.Interpreter.Load(code); err != nil { + return nil, err + } + + mechanoid.Debug("running WASM code") + ins, err := e.Interpreter.Run() + if err != nil { + return nil, err + } + + return ins, nil +} diff --git a/engine/engine_test.go b/engine/engine_test.go index 0c84ab2..d15bf82 100644 --- a/engine/engine_test.go +++ b/engine/engine_test.go @@ -1,11 +1,17 @@ package engine import ( + "bytes" "testing" + _ "embed" + "github.com/orsinium-labs/wypes" ) +//go:embed tester.wasm +var wasmCode []byte + func TestEngine(t *testing.T) { t.Run("cannot init without interpreter", func(t *testing.T) { e := NewEngine() @@ -23,6 +29,19 @@ func TestEngine(t *testing.T) { t.Errorf("Engine.Init() failed: %v", err) } }) + + t.Run("can LoadAndRun", func(t *testing.T) { + e := NewEngine() + e.UseInterpreter(&mockInterpreter{}) + err := e.Init() + if err != nil { + t.Errorf("Engine.Init() failed: %v", err) + } + + if _, err := e.LoadAndRun(bytes.NewReader(wasmCode)); err != nil { + t.Errorf("Engine.LoadAndRun() failed: %v", err) + } + }) } type mockInterpreter struct { diff --git a/engine/tester.wasm b/engine/tester.wasm new file mode 100755 index 0000000..2728446 Binary files /dev/null and b/engine/tester.wasm differ