MCPcopy Index your code
hub / github.com/explodingcamera/tinywasm / from_untyped

Method from_untyped

crates/tinywasm/src/func.rs:175–199  ·  view source on GitHub ↗

Create a new untyped host function import. ## Example ```rust # fn main() -> tinywasm::Result<()> { # use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; # use tinywasm::types::{FuncType, WasmType, WasmValue}; # let wasm = wat::parse_str(r#" # (module # (import "host" "add_one" (func $add_one (param i32) (result i32))) # (func (export "call") (param i32) (re

(
        store: &mut Store,
        ty: &FuncType,
        func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + 'static,
    )

Source from the content-addressed store, hash-verified

173 /// # }
174 /// ```
175 pub fn from_untyped(
176 store: &mut Store,
177 ty: &FuncType,
178 func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + 'static,
179 ) -> Function {
180 let ty = Arc::new(ty.clone());
181 let host_ty = ty.clone();
182
183 let inner_func = move |ctx: FuncContext<'_>, args: &[WasmValue]| -> Result<Vec<WasmValue>> {
184 let result = func(ctx, args)?;
185 let expected = host_ty.results();
186
187 let valid = result.len() == expected.len()
188 && result.iter().zip(expected).all(|(val, ty)| WasmType::from(val) == *ty);
189
190 if !valid {
191 return Err(crate::Error::InvalidHostFnReturn { expected: Arc::clone(&host_ty), actual: result });
192 }
193
194 Ok(result)
195 };
196
197 let addr = store.add_func(FunctionInstance::Host(Rc::new(Self { func: Box::new(inner_func), ty: ty.clone() })));
198 Function { item: crate::StoreItem::new(store.id(), addr), module_addr: 0, addr, ty }
199 }
200
201 /// Create a new typed host function import.
202 ///

Callers

nothing calls this directly

Calls 4

resultsMethod · 0.80
add_funcMethod · 0.80
lenMethod · 0.45
idMethod · 0.45

Tested by

no test coverage detected