memkit/container/
frame_box.rs

1//! Frame-allocated box type.
2
3use std::marker::PhantomData;
4use std::ops::{Deref, DerefMut};
5use std::ptr::NonNull;
6
7/// A Box-like wrapper for frame-allocated memory.
8///
9/// The memory is valid until `end_frame()` is called on the allocator.
10/// This type does NOT free memory on drop - frame memory is bulk-freed.
11pub struct MkFrameBox<'a, T> {
12    ptr: NonNull<T>,
13    _marker: PhantomData<&'a T>,
14}
15
16impl<'a, T> MkFrameBox<'a, T> {
17    /// Create a new MkFrameBox from a raw pointer.
18    ///
19    /// # Safety
20    ///
21    /// The pointer must be valid and properly aligned for T.
22    /// The memory must remain valid for the lifetime 'a.
23    pub(crate) unsafe fn from_raw(ptr: *mut T) -> Option<Self> {
24        NonNull::new(ptr).map(|ptr| Self {
25            ptr,
26            _marker: PhantomData,
27        })
28    }
29
30    /// Get the raw pointer.
31    pub fn as_ptr(&self) -> *const T {
32        self.ptr.as_ptr()
33    }
34
35    /// Get the raw mutable pointer.
36    pub fn as_mut_ptr(&mut self) -> *mut T {
37        self.ptr.as_ptr()
38    }
39
40    /// Leak the MkFrameBox, returning the raw pointer.
41    pub fn into_raw(self) -> *mut T {
42        let ptr = self.ptr.as_ptr();
43        std::mem::forget(self);
44        ptr
45    }
46}
47
48impl<'a, T> Deref for MkFrameBox<'a, T> {
49    type Target = T;
50
51    fn deref(&self) -> &Self::Target {
52        unsafe { self.ptr.as_ref() }
53    }
54}
55
56impl<'a, T> DerefMut for MkFrameBox<'a, T> {
57    fn deref_mut(&mut self) -> &mut Self::Target {
58        unsafe { self.ptr.as_mut() }
59    }
60}
61
62// MkFrameBox doesn't implement Drop - memory is freed in bulk at end_frame()