wasmtime_wasi/p2/view.rs
1use crate::p2::ctx::WasiCtx;
2use wasmtime::component::ResourceTable;
3pub use wasmtime_wasi_io::{IoImpl, IoView};
4
5/// A trait which provides access to the [`WasiCtx`] inside the embedder's `T`
6/// of [`Store<T>`][`Store`].
7///
8/// This crate's WASI Host implementations depend on the contents of
9/// [`WasiCtx`]. The `T` type [`Store<T>`][`Store`] is defined in each
10/// embedding of Wasmtime. These implementations are connected to the
11/// [`Linker<T>`][`Linker`] by the
12/// [`add_to_linker_sync`](crate::p2::add_to_linker_sync) and
13/// [`add_to_linker_async`](crate::p2::add_to_linker_async) functions.
14///
15/// The [`WasiView`] trait implies the [`IoView`] trait, so each `T` must
16/// also contain a [`ResourceTable`] and impl `IoView`.
17///
18/// # Example
19///
20/// ```
21/// use wasmtime_wasi::ResourceTable;
22/// use wasmtime_wasi::p2::{WasiCtx, WasiView, IoView, WasiCtxBuilder};
23///
24/// struct MyState {
25/// ctx: WasiCtx,
26/// table: ResourceTable,
27/// }
28///
29/// impl IoView for MyState {
30/// fn table(&mut self) -> &mut ResourceTable { &mut self.table }
31/// }
32/// impl WasiView for MyState {
33/// fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
34/// }
35/// ```
36/// [`Store`]: wasmtime::Store
37/// [`Linker`]: wasmtime::component::Linker
38/// [`ResourceTable`]: wasmtime::component::ResourceTable
39///
40pub trait WasiView: IoView {
41 /// Yields mutable access to the [`WasiCtx`] configuration used for this
42 /// context.
43 fn ctx(&mut self) -> &mut WasiCtx;
44}
45
46impl<T: ?Sized + WasiView> WasiView for &mut T {
47 fn ctx(&mut self) -> &mut WasiCtx {
48 T::ctx(self)
49 }
50}
51
52impl<T: ?Sized + WasiView> WasiView for Box<T> {
53 fn ctx(&mut self) -> &mut WasiCtx {
54 T::ctx(self)
55 }
56}
57
58/// A small newtype wrapper which serves as the basis for implementations of
59/// `Host` WASI traits in this crate.
60///
61/// This type is used as the basis for the implementation of all `Host` traits
62/// generated by `bindgen!` for WASI interfaces. This is used automatically with
63/// [`add_to_linker_sync`](crate::p2::add_to_linker_sync) and
64/// [`add_to_linker_async`](crate::p2::add_to_linker_async).
65///
66/// This type is otherwise provided if you're calling the `add_to_linker`
67/// functions generated by `bindgen!` from the [`bindings`
68/// module](crate::p2::bindings). In this situation you'll want to create a value of
69/// this type in the closures added to a `Linker`.
70#[repr(transparent)]
71pub struct WasiImpl<T>(pub IoImpl<T>);
72
73impl<T: IoView> IoView for WasiImpl<T> {
74 fn table(&mut self) -> &mut ResourceTable {
75 T::table(&mut self.0 .0)
76 }
77}
78impl<T: WasiView> WasiView for WasiImpl<T> {
79 fn ctx(&mut self) -> &mut WasiCtx {
80 T::ctx(&mut self.0 .0)
81 }
82}