Struct Module

Source
pub struct Module(/* private fields */);
Expand description

A compiled WebAssembly module, ready to be instantiated.

A Module is a compiled in-memory representation of an input WebAssembly binary. A Module is then used to create an Instance through an instantiation process. You cannot call functions or fetch globals, for example, on a Module because it’s purely a code representation. Instead you’ll need to create an Instance to interact with the wasm module.

A Module can be created by compiling WebAssembly code through APIs such as Module::new. This would be a JIT-style use case where code is compiled just before it’s used. Alternatively a Module can be compiled in one process and [Module::serialize] can be used to save it to storage. A later call to [Module::deserialize] will quickly load the module to execute and does not need to compile any code, representing a more AOT-style use case.

Currently a Module does not implement any form of tiering or dynamic optimization of compiled code. Creation of a Module via Module::new or related APIs will perform the entire compilation step synchronously. When finished no further compilation will happen at runtime or later during execution of WebAssembly instances for example.

Compilation of WebAssembly by default goes through Cranelift and is recommended to be done once-per-module. The same WebAssembly binary need not be compiled multiple times and can instead used an embedder-cached result of the first call.

Module is thread-safe and safe to share across threads.

§Modules and Clone

Using clone on a Module is a cheap operation. It will not create an entirely new module, but rather just a new reference to the existing module. In other words it’s a shallow copy, not a deep copy.

§Examples

There are a number of ways you can create a Module, for example pulling the bytes from a number of locations. One example is loading a module from the filesystem:

let engine = Engine::default();
let module = Module::from_file(&engine, "path/to/foo.wasm")?;

You can also load the wasm text format if more convenient too:

let engine = Engine::default();
// Now we're using the WebAssembly text extension: `.wat`!
let module = Module::from_file(&engine, "path/to/foo.wat")?;

And if you’ve already got the bytes in-memory you can use the Module::new constructor:

let engine = Engine::default();
let module = Module::new(&engine, &wasm_bytes)?;

// It also works with the text format!
let module = Module::new(&engine, "(module (func))")?;

Serializing and deserializing a module looks like:

let engine = Engine::default();
let module = Module::new(&engine, &wasm_bytes)?;
let module_bytes = module.serialize()?;

// ... can save `module_bytes` to disk or other storage ...

// recreate the module from the serialized bytes. For the `unsafe` bits
// see the documentation of `deserialize`.
let module = unsafe { Module::deserialize(&engine, &module_bytes)? };

Implementations§

Source§

impl Module

Source

pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Self>

👎Deprecated since 0.4.0: Compiling a module synchronously can panic on the web, please use new_safe instead.
Source

pub async fn new_safe(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Self>

Creates a new WebAssembly Module from the given in-memory bytes.

The bytes provided must be in one of the following formats:

  • A binary-encoded WebAssembly module. This is always supported.
  • A text-encoded instance of the WebAssembly text format. This is only supported when the wat feature of this crate is enabled. If this is supplied then the text format will be parsed before validation. Note that the wat feature is enabled by default.

The data for the wasm module must be loaded in-memory if it’s present elsewhere, for example on disk. This requires that the entire binary is loaded into memory all at once, this API does not support streaming compilation of a module.

The WebAssembly binary will be decoded and validated. It will also be compiled according to the configuration of the provided engine.

§Errors

This function may fail and return an error. Errors may include situations such as:

  • The binary provided could not be decoded because it’s not a valid WebAssembly binary
  • The WebAssembly binary may not validate (e.g. contains type errors)
  • Implementation-specific limits were exceeded with a valid binary (for example too many locals)
  • The wasm binary may use features that are not enabled in the configuration of engine
  • If the wat feature is enabled and the input is text, then it may be rejected if it fails to parse.

The error returned should contain full information about why module creation failed if one is returned.

§Examples

The new function can be invoked with a in-memory array of bytes:

let module = Module::new(&engine, &wasm_bytes)?;

Or you can also pass in a string to be parsed as the wasm text format:

let module = Module::new(&engine, "(module (func))")?;

Trait Implementations§

Source§

impl Clone for Module

Source§

fn clone(&self) -> Module

Returns a copy 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 RefCast for Module

Source§

type From = Module

Source§

fn ref_cast(_from: &Self::From) -> &Self

Source§

fn ref_cast_mut(_from: &mut Self::From) -> &mut Self

Auto Trait Implementations§

§

impl Freeze for Module

§

impl !RefUnwindSafe for Module

§

impl Send for Module

§

impl Sync for Module

§

impl Unpin for Module

§

impl !UnwindSafe for Module

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> 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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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.