### Create New Parser Instance Source: https://docs.rs/tinywasm/0.9.0/tinywasm/parser/struct.Parser.html Instantiate a new Parser with default settings. This is the simplest way to get started with parsing. ```rust pub fn new() -> Parser ``` -------------------------------- ### ModuleInstance::instantiate_no_start Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Instantiate the module in the given store without running the start function. Useful for setup or when the start function needs to be called later. ```APIDOC ## ModuleInstance::instantiate_no_start ### Description Instantiate the module in the given store without running the start function. This allows for manual control over when the module's start function is executed. ### Method POST ### Endpoint `/store/{store_id}/module_instance/instantiate_no_start` (Conceptual) ### Parameters #### Path Parameters - **store_id** (string) - Required - The identifier of the store to instantiate the module in. #### Request Body - **module** (Module) - Required - The module to instantiate. - **imports** (Option) - Optional - Imports to be provided to the new module instance. ### Response #### Success Response (200) - **ModuleInstance** (ModuleInstance) - The newly created module instance. #### Error Response (e.g., 400) - **Error** (string) - Description of the instantiation error. ``` -------------------------------- ### start Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Invoke the start function of the module. Returns `None` if the module has no start function. ```APIDOC ## start ### Description Invoke the start function of the module. Returns `None` if the module has no start function. ### Method ``` pub fn start(&self, store: &mut Store) -> Result> ``` ### Parameters #### Query Parameters - **store** (mut Store) - Description: The store context in which to invoke the start function. ### Response #### Success Response - **Option[()]** - Returns `Some(())` if the start function was invoked successfully, otherwise `None` if no start function exists. ``` -------------------------------- ### start_func Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get the start function of the module. Returns None if the module has no start function. If no start function is specified, also checks for a `_start` function in the exports. ```APIDOC ## start_func ### Description Get the start function of the module. Returns None if the module has no start function. If no start function is specified, also checks for a `_start` function in the exports. ### Method ``` pub fn start_func(&self, store: &Store) -> Result> ``` ### Parameters #### Query Parameters - **store** (Store) - Description: The store context to check for the start function. ### Response #### Success Response - **Option[Function]** - An Option containing the start function if found, otherwise None. ``` -------------------------------- ### Get Module Start Function Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Retrieves the start function of a module instance. Returns None if no start function is specified or if a `_start` function is not found in exports. ```rust let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; assert!(instance.start_func(&store)?.is_some()); ``` -------------------------------- ### Config::memory_backend Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Config.html Gets the current memory backend. ```APIDOC ## Config::memory_backend ### Description Gets the current memory backend. ### Method Instance method ### Parameters None ### Response #### Success Response - **&MemoryBackend** - A reference to the current memory backend. ### Response Example ```json { "example": "&MemoryBackend::SomeBackend" } ``` ``` -------------------------------- ### unwrap_or_else Example Source: https://docs.rs/tinywasm/0.9.0/tinywasm/type.Result.html Demonstrates the use of unwrap_or_else with a closure to provide a default value. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Instantiate Module Without Running Start Function Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Instantiate a module without immediately executing its start function. This is useful for scenarios where you need to interact with the module's state or exports before the start function is invoked, allowing for controlled execution. ```rust let mut store = Store::default(); let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; assert_eq!(instance.global_get(&store, "g")?, 0.into()); instance.start(&mut store)?; assert_eq!(instance.global_get(&store, "g")?, 42.into()); ``` -------------------------------- ### fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/trait.LinearMemory.html Writes all bytes in `src` starting at `addr`, or returns `None` if any byte could not be written. ```APIDOC ## fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> ### Description Writes all bytes in `src` starting at `addr`, or returns `None` if any byte could not be written. ### Method POST (conceptual) ### Endpoint N/A (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **addr** (usize) - Required - The starting address in memory to write to. - **src** (&[u8]) - Required - A byte slice containing the data to write. ### Response #### Success Response - **None** - Indicates all bytes were successfully written. #### Error Response - **None** - Indicates that not all bytes could be written. ``` -------------------------------- ### Invoke Module Start Function Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Invokes the start function of a module instance. This function returns Some(()) if the start function is successfully invoked, and None if the module has no start function. It can also trigger side effects, such as modifying global variables. ```rust let mut store = Store::default(); let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; assert_eq!(instance.global_get(&store, "g")?, 0.into()); assert_eq!(instance.start(&mut store)?, Some(())); assert_eq!(instance.global_get(&store, "g")?, 7.into()); ``` -------------------------------- ### Creating a New Imports Set Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Imports.html Initializes an empty set of imports. This is the starting point before defining any specific import values. ```rust let mut imports = Imports::new(); ``` -------------------------------- ### WasmTupleChain Example Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.WasmTupleChain.html Demonstrates using WasmTupleChain to define and call a function with more than 12 parameters/results. This is useful when a function signature exceeds the direct tuple conversion limit. ```rust type Params = WasmTupleChain<(i32, i32, i32, i32, i32, i32), (i32, i32, i32, i32, i32, i32, i32)>; type Results = WasmTupleChain<(i32, i32, i32, i32, i32, i32), (i32, i32, i32, i32, i32, i32, i32)>; let echo13 = instance.func::(&store, "echo13")?; let result = echo13.call(&mut store, ((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12, 13)).into())?; assert_eq!(result.into_inner(), ((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12, 13))); ``` -------------------------------- ### fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/trait.LinearMemory.html Reads exactly `dst.len()` bytes starting at `addr`. ```APIDOC ## fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> ### Description Reads exactly `dst.len()` bytes starting at `addr`. ### Method GET (conceptual) ### Endpoint N/A (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **addr** (usize) - Required - The starting address in memory to read from. - **dst** (&mut [u8]) - Required - A mutable byte slice to read data into. ### Response #### Success Response - **None** - Indicates that exactly `dst.len()` bytes were successfully read. #### Error Response - **None** - Indicates that exactly `dst.len()` bytes could not be read. ``` -------------------------------- ### Product Implementation for Result Source: https://docs.rs/tinywasm/0.9.0/tinywasm/type.Result.html This example demonstrates how to use the `product` method on an iterator of `Result` types. If any element in the iterator is an `Err`, the entire operation short-circuits and returns that `Err`. Otherwise, it returns the product of all `Ok` values. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### ModuleInstance::export_addr Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get a export by name. Returns the address of the export if found. ```APIDOC ## ModuleInstance::export_addr ### Description Get the address of an exported item by its name. ### Method GET ### Endpoint `/module_instance/{instance_id}/export/{name}` (Conceptual) ### Parameters #### Path Parameters - **instance_id** (string) - Required - The identifier of the module instance. - **name** (string) - Required - The name of the export to retrieve. ### Response #### Success Response (200) - **ExternVal** (ExternVal) - The address of the export. #### Not Found Response (404) - **Error** (string) - Indicates that no export with the given name was found. ``` -------------------------------- ### Get Initial Page Count Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryType.html Retrieves the initial page count from a MemoryType instance. ```rust pub const fn page_count_initial(&self) -> u64 ``` -------------------------------- ### Get Module Instance by Address Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.FuncContext.html Retrieves a module instance from the store using its internal address. Returns an Option containing the ModuleInstance if found. ```rust pub fn get_module_instance( &self, addr: ModuleInstanceAddr, ) -> Option ``` -------------------------------- ### ModuleInstance::memory Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get a memory export by name. Provides access to memory exports. ```APIDOC ## ModuleInstance::memory ### Description Get a memory export by name. This method allows retrieval of memory exports from a module instance. ### Method GET ### Endpoint `/module_instance/{instance_id}/memory/{name}` (Conceptual) ### Parameters #### Path Parameters - **instance_id** (string) - Required - The identifier of the module instance. - **name** (string) - Required - The name of the memory export. ### Response #### Success Response (200) - **Memory** (Memory) - The memory export. #### Error Response (e.g., 400) - **Error** (string) - Description of the error, e.g., if the export is not a memory or not found. ``` -------------------------------- ### ModuleInstance::func_by_index Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get a function by its module-local index. Available on `guest-debug` feature only. Exposes internal functions. ```APIDOC ## ModuleInstance::func_by_index ### Description Get a function by its module-local index. This method is available only when the `guest-debug` feature is enabled and exposes internal module-owned functions, bypassing normal export boundaries. Use with caution as it may affect module behavior. ### Method GET ### Endpoint `/module_instance/{instance_id}/func_by_index/{func_index}` (Conceptual) ### Parameters #### Path Parameters - **instance_id** (string) - Required - The identifier of the module instance. - **func_index** (FuncAddr) - Required - The module-local index of the function. ### Response #### Success Response (200) - **Function** (Function) - The function export identified by its index. #### Error Response (e.g., 400) - **Error** (string) - Description of the error, e.g., if the index is invalid or the feature is not enabled. ``` -------------------------------- ### Creating and Configuring a Config Instance Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Config.html Demonstrates how to create a new Config instance and customize its properties using builder-style methods. This is useful for setting up the interpreter with specific performance or security requirements. ```rust use tinywasm::engine::{Config, FuelPolicy, MemoryBackend, StackConfig}; let config = Config::new() .with_fuel_policy(FuelPolicy::Weighted) .with_value_stack(StackConfig::dynamic(1024, 16 * 1024)) .with_memory_backend(MemoryBackend::paged(64 * 1024)) .with_trap_on_oom(true); assert!(matches!(config.fuel_policy(), FuelPolicy::Weighted)); ``` -------------------------------- ### Create Engine with Custom Configuration Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Engine.html Demonstrates how to create a new Engine instance with custom stack configurations for both value and call stacks. This is useful for fine-tuning the interpreter's resource usage. ```rust use tinywasm::engine::{Config, StackConfig}; use tinywasm::{Engine, Store}; let config = Config::new() .with_value_stack(StackConfig::dynamic(1024, 16 * 1024)) .with_call_stack(StackConfig::fixed(256)); let engine = Engine::new(config); let store = Store::new(engine); ``` -------------------------------- ### Store::new Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Store.html Creates a new Store instance, which holds the global state for WebAssembly programs. It requires an Engine instance to be provided. ```APIDOC ## Store::new ### Description Create a new store. ### Method `new` ### Parameters * `engine` (Engine) - The engine to associate with this store. ### Returns * `Self` - A new Store instance. ``` -------------------------------- ### Sum Implementation for Result Source: https://docs.rs/tinywasm/0.9.0/tinywasm/type.Result.html This example shows the usage of the `sum` method with an iterator yielding `Result` types. Similar to `product`, if any element is an `Err`, the `sum` operation returns that `Err`. Otherwise, it returns the sum of all `Ok` values. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Get Exported Global Value Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Retrieve a specific exported global variable by its name. This example demonstrates accessing the 'answer' global and asserting its value. ```rust let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let ExternItem::Global(global) = instance.extern_item("answer")? else { panic!("expected global export"); }; assert_eq!(global.get(&store)?, 42.into()); ``` -------------------------------- ### fn write(&mut self, addr: usize, src: &[u8]) -> usize Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/trait.LinearMemory.html Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written. Backends may return fewer bytes than requested even when more space is available. This lets non-contiguous backends stop at a natural boundary such as the end of a chunk. ```APIDOC ## fn write(&mut self, addr: usize, src: &[u8]) -> usize ### Description Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written. Backends may return fewer bytes than requested even when more space is available. This lets non-contiguous backends stop at a natural boundary such as the end of a chunk. ### Method POST (conceptual) ### Endpoint N/A (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **addr** (usize) - Required - The starting address in memory to write to. - **src** (&[u8]) - Required - A byte slice containing the data to write. ### Response #### Success Response - **bytes_written** (usize) - The number of bytes actually written from `src`. ``` -------------------------------- ### Instantiate a WebAssembly Module Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Create a ModuleInstance by parsing Wasm bytes, setting up a Store, and instantiating the module. This is the primary way to bring a WebAssembly module into execution context. ```rust let module = tinywasm::parse_bytes(&wasm)?; let mut store = Store::default(); let instance = ModuleInstance::instantiate(&mut store, &module, None)?; ``` -------------------------------- ### Default Value with unwrap_or Source: https://docs.rs/tinywasm/0.9.0/tinywasm/type.Result.html Shows how to get the `Ok` value or a provided default using `unwrap_or`. Note that the default value is eagerly evaluated. ```Rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Get TypeId of MemoryBackend Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.MemoryBackend.html Gets the TypeId of the MemoryBackend. This is part of the Any trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Config::new Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Config.html Creates a new stack configuration with default settings. ```APIDOC ## Config::new ### Description Creates a new stack configuration with default settings. ### Method Associated function (constructor) ### Parameters None ### Response #### Success Response - **Self** (Config) - A new Config instance with default settings. ### Response Example ```json { "example": "Config { ... }" } ``` ``` -------------------------------- ### Creating and Defining Imports Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Imports.html Demonstrates how to create a new Imports object and define various import values like host functions, tables, memories, and globals. It also shows how to link another module instance to the imports. ```rust use tinywasm::types::{GlobalType, MemoryType, TableType, WasmType, WasmValue}; use tinywasm::{Global, HostFunction, Imports, Memory, ModuleInstance, Store, Table}; let mut imports = Imports::new(); let print_i32 = HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, arg: i32| { log::debug!("print_i32: {}", arg); Ok(()) }); let table = Table::new( &mut store, TableType::new(WasmType::RefFunc, 10, Some(20)), WasmValue::default_for(WasmType::RefFunc), )?; let memory = Memory::new( &mut store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)), )?; let global_i32 = Global::new(&mut store, GlobalType::default().with_ty(WasmType::I32), WasmValue::I32(666))?; imports .define("my_module", "print_i32", print_i32) .define("my_module", "table", table) .define("my_module", "memory", memory) .define("my_module", "global_i32", global_i32) .link_module("my_other_module", my_other_instance)?; ``` -------------------------------- ### Config::fuel_policy Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Config.html Gets the current fuel policy. ```APIDOC ## Config::fuel_policy ### Description Gets the current fuel policy. ### Method Instance method ### Parameters None ### Response #### Success Response - **FuelPolicy** - The current fuel policy. ### Response Example ```json { "example": "FuelPolicy::SomePolicy" } ``` ``` -------------------------------- ### impl Any for T Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Memory.html Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method N/A (Method within a trait implementation) ### Endpoint N/A ### Parameters None ### Response - **TypeId**: The unique identifier for the type of `self`. ``` -------------------------------- ### Create Parser with Options Source: https://docs.rs/tinywasm/0.9.0/tinywasm/parser/struct.Parser.html Create a new Parser instance with specific configurations by providing ParserOptions. This allows fine-grained control over the parsing process. ```rust pub fn with_options(options: ParserOptions) -> Parser ``` -------------------------------- ### ModuleInstance::instantiate Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Instantiate the module in the given store. This is the primary method for creating a new module instance. ```APIDOC ## ModuleInstance::instantiate ### Description Instantiate the module in the given store. This method creates a new module instance from a given module and store, optionally including imports. ### Method POST ### Endpoint `/store/{store_id}/module_instance/instantiate` (Conceptual) ### Parameters #### Path Parameters - **store_id** (string) - Required - The identifier of the store to instantiate the module in. #### Request Body - **module** (Module) - Required - The module to instantiate. - **imports** (Option) - Optional - Imports to be provided to the new module instance. ### Response #### Success Response (200) - **ModuleInstance** (ModuleInstance) - The newly created module instance. #### Error Response (e.g., 400) - **Error** (string) - Description of the instantiation error. ``` -------------------------------- ### Get Page Size Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryType.html Retrieves the page size from a MemoryType instance. ```rust pub const fn page_size(&self) -> u64 ``` -------------------------------- ### Get MemoryType Architecture Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryType.html Retrieves the memory architecture from a MemoryType instance. ```rust pub const fn arch(&self) -> MemoryArch ``` -------------------------------- ### Table::size Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Table.html Gets the current number of elements stored in the table. ```APIDOC ## Table::size ### Description Get the current number of elements in the table. ### Method `Table::size(&self, store: &Store) -> Result ### Parameters * `store`: A reference to the `Store`. ### Returns A `Result` containing the current size (number of elements) of the table on success. ``` -------------------------------- ### Engine::default Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Engine.html Creates a new engine with default configuration values. ```APIDOC ## Engine::default ### Description Returns the “default value” for a type. ### Method `default` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters None ### Response #### Success Response (Engine) Returns a new `Engine` instance with default settings. ### Example ```rust let default_engine = Engine::default(); ``` ``` -------------------------------- ### fn read(&self, addr: usize, dst: &mut [u8]) -> usize Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/trait.LinearMemory.html Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read. Backends may return fewer bytes than requested even when more data is available. This lets non-contiguous backends stop at a natural boundary such as the end of a chunk. ```APIDOC ## fn read(&self, addr: usize, dst: &mut [u8]) -> usize ### Description Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read. Backends may return fewer bytes than requested even when more data is available. This lets non-contiguous backends stop at a natural boundary such as the end of a chunk. ### Method GET (conceptual) ### Endpoint N/A (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **addr** (usize) - Required - The starting address in memory to read from. - **dst** (&mut [u8]) - Required - A mutable byte slice to read data into. ### Response #### Success Response - **bytes_read** (usize) - The number of bytes actually read into `dst`. ``` -------------------------------- ### Get LazyLinearMemory length Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.LazyLinearMemory.html Returns the current memory length in bytes. ```rust fn len(&self) -> usize ``` -------------------------------- ### Get Maximum Size Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryType.html Retrieves the maximum memory size from a MemoryType instance. ```rust pub const fn max_size(&self) -> u64 ``` -------------------------------- ### Parser::with_options Source: https://docs.rs/tinywasm/0.9.0/tinywasm/parser/struct.Parser.html Creates a new Parser instance with specified configuration options. ```APIDOC ## Parser::with_options ### Description Create a new parser with explicit options. ### Method `with_options(options: ParserOptions)` ### Parameters #### Request Body - **options** (ParserOptions) - Required - The parser options to use. ``` -------------------------------- ### Parser::new Source: https://docs.rs/tinywasm/0.9.0/tinywasm/parser/struct.Parser.html Creates a new instance of the Parser with default options. ```APIDOC ## Parser::new ### Description Create a new parser instance. ### Method `new()` ### Returns A new `Parser` instance. ``` -------------------------------- ### Get Initial Size Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryType.html Retrieves the initial memory size from a MemoryType instance. ```rust pub const fn initial_size(&self) -> u64 ``` -------------------------------- ### Get MemoryArg offset Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryArg.html Returns the offset value of the MemoryArg. This is a const function. ```rust pub const fn offset(self) -> u64 ``` -------------------------------- ### Create a New Store Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Store.html Creates a new `Store` instance, which is necessary for running WebAssembly modules. It requires an `Engine` instance. ```rust use tinywasm::engine::{Config, StackConfig}; use tinywasm::{Engine, Store}; let engine = Engine::new(Config::new().with_call_stack(StackConfig::dynamic(64, 512))); let store = Store::new(engine); ``` -------------------------------- ### Load and Instantiate WebAssembly Module Source: https://docs.rs/tinywasm/0.9.0/tinywasm/index.html Loads a WebAssembly module from bytes, instantiates it within a store, and calls an exported function. Requires the 'tinywasm' crate. Ensure the WASM file exists at the specified path. ```rust use tinywasm::{ModuleInstance, Store}; // Load a module from bytes let wasm = include_bytes!("../../../examples/wasm/add.wasm"); let module = tinywasm::parse_bytes(wasm)?; // # Create a new store // Stores are used to allocate objects like functions and globals let mut store = Store::default(); // # Instantiate the module // This will allocate the module and its globals into the store // and execute the module's start function. let instance = ModuleInstance::instantiate(&mut store, &module, None)?; // # Get a typed handle to the exported "add" function // Alternatively, you can use `instance.func_untyped` to get an untyped handle // that takes and returns [`WasmValue`]s let func = instance.func::<(i32, i32), i32>(&mut store, "add")?; let res = func.call(&mut store, (1, 2))?; assert_eq!(res, 3); ``` -------------------------------- ### Get Address from ExternRef Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.ExternRef.html Retrieves the optional u32 address associated with the ExternRef. ```rust pub const fn addr(&self) -> Option ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Memory.html Provides the `clone_to_uninit` method for unsafe copy-assignment. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method N/A (Method within a trait implementation) ### Endpoint N/A ### Parameters - **dest** (*mut u8): A mutable pointer to the destination memory. ### Response None ``` -------------------------------- ### Get Maximum Page Count Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryType.html Retrieves the maximum page count from a MemoryType instance. ```rust pub const fn page_count_max(&self) -> u64 ``` -------------------------------- ### Config::with_memory_backend Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Config.html Sets the backend used for runtime memories. ```APIDOC ## Config::with_memory_backend ### Description Sets the backend used for runtime memories. ### Method Instance method ### Parameters - **memory_backend** (MemoryBackend) - Required - The memory backend to set. ### Response #### Success Response - **Self** (Config) - The modified Config instance. ### Response Example ```json { "example": "Config { ... }" } ``` ``` -------------------------------- ### Engine::new Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Engine.html Creates a new WebAssembly interpreter engine with the specified configuration. This engine can be cheaply cloned and shared. ```APIDOC ## Engine::new ### Description Creates a new engine with the given configuration. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **config** (Config) - Required - The configuration for the engine. ### Response #### Success Response (Self) Returns a new `Engine` instance. ### Example ```rust use tinywasm::engine::{Config, StackConfig}; use tinywasm::{Engine, Store}; let config = Config::new() .with_value_stack(StackConfig::dynamic(1024, 16 * 1024)) .with_call_stack(StackConfig::fixed(256)); let engine = Engine::new(config); let store = Store::new(engine); ``` ``` -------------------------------- ### Get Result Types Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.FuncType.html Retrieves the result types of a FuncType instance as a slice of WasmType. ```rust pub fn results(&self) -> &[WasmType] ``` -------------------------------- ### Get Parameter Types Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.FuncType.html Retrieves the parameter types of a FuncType instance as a slice of WasmType. ```rust pub fn params(&self) -> &[WasmType] ``` -------------------------------- ### Call a WebAssembly Function Resumably Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Function.html Initiates a WebAssembly function call and returns a handle for resumable execution. The handle maintains a mutable borrow of the Store until completion. Use `FuncExecution::resume_with_fuel` or `FuncExecution::resume_with_time_budget` to continue execution. ```rust pub fn call_resumable<'store>(&self, store: &'store mut Store, params: &[WasmValue]) -> Result> ``` -------------------------------- ### Create and Manipulate Memory Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Memory.html Demonstrates creating a new memory instance, copying data into it, reading data back, and growing the memory. Ensure the 'std' feature is enabled for MemoryCursor operations. ```rust use tinywasm::types::MemoryType; use tinywasm::{Memory, Store}; let mut store = Store::default(); let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1))?; memory.copy_from_slice(&mut store, 0, b"hi")?; assert_eq!(memory.read_vec(&store, 0, 2)?, b"hi"); assert_eq!(memory.page_count(&store)?, 1); memory.grow(&mut store, 1)?; assert_eq!(memory.page_count(&store)?, 2); ``` -------------------------------- ### ModuleInstance::func_typed_by_index Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get a typed function by its module-local index. Available on `guest-debug` feature only. ```APIDOC ## ModuleInstance::func_typed_by_index ### Description Get a typed function by its module-local index. This method is available only when the `guest-debug` feature is enabled and provides typed access to functions using their internal index. ### Method GET ### Endpoint `/module_instance/{instance_id}/func_typed_by_index/{func_index}` (Conceptual) ### Parameters #### Path Parameters - **instance_id** (string) - Required - The identifier of the module instance. - **func_index** (FuncAddr) - Required - The module-local index of the function. #### Query Parameters - **P** (string) - Required - Type signature for the function's parameters. - **R** (string) - Required - Type signature for the function's return value. ### Response #### Success Response (200) - **FunctionTyped** (FunctionTyped) - The typed function export identified by its index. #### Error Response (e.g., 400) - **Error** (string) - Description of the error, e.g., if the index is invalid, the feature is not enabled, or types do not match. ``` -------------------------------- ### ModuleInstance::func_untyped Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get a function export by name. Returns an untyped function handle. ```APIDOC ## ModuleInstance::func_untyped ### Description Get a function export by name. This method returns an untyped function handle, allowing for dynamic invocation. ### Method GET ### Endpoint `/module_instance/{instance_id}/func_untyped/{name}` (Conceptual) ### Parameters #### Path Parameters - **instance_id** (string) - Required - The identifier of the module instance. - **name** (string) - Required - The name of the function export. ### Response #### Success Response (200) - **Function** (Function) - The untyped function export. #### Error Response (e.g., 400) - **Error** (string) - Description of the error, e.g., if the export is not a function or not found. ``` -------------------------------- ### FuncContext Methods Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.FuncContext.html This section details the methods available on the FuncContext struct for interacting with the WebAssembly environment. ```APIDOC ## FuncContext The context of a host-function call. ### Methods #### `store(&self) -> &Store` Get the store. #### `store_mut(&mut self) -> &mut Store` Get mutable access to the store. #### `module(&self) -> ModuleInstance` Get the module instance. #### `memory(&self, name: &str) -> Result` Get a memory export. #### `extern_item(&self, name: &str) -> Result` Get any exported extern value by name. #### `table(&self, name: &str) -> Result` Get a table export. #### `global_get(&self, name: &str) -> Result` Get the value of a global export. #### `global(&self, name: &str) -> Result` Get a global export. #### `global_set(&mut self, name: &str, value: WasmValue) -> Result<()>` Set the value of a mutable global export. #### `charge_fuel(&mut self, fuel: u32)` Charge additional fuel from the currently running resumable invocation. This is a no-op when the current invocation is not using fuel-based resumption. #### `remaining_fuel(&self) -> u32` Get remaining fuel for the current invocation. Returns `0` when fuel-based resumption is not active. #### `new(store: &'a mut Store, module_addr: ModuleInstanceAddr) -> Self` Create a new host function context. #### `get_module_instance(&self, addr: ModuleInstanceAddr) -> Option` Get a module instance by the internal id #### `id(&self) -> usize` Get the store’s ID (unique per process) ``` -------------------------------- ### Get MemoryArg memory address Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryArg.html Returns the memory address value of the MemoryArg. This is a const function. ```rust pub const fn mem_addr(self) -> u32 ``` -------------------------------- ### Try to create a new PagedMemory Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.PagedMemory.html Use try_new to create a new sparse memory with a specified addressable length and chunk size. Prefer this when memory growth behavior is more critical than absolute read/write speed. ```rust pub fn try_new(len: usize, chunk_size: usize) -> Result ``` -------------------------------- ### Memory::cursor Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Memory.html Creates a cursor positioned at the start of this memory. This method is available only when the `std` feature is enabled. ```APIDOC ## Memory::cursor ### Description Creates a cursor positioned at the start of this memory. ### Availability Available on **crate feature`std`** only. Available with the `std` feature enabled. ### Signature `pub fn cursor<'a>(&self, store: &'a mut Store) -> Result>` ``` -------------------------------- ### Create FuncContext Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.FuncContext.html Creates a new host function context. This constructor requires a mutable reference to the store and the module instance address. ```rust pub const fn new(store: &'a mut Store, module_addr: ModuleInstanceAddr) -> Self ``` -------------------------------- ### Write to LazyLinearMemory Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.LazyLinearMemory.html Writes up to a specified number of bytes starting at an address and returns the number of bytes written. ```rust fn write(&mut self, addr: usize, src: &[u8]) -> usize ``` -------------------------------- ### Table::new Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Table.html Creates a new table instance within a given store, with a specified type and initial value. ```APIDOC ## Table::new ### Description Create a new table in the given store. ### Method `Table::new(store: &mut Store, ty: TableType, init: WasmValue) -> Result ### Parameters * `store`: A mutable reference to the `Store`. * `ty`: The `TableType` defining the table's properties. * `init`: The initial `WasmValue` for the table elements. ### Returns A `Result` containing the newly created `Table` instance on success. ``` -------------------------------- ### Read from LazyLinearMemory Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.LazyLinearMemory.html Reads up to a specified number of bytes starting at an address and returns the number of bytes read. ```rust fn read(&self, addr: usize, dst: &mut [u8]) -> usize ``` -------------------------------- ### Function::call Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Function.html Calls a WebAssembly function with the provided parameters and returns the results. This is a direct invocation. ```APIDOC ## pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result> ### Description Call a function (Invocation). See https://webassembly.github.io/spec/core/exec/modules.html#invocation ### Method `call` ### Parameters * `store`: A mutable reference to the `Store`. * `params`: A slice of `WasmValue` representing the function arguments. ### Returns A `Result` containing a `Vec` on success, representing the function's return values, or an error on failure. ``` -------------------------------- ### Get Default WasmValue for a Type Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/enum.WasmValue.html Returns the default WasmValue for a specified WasmType. This is helpful for initializing values. ```rust pub const fn default_for(ty: WasmType) -> WasmValue ``` -------------------------------- ### ModuleInstance::memory_by_index Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get a memory by its module-local index. Available on `guest-debug` feature only. Exposes internal memories. ```APIDOC ## ModuleInstance::memory_by_index ### Description Get a memory by its module-local index. This method is available only when the `guest-debug` feature is enabled and exposes internal module-owned memories, bypassing normal export boundaries. Use with caution as it may affect module behavior. ### Method GET ### Endpoint `/module_instance/{instance_id}/memory_by_index/{memory_index}` (Conceptual) ### Parameters #### Path Parameters - **instance_id** (string) - Required - The identifier of the module instance. - **memory_index** (MemAddr) - Required - The module-local index of the memory. ### Response #### Success Response (200) - **Memory** (Memory) - The memory export identified by its index. #### Error Response (e.g., 400) - **Error** (string) - Description of the error, e.g., if the index is invalid or the feature is not enabled. ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Module.html Provides an unsafe method to clone data into an uninitialized memory location. This is a nightly-only experimental API. ```APIDOC ## impl CloneToUninit for T ### Description Provides an unsafe method to clone data into an uninitialized memory location. This is a nightly-only experimental API. ### Method #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ``` -------------------------------- ### Get Table Size Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Table.html Returns the current number of elements in the table. Requires an immutable reference to the store. ```rust pub fn size(&self, store: &Store) -> Result ``` -------------------------------- ### fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/trait.LinearMemory.html Fills the range `[addr, addr + len)` with `val`. ```APIDOC ## fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> ### Description Fills the range `[addr, addr + len)` with `val`. ### Method POST (conceptual) ### Endpoint N/A (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **addr** (usize) - Required - The starting address of the range to fill. - **len** (usize) - Required - The number of bytes to fill. - **val** (u8) - Required - The byte value to fill the range with. ### Response #### Success Response - **None** - Indicates the memory range was successfully filled. #### Error Response - **None** - Indicates that the memory range could not be filled. ``` -------------------------------- ### Set Initial Page Count Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/struct.MemoryType.html Returns a new MemoryType with a different initial page count. ```rust pub const fn with_page_count_initial( self, page_count_initial: u64, ) -> MemoryType ``` -------------------------------- ### Get Table Type Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Table.html Retrieves the TableType of an existing table instance. Requires an immutable reference to the store. ```rust pub fn ty(&self, store: &Store) -> Result ``` -------------------------------- ### Get Current Cursor Position Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.MemoryCursor.html Retrieves the current position of the MemoryCursor. This method is available on the MemoryCursor struct. ```rust pub const fn position(&self) -> u64 ``` -------------------------------- ### into_ok Source: https://docs.rs/tinywasm/0.9.0/tinywasm/type.Result.html Returns the contained `Ok` value, but never panics. This is an experimental API. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ### Method `into_ok` ### Parameters None ### Response - **T**: The contained `Ok` value. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### Get Global Value Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Global.html Retrieves the current value of the global instance. This method takes a reference to the store. ```rust pub fn get(&self, store: &Store) -> Result ``` -------------------------------- ### VecMemory::try_new Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.VecMemory.html Tries to create a new memory with a specified number of zero-initialized bytes. This backend is recommended when contiguous access is prioritized over grow performance. ```APIDOC ## `VecMemory::try_new(len: usize) -> Result` ### Description Tries to create a new memory with `len` zero-initialized bytes. This is the simplest backend and typically offers the best read and write throughput due to its contiguous allocation. The tradeoff is the cost of growth, as large grows might require reallocating and copying the entire buffer. ### Method `pub fn try_new(len: usize) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - `Self` (VecMemory) - A new `VecMemory` instance. #### Response Example None ### Error Handling - `Trap` - If memory creation fails. ``` -------------------------------- ### Get Global Type Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Global.html Retrieves the type information of a global instance. This method takes a reference to the store. ```rust pub fn ty(&self, store: &Store) -> Result ``` -------------------------------- ### Default Store Implementation Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.Store.html Provides a default value for the `Store` type. This allows creating a `Store` without explicitly providing an `Engine` in some contexts. ```rust fn default() -> Self ``` -------------------------------- ### Unwrap Err value Source: https://docs.rs/tinywasm/0.9.0/tinywasm/type.Result.html Use `unwrap_err()` to get the contained `Err` value. This method will panic if the `Result` is an `Ok`. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Create VecMemory Backend Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.MemoryBackend.html Uses a contiguous VecMemory for each memory instance. This is typically the fastest option for reads and writes, but large grows can be expensive due to potential reallocation and copying. ```rust pub const fn vec() -> Self ``` -------------------------------- ### Create Paged Memory Backend Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.MemoryBackend.html Uses sparse chunked storage for each memory instance. The chunk_size is the backend chunk size in bytes and is independent of the Wasm page size. This generally makes growth cheaper than Self::vec, but read and write operations may be slightly slower. ```rust pub fn paged(chunk_size: usize) -> Self ``` -------------------------------- ### Get ConstInstruction for WasmValue Source: https://docs.rs/tinywasm/0.9.0/tinywasm/types/enum.WasmValue.html Retrieves the matching ConstInstruction for a given WasmValue. This is useful when working with constant expressions in WebAssembly. ```rust pub fn const_instr(&self) -> Box<[ConstInstruction]> ``` -------------------------------- ### global Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get a global export by name. This method retrieves a global export by its name, providing access to its properties. ```APIDOC ## global ### Description Get a global export by name. ### Method ``` pub fn global(&self, name: &str) -> Result ``` ### Parameters #### Path Parameters - **name** (str) - Description: The name of the global export to retrieve. ### Response #### Success Response - **Global** - The retrieved global export. ``` -------------------------------- ### Config::fmt Source: https://docs.rs/tinywasm/0.9.0/tinywasm/engine/struct.Config.html Formats the Config value using the given formatter. ```APIDOC ## Config::fmt ### Description Formats the Config value using the given formatter. ### Method Instance method (from Debug trait) ### Parameters - **f** (&mut Formatter<'_>) - Required - The formatter to use. ### Response #### Success Response - **Result** - Ok(()) if formatting is successful, Err otherwise. ### Response Example ```json { "example": "Ok(())" } ``` ``` -------------------------------- ### ModuleInstance::id Source: https://docs.rs/tinywasm/0.9.0/tinywasm/struct.ModuleInstance.html Get the module instance’s address. This method returns a unique identifier for the module instance. ```APIDOC ## ModuleInstance::id ### Description Get the module instance’s address. ### Method GET ### Endpoint `/module_instance/{id}` (Conceptual) ### Parameters None ### Response #### Success Response (200) - **ModuleInstanceAddr** (ModuleInstanceAddr) - The address of the module instance. ```