wasmtime_wasi/view.rs
1use crate::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::add_to_linker_sync) and
13/// [`add_to_linker_async`](crate::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::{WasiCtx, ResourceTable, WasiView, IoView, WasiCtxBuilder};
22///
23/// struct MyState {
24/// ctx: WasiCtx,
25/// table: ResourceTable,
26/// }
27///
28/// impl IoView for MyState {
29/// fn table(&mut self) -> &mut ResourceTable { &mut self.table }
30/// }
31/// impl WasiView for MyState {
32/// fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
33/// }
34/// ```
35/// [`Store`]: wasmtime::Store
36/// [`Linker`]: wasmtime::component::Linker
37/// [`ResourceTable`]: wasmtime::component::ResourceTable
38///
39pub trait WasiView: IoView {
40 /// Yields mutable access to the [`WasiCtx`] configuration used for this
41 /// context.
42 fn ctx(&mut self) -> &mut WasiCtx;
43}
44
45impl<T: ?Sized + WasiView> WasiView for &mut T {
46 fn ctx(&mut self) -> &mut WasiCtx {
47 T::ctx(self)
48 }
49}
50
51impl<T: ?Sized + WasiView> WasiView for Box<T> {
52 fn ctx(&mut self) -> &mut WasiCtx {
53 T::ctx(self)
54 }
55}
56
57/// A small newtype wrapper which serves as the basis for implementations of
58/// `Host` WASI traits in this crate.
59///
60/// This type is used as the basis for the implementation of all `Host` traits
61/// generated by `bindgen!` for WASI interfaces. This is used automatically with
62/// [`add_to_linker_sync`](crate::add_to_linker_sync) and
63/// [`add_to_linker_async`](crate::add_to_linker_async).
64///
65/// This type is otherwise provided if you're calling the `add_to_linker`
66/// functions generated by `bindgen!` from the [`bindings`
67/// module](crate::bindings). In this situation you'll want to create a value of
68/// this type in the closures added to a `Linker`.
69#[repr(transparent)]
70pub struct WasiImpl<T>(pub IoImpl<T>);
71
72impl<T: IoView> IoView for WasiImpl<T> {
73 fn table(&mut self) -> &mut ResourceTable {
74 T::table(&mut self.0 .0)
75 }
76}
77impl<T: WasiView> WasiView for WasiImpl<T> {
78 fn ctx(&mut self) -> &mut WasiCtx {
79 T::ctx(&mut self.0 .0)
80 }
81}