use crate::alloc::allocator::{AllocError, Allocator};
use core::alloc::Layout;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
pub struct Box<T> {
boxed: NonNull<T>,
}
impl<T> Box<T> {
pub fn try_new_in(value: T, alloc: &'static dyn Allocator) -> Result<Self, AllocError> {
let layout = Layout::new::<T>();
let memory = match alloc.alloc(layout) {
Ok(m) => m,
Err(e) => return Err(e),
};
let memory = memory.cast::<T>();
unsafe {
memory.as_ptr().write(value);
}
Ok(Box { boxed: memory })
}
pub unsafe fn from_raw(pointer: NonNull<T>) -> Self {
Box { boxed: pointer }
}
pub fn leak(b: Self) -> NonNull<T> {
let boxed = b.boxed;
mem::forget(b);
boxed
}
}
impl<T> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &(*self.boxed.as_ref()) }
}
}
impl<T> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut (*self.boxed.as_mut()) }
}
}
impl<'a, T> Drop for Box<T> {
fn drop(&mut self) {
panic!("Box drop not implemented yet!");
}
}