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