Function

Struct Function 

Source
pub struct Function { /* private fields */ }
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 Instance of its originating 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 Function with one will result in a panic. Closures as host functions tracking issue

Implementations§

Source§

impl Function

Source

pub fn new<FT, F>(store: &Store, ty: FT, func: F) -> Function
where FT: Into<FunctionType>, F: Fn(&[Value<Function>]) -> Result<Vec<Value<Function>>, RuntimeError> + 'static + Send + Sync,

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_native for less runtime overhead.

§Examples
let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);

let f = Function::new(&store, &signature, |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(&store, I32_I32_TO_I32, |args| {
    let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
    Ok(vec![Value::I32(sum)])
});
Source

pub fn new_with_env<FT, F, Env>( store: &Store, ty: FT, env: Env, func: F, ) -> Function
where FT: Into<FunctionType>, F: Fn(&Env, &[Value<Function>]) -> Result<Vec<Value<Function>>, RuntimeError> + 'static + Send + Sync, Env: WasmerEnv + 'static,

Creates a new host Function (dynamic) with the provided signature and environment.

If you know the signature of the host function at compile time, consider using Function::new_native_with_env for less runtime overhead.

§Examples
#[derive(WasmerEnv, Clone)]
struct Env {
  multiplier: i32,
};
let env = Env { multiplier: 2 };

let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);

let f = Function::new_with_env(&store, &signature, env, |env, args| {
    let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32());
    Ok(vec![Value::I32(result)])
});

With constant signature:

const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);

#[derive(WasmerEnv, Clone)]
struct Env {
  multiplier: i32,
};
let env = Env { multiplier: 2 };

let f = Function::new_with_env(&store, I32_I32_TO_I32, env, |env, args| {
    let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32());
    Ok(vec![Value::I32(result)])
});
Source

pub fn new_native<F, Args, Rets, Env>(store: &Store, func: F) -> Function
where F: HostFunction<Args, Rets, WithoutEnv, Env>, Args: WasmTypeList, Rets: WasmTypeList, Env: 'static,

Creates a new host Function from a native function.

The function signature is automatically retrieved using the Rust typing system.

§Example
fn sum(a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_native(&store, sum);
Source

pub fn new_native_with_env<F, Args, Rets, Env>( store: &Store, env: Env, func: F, ) -> Function
where F: HostFunction<Args, Rets, WithEnv, Env>, Args: WasmTypeList, Rets: WasmTypeList, Env: WasmerEnv + 'static,

Creates a new host Function from a native function and a provided environment.

The function signature is automatically retrieved using the Rust typing system.

§Example
#[derive(WasmerEnv, Clone)]
struct Env {
    multiplier: i32,
};
let env = Env { multiplier: 2 };

fn sum_and_multiply(env: &Env, a: i32, b: i32) -> i32 {
    (a + b) * env.multiplier
}

let f = Function::new_native_with_env(&store, env, sum_and_multiply);
Source

pub fn ty(&self) -> &FunctionType

Returns the FunctionType of the Function.

§Example
fn sum(a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_native(&store, sum);

assert_eq!(f.ty().params(), vec![Type::I32, Type::I32]);
assert_eq!(f.ty().results(), vec![Type::I32]);
Source

pub fn store(&self) -> &Store

Returns the Store where the Function belongs.

Source

pub fn param_arity(&self) -> usize

Returns the number of parameters that this function takes.

§Example
fn sum(a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_native(&store, sum);

assert_eq!(f.param_arity(), 2);
Source

pub fn result_arity(&self) -> usize

Returns the number of results this function produces.

§Example
fn sum(a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_native(&store, sum);

assert_eq!(f.result_arity(), 1);
Source

pub fn call( &self, params: &[Value<Function>], ) -> Result<Box<[Value<Function>]>, RuntimeError>

Call the Function function.

Depending on where the Function is defined, it will call it.

  1. If the function is defined inside a WebAssembly, it will call the trampoline for the function signature.
  2. 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(&[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);
Source

pub fn native<Args, Rets>(&self) -> Result<NativeFunc<Args, Rets>, RuntimeError>
where Args: WasmTypeList, Rets: WasmTypeList,

Transform this WebAssembly function into a function with the native ABI. See NativeFunc to learn more.

§Examples
let sum = instance.exports.get_function("sum").unwrap();
let sum_native = sum.native::<(i32, i32), i32>().unwrap();

assert_eq!(sum_native.call(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_native = sum.native::<(i64, i64), i32>().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_native = sum.native::<(i32, i32), i64>().unwrap();

Trait Implementations§

Source§

impl Clone for Function

Source§

fn clone(&self) -> Function

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Function

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'a> Exportable<'a> for Function

Source§

fn to_export(&self) -> Export

This function is used when providedd the Extern as exportable, so it can be used while instantiating the Module.
Source§

fn get_self_from_extern( _extern: &'a Extern, ) -> Result<&'a Function, ExportError>

Implementation of how to get the export corresponding to the implementing type from an Instance by name.
Source§

fn into_weak_instance_ref(&mut self)

Convert the extern internally to hold a weak reference to the InstanceRef. This is useful for preventing cycles, for example for data stored in a type implementing WasmerEnv.
Source§

impl From<Function> for Value<Function>

Source§

fn from(val: Function) -> Value<Function>

Converts to this type from the input type.
Source§

impl<Args, Rets> From<NativeFunc<Args, Rets>> for Function
where Args: WasmTypeList, Rets: WasmTypeList,

Source§

fn from(other: NativeFunc<Args, Rets>) -> Function

Converts to this type from the input type.
Source§

impl MemoryUsage for Function

Source§

fn size_of_val(&self, visited: &mut dyn MemoryUsageTracker) -> usize

Returns the size of the referenced value in bytes. Read more
Source§

impl PartialEq for Function

Source§

fn eq(&self, other: &Function) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl WasmValueType for Function

Source§

unsafe fn write_value_to(&self, p: *mut i128)

Write the value.

Source§

unsafe fn read_value_from( store: &(dyn Any + 'static), p: *const i128, ) -> Function

Read the value.

Source§

impl StructuralPartialEq for Function

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

Source§

fn deserialize( &self, deserializer: &mut D, ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The type for metadata in pointers and references to Self.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcastable for T
where T: Any + Send + Sync + 'static,

Source§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
Source§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
Source§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

upcast boxed dyn
Source§

impl<T> Upcastable for T
where T: Any + Debug + 'static,

Source§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

Source§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

Source§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more