wit-bindgen 0.59.0

Rust bindings generator and runtime support for WIT and the component model. Used when compiling Rust programs to the component model.
Documentation
//! Helper traits, types, and utilities for managing resources in the component
//! model.

/// A trait implemented by all resources that a component might export.
///
/// This is an implementation detail primarily for the code generated by
/// exported resources. The primary purpose of this trait is to serve as an
/// abstraction for the in-memory storage of a resource.
pub trait Resource: Sized + 'static {
    /// The type which is actually stored in-memory for this resource.
    ///
    /// By default this is `Option<T>`.
    type Rep: ResourceRep<Self>;
}

impl<T: 'static> Resource for T {
    type Rep = Option<T>;
}

/// A trait used to define how to access the underlying data `T` from an
/// in-memory representation.
///
/// This is used as a bound on the [`Resource::Rep`] associated type which is in
/// turn used to access data within a resources.
pub unsafe trait ResourceRep<T> {
    /// Creates a new instance of `Self` which wraps the provided data.
    fn rep_new(inner: T) -> Self;

    /// Acquires `&T` from a raw pointer to `Self`.
    unsafe fn rep_as_ref<'a>(ptr: *const Self) -> &'a T;

    /// Acquires `&mut T` from a raw pointer to `Self`.
    unsafe fn rep_as_mut<'a>(ptr: *mut Self) -> &'a mut T;

    /// Takes the value out of `Self` at the provided pointer.
    ///
    /// Note that `ptr` will later be deallocated meaning that it must not run
    /// the destructor of `T` after this method is called. This is guaranteed to
    /// be called at most once, however. Additionally after calling this method
    /// it's guaranteed that the `rep_as_*` method above will not be called.
    unsafe fn rep_take<'a>(ptr: *mut Self) -> T;
}

unsafe impl<T> ResourceRep<T> for Option<T> {
    fn rep_new(inner: T) -> Option<T> {
        Some(inner)
    }
    unsafe fn rep_as_ref<'a>(ptr: *const Option<T>) -> &'a T {
        unsafe { (*ptr).as_ref().unwrap() }
    }
    unsafe fn rep_as_mut<'a>(ptr: *mut Option<T>) -> &'a mut T {
        unsafe { (*ptr).as_mut().unwrap() }
    }
    unsafe fn rep_take(ptr: *mut Option<T>) -> T {
        unsafe { (*ptr).take().unwrap() }
    }
}