Skip to main content

WasiRandomNamedView

Trait WasiRandomNamedView 

Source
pub trait WasiRandomNamedView: Send + 'static {
    // Required method
    fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx;
}
Expand description

A trait used to look up a specific wasi:random context for a named import.

This trait is used in conjunction with the named_imports bindings generated for all WASI interfaces. The purpose of this trait is for embedders to define how a NamedId maps to a particular wasi:random context, here returned as WasiRandomCtx. Embedders are responsible for assigning meaning to NamedId values themselves. These IDs are assigned when add_named_to_linker is called, for example, as the lookup argument to that function.

When using add_named_to_linker it’s sufficient to implement this trait for the T in Store<T>. You can also instead implement the WasiNamedView trait for T which implies an implementation of this trait.

When using add_to_linker in the generated bindings::named_imports module then values implementing this live within the T of Store<T>, and be temporarily referenced in WasiCtxNamedView where internally that’ll hold WasiCtxNamedView(&mut your_type).

§Examples

use wasmtime::component::{Linker, Component};
use wasmtime::{Engine, Result};
use wasmtime_wasi::{NamedId, WasiCtxNamedView};
use wasmtime_wasi::random::*;
use std::collections::HashMap;

struct MyStoreState {
    states: HashMap<NamedId, WasiRandomCtx>,
}

fn main() -> Result<()> {
    let engine = Engine::default();
    let mut linker = Linker::new(&engine);
    let component = Component::new(&engine, "(component)")?;
    let mut name_map = HashMap::new();

    wasmtime_wasi::p3::random::add_named_to_linker::<MyStoreState>(
        &mut linker,
        &component,
        |_, name| {
            let len = name_map.len();
            Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))
        },
    )?;
    Ok(())
}

impl WasiRandomNamedView for MyStoreState {
    fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx {
        self.states.get_mut(&id).expect("state for id")
    }
}

Required Methods§

Source

fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx

Looks up the WasiRandomCtx for the given NamedId.

This method will resolve the id specified to a specific random context that is available to be used. Note that this method is specifically infallible meaning that a random context must be returned and this cannot generate a trap or panic or similar.

Embedders are responsible for allocating NamedId and assigning meaning to ids. When a Linker is populated embedders will have the ability to generate a NamedId for all imports found, and then that embedder-allocated id is then passed back here when the corresponding imported function is invoked.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§