wasmtime/runtime/vm/
store_box.rs

1use crate::prelude::*;
2use crate::runtime::vm::SendSyncPtr;
3use core::ptr::NonNull;
4
5/// A `Box<T>` lookalike for memory that's stored in a `Store<T>`
6///
7/// This is intended to be quite similar to a `Box<T>` except without the
8/// `Deref` implementations. The main motivation for this type's existence is to
9/// appease the aliasing rules in miri to ensure that `StoreBox` can be moved
10/// around without invalidating pointers to the contents within the box. The
11/// standard `Box<T>` type does not implement this for example and moving that
12/// will invalidate derived pointers.
13pub struct StoreBox<T: ?Sized>(SendSyncPtr<T>);
14
15impl<T> StoreBox<T> {
16    /// Allocates space on the heap to store `val` and returns a pointer to it
17    /// living on the heap.
18    pub fn new(val: T) -> StoreBox<T> {
19        let ptr = Box::into_raw(Box::new(val));
20        StoreBox(SendSyncPtr::from(NonNull::new(ptr).unwrap()))
21    }
22}
23
24impl<T: ?Sized> StoreBox<T> {
25    /// Returns the underlying pointer to `T` which is owned by the store.
26    pub fn get(&self) -> NonNull<T> {
27        self.0.as_non_null()
28    }
29}
30
31impl<T: ?Sized> Drop for StoreBox<T> {
32    fn drop(&mut self) {
33        unsafe {
34            drop(Box::from_raw(self.0.as_ptr()));
35        }
36    }
37}