pub trait AsContextMut: AsContext {
    // Required method
    fn as_context_mut(&mut self) -> StoreContextMut<'_, Self::Data>;
}
Expand description

A trait used to get exclusive mutable access to a Store in Wasmtime.

This trait is used as a bound on the first argument of many methods within Wasmtime. This trait is implemented for types like Store, Caller, and StoreContextMut itself. Implementors of this trait provide access to a StoreContextMut via some means, allowing the method in question to get access to the store’s internal information.

This is notably used for methods that may require some mutation of the Store itself. For example calling a wasm function can mutate linear memory or globals. Creation of a Func will update internal data structures. This ends up being quite a common bound in Wasmtime, but typically you can simply pass &mut store or &mut caller to satisfy it.

Calling multiple methods that take &mut impl AsContextMut

As of Rust 1.53.0, generic methods that take a generic &mut T do not get “automatic reborrowing” and therefore you cannot call multiple generic methods with the same &mut T without manually inserting reborrows. This affects the many wasmtime API methods that take &mut impl AsContextMut.

For example, this fails to compile because the context is moved into the first call:

use wasmtime::{AsContextMut, Instance};

fn foo(cx: &mut impl AsContextMut, instance: Instance) {
    // `cx` is not reborrowed, but moved into this call.
    let my_export = instance.get_export(cx, "my_export");

    // Therefore, this use of `cx` is a use-after-move and prohibited by the
    // borrow checker.
    let other_export = instance.get_export(cx, "other_export");
}

To fix this, manually insert reborrows like &mut *cx that would otherwise normally be inserted automatically by the Rust compiler for non-generic methods:

use wasmtime::{AsContextMut, Instance};

fn foo(cx: &mut impl AsContextMut, instance: Instance) {
    let my_export = instance.get_export(&mut *cx, "my_export");

    // This works now, since `cx` was reborrowed above, rather than moved!
    let other_export = instance.get_export(&mut *cx, "other_export");
}

Required Methods§

source

fn as_context_mut(&mut self) -> StoreContextMut<'_, Self::Data>

Returns the store context that this type provides access to.

Implementations on Foreign Types§

source§

impl<T: AsContextMut> AsContextMut for &mut T

Implementors§