pub fn wrap<T, Params, Results>(
        mut store: impl AsContextMut<Data = T>,
        func: impl IntoFunc<T, Params, Results>,
    ) -> Func {
        let mut store = store.as_context_mut().opaque();
        // part of this unsafety is about matching the `T` to a `Store<T>`,
        // which is done through the `AsContextMut` bound above.
        unsafe {
            let host = HostFunc::wrap(store.engine(), func);
            host.into_func(&mut store)
        }
    }
/// Creates a new `Func` from the given Rust closure.
///
/// This function will create a new `Func` which, when called, will
/// execute the given Rust closure. Unlike [`Func::new`] the target
/// function being called is known statically so the type signature can
/// be inferred. Rust types will map to WebAssembly types as follows:
///
/// | Rust Argument Type  | WebAssembly Type |
/// |---------------------|------------------|
/// | `i32`               | `i32`            |
/// | `u32`               | `i32`            |
/// | `i64`               | `i64`            |
/// | `u64`               | `i64`            |
/// | `f32`               | `f32`            |
/// | `f64`               | `f64`            |
/// | (not supported)     | `v128`           |
/// | `Option<Func>`      | `funcref`        |
/// | `Option<ExternRef>` | `externref`      |
///
/// Any of the Rust types can be returned from the closure as well, in
/// addition to some extra types
///
/// | Rust Return Type  | WebAssembly Return Type | Meaning               |
/// |-------------------|-------------------------|-----------------------|
/// | `()`              | nothing                 | no return value       |
/// | `T`               | `T`                     | a single return value |
/// | `(T1, T2, ...)`   | `T1 T2 ...`             | multiple returns      |
///
/// Note that all return types can also be wrapped in `Result<_, Trap>` to
/// indicate that the host function can generate a trap as well as possibly
/// returning a value.
///
/// Finally you can also optionally take [`Caller`] as the first argument of
/// your closure. If inserted then you're able to inspect the caller's
/// state, for example the [`Memory`](crate::Memory) it has exported so you
/// can read what pointers point to.
///
/// Note that when using this API, the intention is to create as thin of a
/// layer as possible for when WebAssembly calls the function provided. With
/// sufficient inlining and optimization the WebAssembly will call straight
/// into `func` provided, with no extra fluff entailed.
///
/// # Why `Send + Sync + 'static`?
///
/// All host functions defined in a [`Store`](crate::Store) (including
/// those from [`Func::new`] and other constructors) require that the
/// `func` provided is `Send + Sync + 'static`. Additionally host functions
/// always are `Fn` as opposed to `FnMut` or `FnOnce`. This can at-a-glance
/// feel restrictive since the closure cannot close over as many types as
/// before. The reason for this, though, is to ensure that
/// [`Store<T>`](crate::Store) can implement both the `Send` and `Sync`
/// traits.
///
/// Fear not, however, because this isn't as restrictive as it seems! Host
/// functions are provided a [`Caller<'_, T>`](crate::Caller) argument which
/// allows access to the host-defined data within the
/// [`Store`](crate::Store). The `T` type is not required to be any of
/// `Send`, `Sync`, or `'static`! This means that you can store whatever
/// you'd like in `T` and have it accessible by all host functions.
/// Additionally mutable access to `T` is allowed through
/// [`Caller::data_mut`].
///
/// Most host-defined [`Func`] values provide closures that end up not
/// actually closing over any values. These zero-sized types will use the
/// context from [`Caller`] for host-defined information.
///
/// # Examples
///
/// First up we can see how simple wasm imports can be implemented, such
/// as a function that adds its two arguments and returns the result.
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::<()>::default();
/// let add = Func::wrap(&mut store, |a: i32, b: i32| a + b);
/// let module = Module::new(
///     store.engine(),
///     r#"
///         (module
///             (import "" "" (func $add (param i32 i32) (result i32)))
///             (func (export "foo") (param i32 i32) (result i32)
///                 local.get 0
///                 local.get 1
///                 call $add))
///     "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[add.into()])?;
/// let foo = instance.get_typed_func::<(i32, i32), i32, _>(&mut store, "foo")?;
/// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
/// # Ok(())
/// # }
/// ```
///
/// We can also do the same thing, but generate a trap if the addition
/// overflows:
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::<()>::default();
/// let add = Func::wrap(&mut store, |a: i32, b: i32| {
///     match a.checked_add(b) {
///         Some(i) => Ok(i),
///         None => Err(Trap::new("overflow")),
///     }
/// });
/// let module = Module::new(
///     store.engine(),
///     r#"
///         (module
///             (import "" "" (func $add (param i32 i32) (result i32)))
///             (func (export "foo") (param i32 i32) (result i32)
///                 local.get 0
///                 local.get 1
///                 call $add))
///     "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[add.into()])?;
/// let foo = instance.get_typed_func::<(i32, i32), i32, _>(&mut store, "foo")?;
/// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
/// assert!(foo.call(&mut store, (i32::max_value(), 1)).is_err());
/// # Ok(())
/// # }
/// ```
///
/// And don't forget all the wasm types are supported!
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::<()>::default();
/// let debug = Func::wrap(&mut store, |a: i32, b: u32, c: f32, d: i64, e: u64, f: f64| {
///
///     println!("a={}", a);
///     println!("b={}", b);
///     println!("c={}", c);
///     println!("d={}", d);
///     println!("e={}", e);
///     println!("f={}", f);
/// });
/// let module = Module::new(
///     store.engine(),
///     r#"
///         (module
///             (import "" "" (func $debug (param i32 i32 f32 i64 i64 f64)))
///             (func (export "foo")
///                 i32.const -1
///                 i32.const 1
///                 f32.const 2
///                 i64.const -3
///                 i64.const 3
///                 f64.const 4
///                 call $debug))
///     "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[debug.into()])?;
/// let foo = instance.get_typed_func::<(), (), _>(&mut store, "foo")?;
/// foo.call(&mut store, ())?;
/// # Ok(())
/// # }
/// ```
///
/// Finally if you want to get really fancy you can also implement
/// imports that read/write wasm module's memory
///
/// ```
/// use std::str;
///
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::default();
/// let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
///     let mem = match caller.get_export("memory") {
///         Some(Extern::Memory(mem)) => mem,
///         _ => return Err(Trap::new("failed to find host memory")),
///     };
///     let data = mem.data(&caller)
///         .get(ptr as u32 as usize..)
///         .and_then(|arr| arr.get(..len as u32 as usize));
///     let string = match data {
///         Some(data) => match str::from_utf8(data) {
///             Ok(s) => s,
///             Err(_) => return Err(Trap::new("invalid utf-8")),
///         },
///         None => return Err(Trap::new("pointer/length out of bounds")),
///     };
///     assert_eq!(string, "Hello, world!");
///     println!("{}", string);
///     Ok(())
/// });
/// let module = Module::new(
///     store.engine(),
///     r#"
///         (module
///             (import "" "" (func $log_str (param i32 i32)))
///             (func (export "foo")
///                 i32.const 4   ;; ptr
///                 i32.const 13  ;; len
///                 call $log_str)
///             (memory (export "memory") 1)
///             (data (i32.const 4) "Hello, world!"))
///     "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
/// let foo = instance.get_typed_func::<(), (), _>(&mut store, "foo")?;
/// foo.call(&mut store, ())?;
/// # Ok(())
/// # }
/// ```
Creates a new `Func` from the given Rust closure.
This function will create a new `Func` which, when called, will
execute the given Rust closure. Unlike [`Func::new`] the target
function being called is known statically so the type signature can
be inferred. Rust types will map to WebAssembly types as follows.



Any of the Rust types can be returned from the closure as well, in
addition to some extra types



Note that all return types can also be wrapped in `Result<_, Trap>` to
indicate that the host function can generate a trap as well as possibly
returning a value.

Finally you can also optionally take [`Caller`] as the first argument of
your closure. If inserted then you're able to inspect the caller's
state, for example the [`Memory`](crate::Memory) it has exported so you
can read what pointers point to.

Note that when using this API, the intention is to create as thin of a
layer as possible for when WebAssembly calls the function provided. With
sufficient inlining and optimization the WebAssembly will call straight
into `func` provided, with no extra fluff entailed.
Creates a new ` Func ` from the given Rust closure . This function will create a new ` Func ` which when called will execute the given Rust closure . Unlike [ ` Func :: new ` ] the target function being called is known statically so the type signature can be inferred . Rust types will map to WebAssembly types as follows . Any of the Rust types can be returned from the closure as well in addition to some extra types Note that all return types can also be wrapped in ` Result<_ Trap > ` to indicate that the host function can generate a trap as well as possibly returning a value . Finally you can also optionally take [ ` Caller ` ] as the first argument of your closure . If inserted then you ' re able to inspect the caller ' s state for example the [ ` Memory ` ] ( crate :: Memory ) it has exported so you can read what pointers point to . Note that when using this API the intention is to create as thin of a layer as possible for when WebAssembly calls the function provided . With sufficient inlining and optimization the WebAssembly will call straight into ` func ` provided with no extra fluff entailed .
pub fn wrap<T, Params, Results>(
        mut store: impl AsContextMut<Data = T>,
        func: impl IntoFunc<T, Params, Results>,
    ) -> Func {
        let mut store = store.as_context_mut().opaque();
        // part of this unsafety is about matching the `T` to a `Store<T>`,
        // which is done through the `AsContextMut` bound above.
        unsafe {
            let host = HostFunc::wrap(store.engine(), func);
            host.into_func(&mut store)
        }
    }
pub fn wrap < T , Params , Results > ( mut store : impl AsContextMut < Data = T > , func : impl IntoFunc < T , Params , Results > , ) -> Func { let mut store = store . as_context_mut ( ) . opaque ( ) ; // part of this unsafety is about matching the `T` to a `Store<T>`, // which is done through the `AsContextMut` bound above. unsafe { let host = HostFunc :: wrap ( store . engine ( ) , func ) ; host . into_func ( & mut store ) } }
Creates a new `Func` from the given Rust closure.
Creates a new ` Func ` from the given Rust closure .
store
impl AsContextMut<Data = T>
func
impl IntoFunc<T, Params, Results>
store
impl AsContextMut<Data = T>
func
impl IntoFunc<T, Params, Results>
why `send + sync + 'static`?
All host functions defined in a [`Store`](crate::Store) (including
those from [`Func::new`] and other constructors) require that the
`func` provided is `Send + Sync + 'static`. Additionally host functions
always are `Fn` as opposed to `FnMut` or `FnOnce`. This can at-a-glance
feel restrictive since the closure cannot close over as many types as
before. The reason for this, though, is to ensure that
[`Store`](crate::Store) can implement both the `Send` and `Sync`
traits.

Fear not, however, because this isn't as restrictive as it seems. Host
functions are provided a [`Caller<'_, T>`](crate::Caller) argument which
allows access to the host-defined data within the
[`Store`](crate::Store). The `T` type is not required to be any of
`Send`, `Sync`, or `'static`. This means that you can store whatever
you'd like in `T` and have it accessible by all host functions.
Additionally mutable access to `T` is allowed through
[`Caller::data_mut`].

Most host-defined [`Func`] values provide closures that end up not
actually closing over any values. These zero-sized types will use the
context from [`Caller`] for host-defined information.
All host functions defined in a [ ` Store ` ] ( crate :: Store ) ( including those from [ ` Func :: new ` ] and other constructors ) require that the ` func ` provided is ` Send + Sync + ' static ` . Additionally host functions always are ` Fn ` as opposed to ` FnMut ` or ` FnOnce ` . This can at - a - glance feel restrictive since the closure cannot close over as many types as before . The reason for this though is to ensure that [ ` Store ` ] ( crate :: Store ) can implement both the ` Send ` and ` Sync ` traits . Fear not however because this isn ' t as restrictive as it seems . Host functions are provided a [ ` Caller< ' _ T > ` ] ( crate :: Caller ) argument which allows access to the host - defined data within the [ ` Store ` ] ( crate :: Store ) . The ` T ` type is not required to be any of ` Send ` ` Sync ` or ` ' static ` . This means that you can store whatever you ' d like in ` T ` and have it accessible by all host functions . Additionally mutable access to ` T ` is allowed through [ ` Caller :: data_mut ` ] . Most host - defined [ ` Func ` ] values provide closures that end up not actually closing over any values . These zero - sized types will use the context from [ ` Caller ` ] for host - defined information .
examples
First up we can see how simple wasm imports can be implemented, such
as a function that adds its two arguments and returns the result.


First up we can see how simple wasm imports can be implemented such as a function that adds its two arguments and returns the result .
use wasmtime::*;
None
fn main() -> anyhow::result<()> {
None
let mut store = store::<()>::default();
None
ok(())
None
}


We can also do the same thing, but generate a trap if the addition
overflows.


We can also do the same thing but generate a trap if the addition overflows .
use wasmtime::*;
None
fn main() -> anyhow::result<()> {
None
let mut store = store::<()>::default();
None
ok(())
None
}


And don't forget all the wasm types are supported!


And don ' t forget all the wasm types are supported!
use wasmtime::*;
None
fn main() -> anyhow::result<()> {
None
let mut store = store::<()>::default();
None
ok(())
None
}


Finally if you want to get really fancy you can also implement
imports that read/write wasm module's memory


Finally if you want to get really fancy you can also implement imports that read / write wasm module ' s memory
use wasmtime::*;
None
fn main() -> anyhow::result<()> {
None
let mut store = store::default();
let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
let mem = match caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Trap::new("failed to find host memory")),
};
let data = mem.data(&caller)
.get(ptr as u32 as usize..)
.and_then(|arr| arr.get(..len as u32 as usize));
let string = match data {
Some(data) => match str::from_utf8(data) {
Ok(s) => s,
Err(_) => return Err(Trap::new("invalid utf-8")),
},
None => return Err(Trap::new("pointer/length out of bounds")),
};
assert_eq!(string, "Hello, world!");
println!("{}", string);
Ok(())
});
let module = Module::new(
store.engine(),
r#"
(module
(import "" "" (func $log_str (param i32 i32)))
(func (export "foo")
i32.const 4   ;; ptr
i32.const 13  ;; len
call $log_str)
(memory (export "memory") 1)
(data (i32.const 4) "Hello, world!"))
"#,
)?;
let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
let foo = instance.get_typed_func::<(), (), _>(&mut store, "foo")?;
foo.call(&mut store, ())?.
let log_str = Func :: wrap ( &mut store |mut caller : Caller< ' _ () > ptr : i32 len : i32| { let mem = match caller . get_export ( " memory " ) { Some ( Extern :: Memory ( mem )) = > mem _ = > return Err ( Trap :: new ( " failed to find host memory " )) } ; let data = mem . data ( &caller ) . get ( ptr as u32 as usize .. ) . and_then ( |arr| arr . get ( .. len as u32 as usize )) ; let string = match data { Some ( data ) = > match str :: from_utf8 ( data ) { Ok ( s ) = > s Err ( _ ) = > return Err ( Trap :: new ( " invalid utf - 8 " )) } None = > return Err ( Trap :: new ( " pointer / length out of bounds " )) } ; assert_eq! ( string " Hello world! " ) ; println! ( " {} " string ) ; Ok (( )) } ) ; let module = Module :: new ( store . engine () r# " ( module ( import " " " " ( func $log_str ( param i32 i32 ))) ( func ( export " foo " ) i32 . const 4 ;; ptr i32 . const 13 ;; len call $log_str ) ( memory ( export " memory " ) 1 ) ( data ( i32 . const 4 ) " Hello world! " )) " # ) ? ; let instance = Instance :: new ( &mut store &module & [ log_str . into () ] ) ? ; let foo = instance . get_typed_func :: < () () _ > ( &mut store " foo " ) ? ; foo . call ( &mut store () ) ? .
ok(())
None
}
None