wasmtime_wasi/p3/sockets/
mod.rs

1use crate::TrappableError;
2use crate::p3::bindings::sockets::{ip_name_lookup, types};
3use crate::sockets::{WasiSockets, WasiSocketsView};
4use wasmtime::component::Linker;
5
6mod conv;
7mod host;
8
9pub type SocketResult<T> = Result<T, SocketError>;
10pub type SocketError = TrappableError<types::ErrorCode>;
11
12/// Add all WASI interfaces from this module into the `linker` provided.
13///
14/// This function will add all interfaces implemented by this module to the
15/// [`Linker`], which corresponds to the `wasi:sockets/imports` world supported by
16/// this module.
17///
18/// This is low-level API for advanced use cases,
19/// [`wasmtime_wasi::p3::add_to_linker`](crate::p3::add_to_linker) can be used instead
20/// to add *all* wasip3 interfaces (including the ones from this module) to the `linker`.
21///
22/// # Example
23///
24/// ```
25/// use wasmtime::{Engine, Result, Store, Config};
26/// use wasmtime::component::{Linker, ResourceTable};
27/// use wasmtime_wasi::sockets::{WasiSocketsCtx, WasiSocketsCtxView, WasiSocketsView};
28///
29/// fn main() -> Result<()> {
30///     let mut config = Config::new();
31///     config.async_support(true);
32///     config.wasm_component_model_async(true);
33///     let engine = Engine::new(&config)?;
34///
35///     let mut linker = Linker::<MyState>::new(&engine);
36///     wasmtime_wasi::p3::sockets::add_to_linker(&mut linker)?;
37///     // ... add any further functionality to `linker` if desired ...
38///
39///     let mut store = Store::new(
40///         &engine,
41///         MyState::default(),
42///     );
43///
44///     // ... use `linker` to instantiate within `store` ...
45///
46///     Ok(())
47/// }
48///
49/// #[derive(Default)]
50/// struct MyState {
51///     sockets: WasiSocketsCtx,
52///     table: ResourceTable,
53/// }
54///
55/// impl WasiSocketsView for MyState {
56///     fn sockets(&mut self) -> WasiSocketsCtxView<'_> {
57///         WasiSocketsCtxView {
58///             ctx: &mut self.sockets,
59///             table: &mut self.table,
60///         }
61///     }
62/// }
63/// ```
64pub fn add_to_linker<T>(linker: &mut Linker<T>) -> wasmtime::Result<()>
65where
66    T: WasiSocketsView + 'static,
67{
68    ip_name_lookup::add_to_linker::<_, WasiSockets>(linker, T::sockets)?;
69    types::add_to_linker::<_, WasiSockets>(linker, T::sockets)?;
70    Ok(())
71}