memkit 0.1.1-beta.1

Deterministic, intent-driven memory allocation for systems requiring predictable performance
Documentation
//! Frame-allocated box type.

use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::ptr::NonNull;

/// A Box-like wrapper for frame-allocated memory.
///
/// The memory is valid until `end_frame()` is called on the allocator.
/// This type does NOT free memory on drop - frame memory is bulk-freed.
pub struct MkFrameBox<'a, T> {
    ptr: NonNull<T>,
    _marker: PhantomData<&'a T>,
}

impl<'a, T> MkFrameBox<'a, T> {
    /// Create a new MkFrameBox from a raw pointer.
    ///
    /// # Safety
    ///
    /// The pointer must be valid and properly aligned for T.
    /// The memory must remain valid for the lifetime 'a.
    pub(crate) unsafe fn from_raw(ptr: *mut T) -> Option<Self> {
        NonNull::new(ptr).map(|ptr| Self {
            ptr,
            _marker: PhantomData,
        })
    }

    /// Get the raw pointer.
    pub fn as_ptr(&self) -> *const T {
        self.ptr.as_ptr()
    }

    /// Get the raw mutable pointer.
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.ptr.as_ptr()
    }

    /// Leak the MkFrameBox, returning the raw pointer.
    pub fn into_raw(self) -> *mut T {
        let ptr = self.ptr.as_ptr();
        std::mem::forget(self);
        ptr
    }
}

impl<'a, T> Deref for MkFrameBox<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { self.ptr.as_ref() }
    }
}

impl<'a, T> DerefMut for MkFrameBox<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.ptr.as_mut() }
    }
}

// MkFrameBox doesn't implement Drop - memory is freed in bulk at end_frame()