From 741955aed21c814a0805386a4f9be997c2eb1199 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 14 Sep 2026 12:05:52 +0200 Subject: feat: add custom store state Signed-off-by: Henry --- examples/state.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 examples/state.rs (limited to 'examples/state.rs') 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::().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::().unwrap().calls, 2); + Ok(()) +} -- cgit v1.3.1