diff options
| author | Henry <mail@henrygressmann.de> | 2026-09-14 12:05:52 +0200 |
|---|---|---|
| committer | Henry <mail@henrygressmann.de> | 2026-09-14 12:05:52 +0200 |
| commit | 741955aed21c814a0805386a4f9be997c2eb1199 (patch) | |
| tree | b3510eb2d314e5a096aa1a04babab37ac8028234 | |
| parent | 70b4ca7b8effb5b8f61c7a43ea15a77af0db0103 (diff) | |
feat: add custom store state
Signed-off-by: Henry <mail@henrygressmann.de>
| -rw-r--r-- | CHANGELOG.md | 1 | ||||
| -rw-r--r-- | README.md | 1 | ||||
| -rw-r--r-- | crates/tinywasm/Cargo.toml | 7 | ||||
| -rw-r--r-- | crates/tinywasm/src/store/mod.rs | 63 | ||||
| -rw-r--r-- | crates/tinywasm/tests/store_state.rs | 36 | ||||
| -rw-r--r-- | examples/doom/Cargo.toml | 1 | ||||
| -rw-r--r-- | examples/doom/src/main.rs | 2 | ||||
| -rw-r--r-- | examples/doom/src/runtime.rs | 305 | ||||
| -rw-r--r-- | examples/rust.rs | 2 | ||||
| -rwxr-xr-x | examples/rust/build.sh | 4 | ||||
| -rw-r--r-- | examples/state.rs | 51 |
11 files changed, 302 insertions, 171 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index a37655e..dc59e5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ This release adds garbage collection and typed function reference support, singl ### Added +- Optional store-owned host state through `Store::with_state`, `Store::state`, and `Store::state_mut`. - Support for the typed function references, garbage collection, exception handling, and compact import section proposals. - `ResourceLimiter` callbacks for memory and table allocation or growth. - A default-enabled `validate` Cargo feature and a parser option to skip WebAssembly validation. @@ -56,6 +56,7 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. - **`log`:** Enables integration with the `log` crate. Enabled by default. - **`send`:** Makes stores and store-local handles movable across threads. +- **`state`:** Adds store-owned host state for access from host callbacks. - **`portable-atomic`:** Supports targets without native atomic compare-and-swap. - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. - **`debug`:** Derives `Debug` for runtime types. Enabled by default. diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index d59d3dd..15b151c 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -11,7 +11,7 @@ keywords.workspace = true categories.workspace = true [package.metadata.docs.rs] -features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "debug", "guest-debug"] +features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "state", "debug", "guest-debug"] rustdoc-args = ["--cfg", "docsrs"] [lib] @@ -90,7 +90,7 @@ wat.workspace = true [features] default = ["full", "std"] -full = ["archive", "debug", "parallel-parser", "parser", "validate"] +full = ["archive", "debug", "parallel-parser", "parser", "state", "validate"] log = ["dep:log", "tinywasm-parser?/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] @@ -98,6 +98,9 @@ std = ["tinywasm-parser?/std", "tinywasm-types/std"] # make stores, instances, references, and host callbacks movable across threads send = [] +# store host state for access from host callbacks +state = [] + # support for parsing WebAssembly parser = ["dep:tinywasm-parser"] diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index e157240..ed9b4f0 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,4 +1,8 @@ +#[cfg(feature = "state")] +use alloc::collections::BTreeMap; use alloc::{boxed::Box, format, vec::Vec}; +#[cfg(feature = "state")] +use core::any::{Any, TypeId}; use core::hint::cold_path; use tinywasm_types::*; @@ -110,6 +114,25 @@ pub trait ResourceLimiter: Send + Sync { } } +/// A value stored as host state. +#[doc(hidden)] +#[cfg(all(feature = "state", not(feature = "send")))] +pub trait StoreState: Any {} +#[cfg(all(feature = "state", not(feature = "send")))] +impl<T: Any> StoreState for T {} + +/// A value stored as host state. +#[doc(hidden)] +#[cfg(all(feature = "state", feature = "send"))] +pub trait StoreState: Any + Send {} +#[cfg(all(feature = "state", feature = "send"))] +impl<T: Any + Send> StoreState for T {} + +#[cfg(all(feature = "state", not(feature = "send")))] +type StoredState = dyn Any; +#[cfg(all(feature = "state", feature = "send"))] +type StoredState = dyn Any + Send; + /// Runtime state used by WebAssembly instances and host functions. /// /// ## Example @@ -133,6 +156,8 @@ pub struct Store { pub(crate) call_stack: CallStack, pub(crate) value_stack: ValueStack, value_scratch: ValueScratch, + #[cfg(feature = "state")] + host_state: BTreeMap<TypeId, Box<StoredState>>, } #[derive(Default)] @@ -238,9 +263,47 @@ impl Store { engine, execution_fuel: 0, execution_active: false, + #[cfg(feature = "state")] + host_state: BTreeMap::new(), } } + /// Adds host state to this store. + /// + /// Host callbacks can access the value through [`Store::state`] and + /// [`Store::state_mut`]. If state of the same type already exists, this + /// method replaces it. + /// + /// # Example + /// + /// ```rust + /// use tinywasm::Store; + /// + /// struct AppState { + /// requests: usize, + /// } + /// + /// let store = Store::default().with_state(AppState { requests: 0 }); + /// assert_eq!(store.state::<AppState>().unwrap().requests, 0); + /// ``` + #[cfg(feature = "state")] + pub fn with_state<T: StoreState>(mut self, state: T) -> Self { + self.host_state.insert(TypeId::of::<T>(), Box::new(state)); + self + } + + /// Get host state. + #[cfg(feature = "state")] + pub fn state<T: StoreState>(&self) -> Option<&T> { + self.host_state.get(&TypeId::of::<T>()).and_then(|state| state.downcast_ref()) + } + + /// Get mutable access to host state. + #[cfg(feature = "state")] + pub fn state_mut<T: StoreState>(&mut self) -> Option<&mut T> { + self.host_state.get_mut(&TypeId::of::<T>()).and_then(|state| state.downcast_mut()) + } + pub(crate) const fn id(&self) -> StoreId { self.id } diff --git a/crates/tinywasm/tests/store_state.rs b/crates/tinywasm/tests/store_state.rs new file mode 100644 index 0000000..573c250 --- /dev/null +++ b/crates/tinywasm/tests/store_state.rs @@ -0,0 +1,36 @@ +#![cfg(feature = "state")] + +use tinywasm::types::WasmValue; +use tinywasm::{HostFunction, Store}; + +struct Counter(i32); +struct Label(&'static str); + +#[test] +fn stores_state_by_type() { + let mut store = Store::default().with_state(Counter(1)).with_state(Label("first")).with_state(Counter(2)); + + assert_eq!(store.state::<Counter>().unwrap().0, 2); + assert_eq!(store.state::<Label>().unwrap().0, "first"); + + store.state_mut::<Counter>().unwrap().0 = 3; + assert_eq!(store.state::<Counter>().unwrap().0, 3); +} + +#[test] +fn host_function_mutates_store_state() -> tinywasm::Result<()> { + let mut store = Store::default().with_state(Counter(40)); + let function = HostFunction::from(|mut ctx, value: i32| { + let counter = ctx.state_mut::<Counter>().expect("counter state"); + counter.0 += value; + Ok(counter.0) + }) + .instantiate(&mut store)?; + + let mut results = [WasmValue::I32(0)]; + function.call(&mut store, &[WasmValue::I32(2)], &mut results)?; + + assert_eq!(results, [WasmValue::I32(42)]); + assert_eq!(store.state::<Counter>().unwrap().0, 42); + Ok(()) +} diff --git a/examples/doom/Cargo.toml b/examples/doom/Cargo.toml index abec73d..c096db6 100644 --- a/examples/doom/Cargo.toml +++ b/examples/doom/Cargo.toml @@ -14,6 +14,7 @@ softbuffer = "0.4" tinywasm = { path = "../../crates/tinywasm", features = [ "archive", "canonicalize-nans", + "state", "debug", "log", "parallel-parser", diff --git a/examples/doom/src/main.rs b/examples/doom/src/main.rs index c5e49b5..a8e98ef 100644 --- a/examples/doom/src/main.rs +++ b/examples/doom/src/main.rs @@ -129,7 +129,7 @@ impl ApplicationHandler for DoomApp { window.request_redraw(); } - if self.runtime.host_state.lock().unwrap().exit_code.is_some() { + if self.runtime.exited() { event_loop.exit(); } } diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs index 2ad02ae..745e3bd 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -2,7 +2,6 @@ use std::collections::BTreeMap; use std::fs::{File, OpenOptions, create_dir_all}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::Result; @@ -20,15 +19,13 @@ pub struct Runtime { key_up: tinywasm::FunctionTyped<i32, ()>, memory: tinywasm::Memory, framebuffer_bytes: Vec<u8>, - pub host_state: Arc<Mutex<HostState>>, } impl Runtime { pub fn new(wad_path: PathBuf, guest_path: PathBuf) -> Result<Self> { let module = tinywasm::parse_file(&guest_path)?; - let mut store = Store::default(); - let host_state = Arc::new(Mutex::new(HostState::new(wad_path))); - let imports = build_imports(host_state.clone()); + let mut store = Store::default().with_state(HostState::new(wad_path)); + let imports = build_imports(); let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let wad_path_buf = instance.func::<(), i32>(&store, "tinywasm_doom_wad_path_buf")?; @@ -40,7 +37,7 @@ impl Runtime { let memory = instance.memory("memory")?; let buf_ptr = wad_path_buf.call(&mut store, ())? as usize; - let wad_path_string = host_state.lock().unwrap().wad_path.to_string_lossy().into_owned(); + let wad_path_string = store.state::<HostState>().unwrap().wad_path.to_string_lossy().into_owned(); memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?; init.call(&mut store, ())?; @@ -55,7 +52,6 @@ impl Runtime { key_up, memory, framebuffer_bytes: vec![0; width * height * 4], - host_state, }) } @@ -84,15 +80,19 @@ impl Runtime { self.key_up.call(&mut self.store, key)?; Ok(()) } + + pub fn exited(&self) -> bool { + self.store.state::<HostState>().unwrap().exit_code.is_some() + } } pub struct HostState { - pub wad_path: PathBuf, + wad_path: PathBuf, runtime_dir: PathBuf, start: Instant, files: BTreeMap<i32, File>, next_file: i32, - pub exit_code: Option<i32>, + exit_code: Option<i32>, } impl HostState { @@ -160,183 +160,158 @@ impl HostState { } } -fn build_imports(state: Arc<Mutex<HostState>>) -> Imports { +fn build_imports() -> Imports { let mut imports = Imports::new(); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_open", - HostFunction::from(move |ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| { - let memory = ctx.memory("memory")?; - let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?; - let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?; - let filename = filename.to_string_lossy(); - let mode = mode.to_string_lossy(); - let mut state = state.lock().unwrap(); - let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) { - state.wad_path.clone() - } else { - state.resolve_path(&filename) - }; + imports.define( + IMPORT_MODULE, + "host_open", + HostFunction::from(|mut ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| { + let memory = ctx.memory("memory")?; + let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?; + let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?; + let filename = filename.to_string_lossy(); + let mode = mode.to_string_lossy(); + let state = ctx.state_mut::<HostState>().unwrap(); + let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) { + state.wad_path.clone() + } else { + state.resolve_path(&filename) + }; - if path.is_dir() { - log::debug!("guest open rejected directory: path={} mode={}", path.display(), mode); + if path.is_dir() { + log::debug!("guest open rejected directory: path={} mode={}", path.display(), mode); + return Ok(-1); + } + + let file = match HostState::open_mode_options(&mode).open(&path) { + Ok(file) => file, + Err(err) => { + log::debug!("guest open failed: path={} mode={} err={err}", path.display(), mode); return Ok(-1); } + }; - let file = match HostState::open_mode_options(&mode).open(&path) { - Ok(file) => file, - Err(err) => { - log::debug!("guest open failed: path={} mode={} err={err}", path.display(), mode); - return Ok(-1); - } - }; - - let handle = state.next_file; - state.next_file += 1; - state.files.insert(handle, file); - Ok(handle) - }), - ); - } + let handle = state.next_file; + state.next_file += 1; + state.files.insert(handle, file); + Ok(handle) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_close", - HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - state.lock().unwrap().files.remove(&handle); - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_close", + HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| { + ctx.state_mut::<HostState>().unwrap().files.remove(&handle); + Ok(()) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_read", - HostFunction::from(move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { - let mut state = state.lock().unwrap(); + imports.define( + IMPORT_MODULE, + "host_read", + HostFunction::from(|mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + let mut buffer = vec![0; count.max(0) as usize]; + let read = { + let state = ctx.state_mut::<HostState>().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(0); }; - let mut buffer = vec![0; count.max(0) as usize]; - let read = file.read(&mut buffer).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - ctx.memory("memory")?.copy_from_slice(ctx.store_mut(), buf_ptr as usize, &buffer[..read])?; - Ok(read as i32) - }), - ); - } + file.read(&mut buffer).map_err(|err| tinywasm::Error::Other(err.to_string()))? + }; + ctx.memory("memory")?.copy_from_slice(ctx.store_mut(), buf_ptr as usize, &buffer[..read])?; + Ok(read as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_write", - HostFunction::from(move |ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { - let data = ctx.memory("memory")?.read_vec(ctx.store(), buf_ptr as usize, count.max(0) as usize)?; - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(-1); - }; - let written = file.write(&data).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - Ok(written as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_write", + HostFunction::from(|mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + let data = ctx.memory("memory")?.read_vec(ctx.store(), buf_ptr as usize, count.max(0) as usize)?; + let state = ctx.state_mut::<HostState>().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(-1); + }; + let written = file.write(&data).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + Ok(written as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_seek", - HostFunction::from(move |_ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| { - let seek_from = match origin { - 0 => SeekFrom::Start(offset.max(0) as u64), - 1 => SeekFrom::Current(offset as i64), - 2 => SeekFrom::End(offset as i64), - _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))), - }; - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(-1); - }; - let pos = file.seek(seek_from).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - Ok(pos.min(i32::MAX as u64) as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_seek", + HostFunction::from(|mut ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| { + let seek_from = match origin { + 0 => SeekFrom::Start(offset.max(0) as u64), + 1 => SeekFrom::Current(offset as i64), + 2 => SeekFrom::End(offset as i64), + _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))), + }; + let state = ctx.state_mut::<HostState>().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(-1); + }; + let pos = file.seek(seek_from).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + Ok(pos.min(i32::MAX as u64) as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_tell", - HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(-1); - }; - let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; - Ok(pos.min(i32::MAX as u64) as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_tell", + HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| { + let state = ctx.state_mut::<HostState>().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(-1); + }; + let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; + Ok(pos.min(i32::MAX as u64) as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_eof", - HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(1); - }; - let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; - let len = file.metadata().map_err(|err| tinywasm::Error::Other(err.to_string()))?.len(); - Ok((pos >= len) as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_eof", + HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| { + let state = ctx.state_mut::<HostState>().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(1); + }; + let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; + let len = file.metadata().map_err(|err| tinywasm::Error::Other(err.to_string()))?.len(); + Ok((pos >= len) as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_gettime", - HostFunction::from(move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { - let elapsed = state.lock().unwrap().start.elapsed() + Duration::from_secs(1); - let sec = elapsed.as_secs().min(i32::MAX as u64) as i32; - let usec = elapsed.subsec_micros() as i32; - let memory = ctx.memory("memory")?; - memory.copy_from_slice(ctx.store_mut(), sec_ptr as usize, &sec.to_le_bytes())?; - memory.copy_from_slice(ctx.store_mut(), usec_ptr as usize, &usec.to_le_bytes())?; - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_gettime", + HostFunction::from(|mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { + let elapsed = ctx.state::<HostState>().unwrap().start.elapsed() + Duration::from_secs(1); + let sec = elapsed.as_secs().min(i32::MAX as u64) as i32; + let usec = elapsed.subsec_micros() as i32; + let memory = ctx.memory("memory")?; + memory.copy_from_slice(ctx.store_mut(), sec_ptr as usize, &sec.to_le_bytes())?; + memory.copy_from_slice(ctx.store_mut(), usec_ptr as usize, &usec.to_le_bytes())?; + Ok(()) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_exit", - HostFunction::from(move |_ctx: FuncContext<'_>, code: i32| { - state.lock().unwrap().exit_code = Some(code); - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_exit", + HostFunction::from(|mut ctx: FuncContext<'_>, code: i32| { + ctx.state_mut::<HostState>().unwrap().exit_code = Some(code); + Ok(()) + }), + ); imports.define( IMPORT_MODULE, "host_print", - HostFunction::from(move |ctx: FuncContext<'_>, ptr: i32| { + HostFunction::from(|ctx: FuncContext<'_>, ptr: i32| { let text = ctx.memory("memory")?.read_cstring_until_null(ctx.store(), ptr as usize, 4096)?; log::info!("guest: {}", text.to_string_lossy()); Ok(()) diff --git a/examples/rust.rs b/examples/rust.rs index 77ba428..58fd11e 100644 --- a/examples/rust.rs +++ b/examples/rust.rs @@ -87,7 +87,7 @@ fn tinywasm() -> Result<()> { } fn tinywasm_no_std() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?; + let module = tinywasm::parse_file("./examples/rust/out/tinywasm-no-std.wasm")?; let mut store = Store::default(); let mut imports = Imports::new(); diff --git a/examples/rust/build.sh b/examples/rust/build.sh index aa60d33..e19b8b8 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -18,8 +18,8 @@ cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \ # build no_std RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm-no-std --no-default-features -cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" -wasm-opt "$dest_dir/tinywasm_no_std.wasm" -o "$dest_dir/tinywasm_no_std.opt.wasm" -O3 $wasmopt_features +cp "$out_dir/tinywasm-no-std.wasm" "$dest_dir/" +wasm-opt "$dest_dir/tinywasm-no-std.wasm" -o "$dest_dir/tinywasm-no-std.opt.wasm" -O3 $wasmopt_features for bin in "${bins[@]}"; do RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=std,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin "$bin" 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(()) +} |
