pub(crate) struct Function(pub(crate) BackendFunction);Expand description
A WebAssembly function instance.
A function instance is the runtime representation of a function.
It effectively is a closure of the original function (defined in either
the host or the WebAssembly module) over the runtime crate::Instance of its
originating crate::Module.
The module instance is used to resolve references to other definitions during execution of the function.
Spec: https://webassembly.github.io/spec/core/exec/runtime.html#function-instances
§Panics
- Closures (functions with captured environments) are not currently supported
with native functions. Attempting to create a native
Functionwith one will result in a panic. Closures as host functions tracking issue
Tuple Fields§
§0: BackendFunctionImplementations§
Source§impl Function
impl Function
Sourcepub fn into_sys(self) -> Function
pub fn into_sys(self) -> Function
Consume self into crate::backend::sys::function::Function.
Sourcepub fn as_sys(&self) -> &Function
pub fn as_sys(&self) -> &Function
Convert a reference to self into a reference to crate::backend::sys::function::Function.
Sourcepub fn as_sys_mut(&mut self) -> &mut Function
pub fn as_sys_mut(&mut self) -> &mut Function
Convert a mutable reference to self into a mutable reference crate::backend::sys::function::Function.
Source§impl Function
impl Function
Sourcepub fn new<FT, F>(store: &mut impl AsStoreMut, ty: FT, func: F) -> Function
pub fn new<FT, F>(store: &mut impl AsStoreMut, ty: FT, func: F) -> Function
Creates a new host Function (dynamic) with the provided signature.
If you know the signature of the host function at compile time,
consider using Function::new_typed for less runtime overhead.
Sourcepub fn new_with_env<FT, F, T>(
store: &mut impl AsStoreMut,
env: &FunctionEnv<T>,
ty: FT,
func: F,
) -> Function
pub fn new_with_env<FT, F, T>( store: &mut impl AsStoreMut, env: &FunctionEnv<T>, ty: FT, func: F, ) -> Function
Creates a new host Function (dynamic) with the provided signature.
If you know the signature of the host function at compile time,
consider using Function::new_typed_with_env for less runtime overhead.
Takes a FunctionEnv that is passed into func. If that is not required,
Function::new might be an option as well.
§Examples
let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);
let f = Function::new_with_env(&mut store, &env, &signature, |_env, args| {
let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
Ok(vec![Value::I32(sum)])
});With constant signature:
const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);
let f = Function::new_with_env(&mut store, &env, I32_I32_TO_I32, |_env, args| {
let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
Ok(vec![Value::I32(sum)])
});Sourcepub fn new_typed<F, Args, Rets>(
store: &mut impl AsStoreMut,
func: F,
) -> Functionwhere
F: HostFunction<(), Args, Rets, WithoutEnv> + 'static + Send + Sync,
Args: WasmTypeList,
Rets: WasmTypeList,
pub fn new_typed<F, Args, Rets>(
store: &mut impl AsStoreMut,
func: F,
) -> Functionwhere
F: HostFunction<(), Args, Rets, WithoutEnv> + 'static + Send + Sync,
Args: WasmTypeList,
Rets: WasmTypeList,
Creates a new host Function from a native function.
Sourcepub fn new_typed_with_env<T, F, Args, Rets>(
store: &mut impl AsStoreMut,
env: &FunctionEnv<T>,
func: F,
) -> Functionwhere
T: Send + 'static,
F: HostFunction<T, Args, Rets, WithEnv> + 'static + Send + Sync,
Args: WasmTypeList,
Rets: WasmTypeList,
pub fn new_typed_with_env<T, F, Args, Rets>(
store: &mut impl AsStoreMut,
env: &FunctionEnv<T>,
func: F,
) -> Functionwhere
T: Send + 'static,
F: HostFunction<T, Args, Rets, WithEnv> + 'static + Send + Sync,
Args: WasmTypeList,
Rets: WasmTypeList,
Creates a new host Function with an environment from a typed function.
The function signature is automatically retrieved using the Rust typing system.
§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
a + b
}
let f = Function::new_typed_with_env(&mut store, &env, sum);Sourcepub fn new_async<FT, F, Fut>(
store: &mut impl AsStoreMut,
ty: FT,
func: F,
) -> Function
pub fn new_async<FT, F, Fut>( store: &mut impl AsStoreMut, ty: FT, func: F, ) -> Function
Creates a new async host Function (dynamic) with the provided
signature.
If you know the signature of the host function at compile time,
consider using Self::new_typed_async for less runtime overhead.
The provided closure returns a future that resolves to the function results.
When invoked synchronously (via Function::call) the future will run to
completion immediately, provided it doesn’t suspend. When invoked through
Function::call_async, the future may suspend and resume as needed.
Sourcepub fn new_with_env_async<FT, F, Fut, T>(
store: &mut impl AsStoreMut,
env: &FunctionEnv<T>,
ty: FT,
func: F,
) -> Functionwhere
T: 'static,
FT: Into<FunctionType>,
F: Fn(AsyncFunctionEnvMut<T>, &[Value]) -> Fut + 'static,
Fut: Future<Output = Result<Vec<Value>, RuntimeError>> + 'static,
pub fn new_with_env_async<FT, F, Fut, T>(
store: &mut impl AsStoreMut,
env: &FunctionEnv<T>,
ty: FT,
func: F,
) -> Functionwhere
T: 'static,
FT: Into<FunctionType>,
F: Fn(AsyncFunctionEnvMut<T>, &[Value]) -> Fut + 'static,
Fut: Future<Output = Result<Vec<Value>, RuntimeError>> + 'static,
Creates a new async host Function (dynamic) with the provided
signature and environment.
If you know the signature of the host function at compile time,
consider using Self::new_typed_with_env_async for less runtime overhead.
Takes an AsyncFunctionEnvMut that is passed into func. If
that is not required, Self::new_async might be an option as well.
Sourcepub fn new_typed_async<F, Args, Rets>(
store: &mut impl AsStoreMut,
func: F,
) -> Functionwhere
Rets: WasmTypeList + 'static,
Args: WasmTypeList + 'static,
F: AsyncHostFunction<(), Args, Rets, WithoutEnv> + 'static,
pub fn new_typed_async<F, Args, Rets>(
store: &mut impl AsStoreMut,
func: F,
) -> Functionwhere
Rets: WasmTypeList + 'static,
Args: WasmTypeList + 'static,
F: AsyncHostFunction<(), Args, Rets, WithoutEnv> + 'static,
Creates a new async host Function from a native typed function.
The future can return either the raw result tuple or any type that implements
IntoResult for the result tuple (e.g. Result<Rets, E>).
Sourcepub fn new_typed_with_env_async<T, F, Args, Rets>(
store: &mut impl AsStoreMut,
env: &FunctionEnv<T>,
func: F,
) -> Functionwhere
T: 'static,
Rets: WasmTypeList + 'static,
Args: WasmTypeList + 'static,
F: AsyncHostFunction<T, Args, Rets, WithEnv> + 'static,
pub fn new_typed_with_env_async<T, F, Args, Rets>(
store: &mut impl AsStoreMut,
env: &FunctionEnv<T>,
func: F,
) -> Functionwhere
T: 'static,
Rets: WasmTypeList + 'static,
Args: WasmTypeList + 'static,
F: AsyncHostFunction<T, Args, Rets, WithEnv> + 'static,
Creates a new async host Function with an environment from a typed function.
Sourcepub fn ty(&self, store: &impl AsStoreRef) -> FunctionType
pub fn ty(&self, store: &impl AsStoreRef) -> FunctionType
Returns the [FunctionType] of the Function.
§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
a + b
}
let f = Function::new_typed_with_env(&mut store, &env, sum);
assert_eq!(f.ty(&mut store).params(), vec![Type::I32, Type::I32]);
assert_eq!(f.ty(&mut store).results(), vec![Type::I32]);Sourcepub fn param_arity(&self, store: &impl AsStoreRef) -> usize
pub fn param_arity(&self, store: &impl AsStoreRef) -> usize
Returns the number of parameters that this function takes.
§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
a + b
}
let f = Function::new_typed_with_env(&mut store, &env, sum);
assert_eq!(f.param_arity(&mut store), 2);Sourcepub fn result_arity(&self, store: &impl AsStoreRef) -> usize
pub fn result_arity(&self, store: &impl AsStoreRef) -> usize
Returns the number of results this function produces.
§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
a + b
}
let f = Function::new_typed_with_env(&mut store, &env, sum);
assert_eq!(f.result_arity(&mut store), 1);Sourcepub fn call(
&self,
store: &mut impl AsStoreMut,
params: &[Value],
) -> Result<Box<[Value]>, RuntimeError>
pub fn call( &self, store: &mut impl AsStoreMut, params: &[Value], ) -> Result<Box<[Value]>, RuntimeError>
Call the function.
Depending on where the Function is defined, it will call it.
- If the function is defined inside a WebAssembly, it will call the trampoline for the function signature.
- If the function is defined in the host (in a native way), it will call the trampoline.
§Examples
let sum = instance.exports.get_function("sum").unwrap();
assert_eq!(sum.call(&mut store, &[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);Sourcepub fn call_async(
&self,
store: &impl AsStoreAsync,
params: Vec<Value>,
) -> impl Future<Output = Result<Box<[Value]>, RuntimeError>> + 'static
pub fn call_async( &self, store: &impl AsStoreAsync, params: Vec<Value>, ) -> impl Future<Output = Result<Box<[Value]>, RuntimeError>> + 'static
Calls the function asynchronously.
The returned future drives execution of the WebAssembly function on a
coroutine stack. Host functions created with Function::new_async may
suspend execution by awaiting futures, and their completion will resume
the Wasm instance according to the JSPI proposal.
Sourcepub fn typed<Args, Rets>(
&self,
store: &impl AsStoreRef,
) -> Result<TypedFunction<Args, Rets>, RuntimeError>where
Args: WasmTypeList,
Rets: WasmTypeList,
pub fn typed<Args, Rets>(
&self,
store: &impl AsStoreRef,
) -> Result<TypedFunction<Args, Rets>, RuntimeError>where
Args: WasmTypeList,
Rets: WasmTypeList,
Transform this WebAssembly function into a typed function.
See TypedFunction to learn more.
§Examples
let sum = instance.exports.get_function("sum").unwrap();
let sum_typed: TypedFunction<(i32, i32), i32> = sum.typed(&mut store).unwrap();
assert_eq!(sum_typed.call(&mut store, 1, 2).unwrap(), 3);§Errors
If the Args generic parameter does not match the exported function
an error will be raised:
let sum = instance.exports.get_function("sum").unwrap();
// This results in an error: `RuntimeError`
let sum_typed : TypedFunction<(i64, i64), i32> = sum.typed(&mut store).unwrap();If the Rets generic parameter does not match the exported function
an error will be raised:
let sum = instance.exports.get_function("sum").unwrap();
// This results in an error: `RuntimeError`
let sum_typed: TypedFunction<(i32, i32), i64> = sum.typed(&mut store).unwrap();Sourcepub fn is_from_store(&self, store: &impl AsStoreRef) -> bool
pub fn is_from_store(&self, store: &impl AsStoreRef) -> bool
Checks whether this Function can be used with the given store.
Trait Implementations§
Source§impl<'a> Exportable<'a> for Function
impl<'a> Exportable<'a> for Function
Source§fn get_self_from_extern(
_extern: &'a Extern,
) -> Result<&'a Function, ExportError>
fn get_self_from_extern( _extern: &'a Extern, ) -> Result<&'a Function, ExportError>
Instance by name.Source§impl<Args, Rets> From<TypedFunction<Args, Rets>> for Functionwhere
Args: WasmTypeList,
Rets: WasmTypeList,
impl<Args, Rets> From<TypedFunction<Args, Rets>> for Functionwhere
Args: WasmTypeList,
Rets: WasmTypeList,
Source§fn from(other: TypedFunction<Args, Rets>) -> Function
fn from(other: TypedFunction<Args, Rets>) -> Function
impl Eq for Function
impl StructuralPartialEq for Function
Auto Trait Implementations§
impl Freeze for Function
impl RefUnwindSafe for Function
impl Send for Function
impl Sync for Function
impl Unpin for Function
impl UnwindSafe for Function
Blanket Implementations§
§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
§type ArchivedMetadata = ()
type ArchivedMetadata = ()
§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Source§impl<'a, T> ExportableWithGenerics<'a, (), ()> for Twhere
T: Exportable<'a> + Clone + 'static,
impl<'a, T> ExportableWithGenerics<'a, (), ()> for Twhere
T: Exportable<'a> + Clone + 'static,
Source§fn get_self_from_extern_with_generics(
_extern: &'a Extern,
) -> Result<T, ExportError>
fn get_self_from_extern_with_generics( _extern: &'a Extern, ) -> Result<T, ExportError>
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2where
T: SharedNiching<N1, N2>,
N1: Niching<T>,
N2: Niching<T>,
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2where
T: SharedNiching<N1, N2>,
N1: Niching<T>,
N2: Niching<T>,
§impl<T> Pointable for T
impl<T> Pointable for T
§impl<T> Pointee for T
impl<T> Pointee for T
§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
§impl<T> ServiceExt for T
impl<T> ServiceExt for T
§fn decompression(self) -> Decompression<Self>where
Self: Sized,
fn decompression(self) -> Decompression<Self>where
Self: Sized,
§fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
§fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
§fn follow_redirects(self) -> FollowRedirect<Self>where
Self: Sized,
fn follow_redirects(self) -> FollowRedirect<Self>where
Self: Sized,
§fn catch_panic(self) -> CatchPanic<Self, DefaultResponseForPanic>where
Self: Sized,
fn catch_panic(self) -> CatchPanic<Self, DefaultResponseForPanic>where
Self: Sized,
500 Internal Server responses. Read more