diff options
| author | Mica White <botahamec@outlook.com> | 2026-10-31 11:10:49 -0400 |
|---|---|---|
| committer | Mica White <botahamec@outlook.com> | 2026-10-31 11:10:49 -0400 |
| commit | 264ea48cc8c6dd9c3c9e0fe1a559252863fc9962 (patch) | |
| tree | 84a4a58de14442f4fcfa06bd0d82480508f82759 /examples/state.rs | |
| parent | 7877eca4e8be283e7c51168ee3a3b05d9000f39c (diff) | |
| parent | b45a98a85c776d956a797773acd2f198c06b40ed (diff) | |
Merge branch 'main' into bota-tortuise
Diffstat (limited to 'examples/state.rs')
| -rw-r--r-- | examples/state.rs | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/examples/state.rs b/examples/state.rs new file mode 100644 index 0000000..ecc74fd --- /dev/null +++ b/examples/state.rs @@ -0,0 +1,51 @@ +use anyhow::Result; +use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; + +const WASM: &str = r#" +(module + (import "host" "record" (func $record (param i32) (result i32))) + + (func (export "run") (result i32) + i32.const 20 + call $record + drop + i32.const 22 + call $record)) +"#; + +#[derive(Default)] +struct State { + calls: u32, + total: i32, +} + +// Requires the `parser`, `std`, and `state` features. +// Run with `cargo run --example state` from the repository root. +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + + // State is owned by the Store and is available to its host-function calls. + let mut store = Store::default().with_state(State::default()); + + let record = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| { + // FuncContext accesses the active Store without captured shared state. + let state = ctx.state_mut::<State>().expect("State was added to the store"); + state.calls += 1; + state.total += value; + Ok(state.total) + }); + + // The import definition captures no state and can be reused with other stores. + let mut imports = Imports::new(); + imports.define("host", "record", record); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let run = instance.func::<(), i32>(&store, "run")?; + + assert_eq!(run.call(&mut store, ())?, 42); + + // Host code can inspect the same state after guest execution. + assert_eq!(store.state::<State>().unwrap().calls, 2); + Ok(()) +} |
