Skip to content

Instantly share code, notes, and snippets.

@lann
Last active April 23, 2024 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lann/8d85f69ef334051206ee1c7c0897f0f4 to your computer and use it in GitHub Desktop.
Save lann/8d85f69ef334051206ee1c7c0897f0f4 to your computer and use it in GitHub Desktop.
// Example generated bindings
mod bindings {
pub trait Host {
fn host_func(&mut self);
}
pub trait GetHost<T>: Send + Sync + 'static {
fn get_host<'a>(&self, data: &'a mut T) -> impl Host;
}
pub fn add_to_linker_get_host<T>(
linker: &mut wasmtime::component::Linker<T>,
host_getter: impl GetHost<T>,
) -> wasmtime::Result<()> {
let mut inst = linker.instance("foo")?;
inst.func_wrap(
"bar",
move |mut caller: wasmtime::StoreContextMut<'_, T>, (): ()| {
let mut host = host_getter.get_host(caller.data_mut());
host.host_func();
Ok(())
},
)
}
impl<T, U, F> GetHost<T> for F
where
U: Host,
F: Fn(&mut T) -> &mut U + Send + Sync + 'static,
{
fn get_host<'a>(&self, data: &'a mut T) -> impl Host {
self(data)
}
}
impl<T: Host + ?Sized> Host for &mut T {
fn host_func(&mut self) {
(*self).host_func()
}
}
pub fn add_to_linker<T, U>(
linker: &mut wasmtime::component::Linker<T>,
get: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static,
) -> wasmtime::Result<()>
where
U: Host,
{
add_to_linker_get_host(linker, get)
}
}
// Example usage
struct HostImpl;
impl bindings::Host for HostImpl {
fn host_func(&mut self) {}
}
struct HostWrapper<'a> {
host: &'a mut HostImpl,
}
impl<'a> bindings::Host for HostWrapper<'a> {
fn host_func(&mut self) {
self.host.host_func()
}
}
struct HostWrapperGetter;
impl bindings::GetHost<Data> for HostWrapperGetter {
fn get_host<'a>(&self, data: &'a mut Data) -> impl bindings::Host + 'a {
HostWrapper {
host: &mut data.host,
}
}
}
pub struct Data {
host: HostImpl,
}
#[allow(unused)]
pub fn setup(linker: &mut wasmtime::component::Linker<Data>) {
bindings::add_to_linker(linker, |data| &mut data.host).unwrap();
bindings::add_to_linker_get_host(linker, HostWrapperGetter).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment