Skip to main content

wasmtime_wasi/p3/random/
mod.rs

1mod host;
2
3use crate::p3::Interface;
4use crate::p3::bindings::random::{insecure, insecure_seed, random};
5use crate::random::{WasiRandom, WasiRandomNamed, WasiRandomNamedView, WasiRandomView};
6use crate::{NamedId, WasiCtxNamedView};
7use wasmtime::component::{Component, Linker};
8
9/// Add all WASI interfaces from this module into the `linker` provided.
10///
11/// This function will add all interfaces implemented by this module to the
12/// [`Linker`], which corresponds to the `wasi:random/imports` world supported by
13/// this crate.
14///
15/// This is low-level API for advanced use cases,
16/// [`wasmtime_wasi::p3::add_to_linker`](crate::p3::add_to_linker) can be used instead
17/// to add *all* wasip3 interfaces (including the ones from this module) to the `linker`.
18///
19///
20/// # Example
21///
22/// ```
23/// use wasmtime::{Engine, Result, Store};
24/// use wasmtime::component::Linker;
25/// use wasmtime_wasi::random::{WasiRandomView, WasiRandomCtx};
26///
27/// fn main() -> Result<()> {
28///     let engine = Engine::default();
29///
30///     let mut linker = Linker::<MyState>::new(&engine);
31///     wasmtime_wasi::p3::random::add_to_linker(&mut linker)?;
32///     // ... add any further functionality to `linker` if desired ...
33///
34///     let mut store = Store::new(
35///         &engine,
36///         MyState {
37///             random: WasiRandomCtx::default(),
38///         },
39///     );
40///
41///     // ... use `linker` to instantiate within `store` ...
42///
43///     Ok(())
44/// }
45///
46/// struct MyState {
47///     random: WasiRandomCtx,
48/// }
49///
50/// impl WasiRandomView for MyState {
51///     fn random(&mut self) -> &mut WasiRandomCtx { &mut self.random }
52/// }
53/// ```
54pub fn add_to_linker<T>(linker: &mut Linker<T>) -> wasmtime::Result<()>
55where
56    T: WasiRandomView + 'static,
57{
58    random::add_to_linker::<_, WasiRandom>(linker, T::random)?;
59    insecure::add_to_linker::<_, WasiRandom>(linker, T::random)?;
60    insecure_seed::add_to_linker::<_, WasiRandom>(linker, T::random)?;
61    Ok(())
62}
63
64/// Convenience function to add `wasi:random` interfaces into `linker` for any
65/// named imports of `wasi:random` interfaces.
66///
67/// This function is similar to [`add_to_linker`] except that it's specifically
68/// designed to work with named imports of `wasi:random` interfaces that
69/// components may have. This requires a [`Component`] parameter to be passed in
70/// when populating the [`Linker`] provided to see what the [`Component`]
71/// actually imports.
72///
73/// Like [`add_to_linker`] this is a bit low level and you may want to possibly
74/// invoke [`wasmtime_wasi::p3::add_named_to_linker`] instead. Alternatively if
75/// this isn't low level enough you can additionally invoke bindgen-generated
76/// `add_to_linker` functions directly from within the
77/// [`named_imports::wasi::random`] module.
78///
79/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker
80/// [`named_imports::wasi::random`]: crate::p3::bindings::named_imports::wasi::random
81///
82/// The `lookup` function provided here is invoked for every named import found
83/// for a particular interface. The [`Interface`] given is what's being bound,
84/// and the `&str` argument is the name that the component imports it as. The
85/// embedder can then decide how it would like to allocate a [`NamedId`] for
86/// this import. If `Ok` is returned then the linker is populated with this
87/// name, and imported functions will pass the [`NamedId`] later to the
88/// implementation of [`WasiRandomNamedView`] on `T` when invoked. If `Err` is
89/// returned then the error will cause this entire function to fail and this
90/// function call will return the same error.
91///
92/// # Example
93///
94/// ```
95/// use std::collections::HashMap;
96/// use wasmtime::component::{Component, Linker};
97/// use wasmtime::{Engine, Result, Store, Config};
98/// use wasmtime_wasi::NamedId;
99/// use wasmtime_wasi::random::{WasiRandomCtx, WasiRandomNamedView};
100///
101/// fn main() -> Result<()> {
102///     let engine = Engine::default();
103///     let component = Component::new(&engine, "(component)")?;
104///
105///     let mut linker = Linker::<MyState>::new(&engine);
106///
107///     // ... add default functionality to `linker` as needed ...
108///
109///     // and then additionally fill in any specific named imports `component`
110///     // might have for `wasi:random` interfaces.
111///     let mut name_map = HashMap::new();
112///     wasmtime_wasi::p3::random::add_named_to_linker(&mut linker, &component, |_i, name| {
113///         let len = name_map.len();
114///         Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))
115///     })?;
116///
117///     // Here a `WasiRandomCtx` is allocated per-named-import and will then be
118///     // referred to internally by the [`NamedId`] allocated above. You could
119///     // also use `name_map` to configure each context differently.
120///     let mut my_state = MyState::default();
121///     for _ in 0..name_map.len() {
122///         my_state.contexts.push(WasiRandomCtx::default());
123///     }
124///     let mut store = Store::new(&engine, my_state);
125///     let instance = linker.instantiate(&mut store, &component)?;
126///
127///     // ... work with `instance` ...
128///
129///     Ok(())
130/// }
131///
132/// #[derive(Default)]
133/// struct MyState {
134///     contexts: Vec<WasiRandomCtx>,
135/// }
136///
137/// impl WasiRandomNamedView for MyState {
138///     fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx {
139///         &mut self.contexts[id.0]
140///     }
141/// }
142/// ```
143pub fn add_named_to_linker<T>(
144    linker: &mut Linker<T>,
145    component: &Component,
146    mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,
147) -> wasmtime::Result<()>
148where
149    T: WasiRandomNamedView + 'static,
150{
151    use crate::p3::bindings::named_imports::wasi::random::{insecure, insecure_seed, random};
152    random::add_to_linker::<_, WasiRandomNamed<T>>(
153        linker,
154        component,
155        |name| lookup(Interface::RandomRandom, name),
156        |x| WasiCtxNamedView(x),
157    )?;
158    insecure::add_to_linker::<_, WasiRandomNamed<T>>(
159        linker,
160        component,
161        |name| lookup(Interface::RandomInsecure, name),
162        |x| WasiCtxNamedView(x),
163    )?;
164    insecure_seed::add_to_linker::<_, WasiRandomNamed<T>>(
165        linker,
166        component,
167        |name| lookup(Interface::RandomInsecureSeed, name),
168        |x| WasiCtxNamedView(x),
169    )?;
170    Ok(())
171}