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 /crates | |
| parent | 70b4ca7b8effb5b8f61c7a43ea15a77af0db0103 (diff) | |
feat: add custom store state
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates')
| -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 |
3 files changed, 104 insertions, 2 deletions
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(()) +} |
