wiggle::wasmtime_crate

Struct StructRef

pub struct StructRef { /* private fields */ }
Expand description

A reference to a GC-managed struct instance.

WebAssembly structs are static, fixed-length, ordered sequences of fields. Fields are named by index, not by identifier; in this way, they are similar to Rust’s tuples. Each field is mutable or constant and stores unpacked Vals or packed 8-/16-bit integers.

Like all WebAssembly references, these are opaque and unforgeable to Wasm: they cannot be faked and Wasm cannot, for example, cast the integer 0x12345678 into a reference, pretend it is a valid structref, and trick the host into dereferencing it and segfaulting or worse.

Note that you can also use Rooted<StructRef> and ManuallyRooted<StructRef> as a type parameter with Func::typed- and Func::wrap-style APIs.

§Example

use wasmtime::*;

let mut config = Config::new();
config.wasm_function_references(true);
config.wasm_gc(true);

let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());

// Define a struct type.
let struct_ty = StructType::new(
   store.engine(),
   [FieldType::new(Mutability::Var, StorageType::I8)],
)?;

// Create an allocator for the struct type.
let allocator = StructRefPre::new(&mut store, struct_ty);

{
    let mut scope = RootScope::new(&mut store);

    // Allocate an instance of the struct type.
    let my_struct = match StructRef::new(&mut scope, &allocator, &[Val::I32(42)]) {
        Ok(s) => s,
        // If the heap is out of memory, then do a GC and try again.
        Err(e) if e.is::<GcHeapOutOfMemory<()>>() => {
            // Do a GC! Note: in an async context, you'd want to do
            // `scope.as_context_mut().gc_async().await`.
            scope.as_context_mut().gc();

            StructRef::new(&mut scope, &allocator, &[Val::I32(42)])?
        }
        Err(e) => return Err(e),
    };

    // That instance's field should have the expected value.
    let val = my_struct.field(&mut scope, 0)?.unwrap_i32();
    assert_eq!(val, 42);

    // And we can update the field's value because it is a mutable field.
    my_struct.set_field(&mut scope, 0, Val::I32(36))?;
    let new_val = my_struct.field(&mut scope, 0)?.unwrap_i32();
    assert_eq!(new_val, 36);
}

Implementations§

§

impl StructRef

pub fn new( store: impl AsContextMut, allocator: &StructRefPre, fields: &[Val], ) -> Result<Rooted<StructRef>, Error>

Allocate a new struct and get a reference to it.

§Errors

If the given fields values’ types do not match the field types of the allocator’s struct type, an error is returned.

If the allocation cannot be satisfied because the GC heap is currently out of memory, but performing a garbage collection might free up space such that retrying the allocation afterwards might succeed, then a GcHeapOutOfMemory<()> error is returned.

§Panics

Panics if the allocator, or any of the field values, is not associated with the given store.

pub fn ty(&self, store: impl AsContext) -> Result<StructType, Error>

Get this structref’s type.

§Errors

Return an error if this reference has been unrooted.

§Panics

Panics if this reference is associated with a different store.

pub fn matches_ty( &self, store: impl AsContext, ty: &StructType, ) -> Result<bool, Error>

Does this structref match the given type?

That is, is this struct’s type a subtype of the given type?

§Errors

Return an error if this reference has been unrooted.

§Panics

Panics if this reference is associated with a different store or if the type is not associated with the store’s engine.

pub fn fields<'a, T>( &'a self, store: impl Into<StoreContextMut<'a, T>>, ) -> Result<impl ExactSizeIterator + 'a, Error>
where T: 'a,

Get the values of this struct’s fields.

Note that i8 and i16 field values are zero-extended into Val::I32(_)s.

§Errors

Return an error if this reference has been unrooted.

§Panics

Panics if this reference is associated with a different store.

pub fn field( &self, store: impl AsContextMut, index: usize, ) -> Result<Val, Error>

Get this struct’s indexth field.

Note that i8 and i16 field values are zero-extended into Val::I32(_)s.

§Errors

Returns an Err(_) if the index is out of bounds or this reference has been unrooted.

§Panics

Panics if this reference is associated with a different store.

pub fn set_field( &self, store: impl AsContextMut, index: usize, value: Val, ) -> Result<(), Error>

Set this struct’s indexth field.

§Errors

Returns an error in the following scenarios:

  • When given a value of the wrong type, such as trying to set an f32 field to an i64 value.

  • When the field is not mutable.

  • When this struct does not have an indexth field, i.e. index is out of bounds.

  • When value is a GC reference that has since been unrooted.

§Panics

Panics if this reference is associated with a different store.

Trait Implementations§

§

impl Debug for StructRef

§

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

Formats the value using the given formatter. Read more

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

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

impl<T> Pointee for T

Source§

type Pointer = u32

Source§

fn debug( pointer: <T as Pointee>::Pointer, f: &mut Formatter<'_>, ) -> Result<(), Error>

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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> 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
§

impl<T> GcRef for T
where T: GcRefImpl,