use std::{alloc, mem, ptr};
pub struct BoxAllocation<T>(*mut T);
impl<T> BoxAllocation<T> {
pub fn init(mut self, value: T) -> Box<T> {
if mem::size_of::<T>() == 0 {
return Box::new(value);
}
let ptr = mem::replace(&mut self.0, ptr::null_mut());
unsafe {
ptr::write(ptr, value);
Box::from_raw(ptr)
}
}
}
impl<T> Drop for BoxAllocation<T> {
fn drop(&mut self) {
if !self.0.is_null() {
let layout = alloc::Layout::new::<T>();
unsafe {
alloc::dealloc(self.0 as *mut u8, layout);
}
}
}
}
pub trait BoxHelper<T> {
fn alloc() -> BoxAllocation<T>;
}
impl<T> BoxHelper<T> for Box<T> {
fn alloc() -> BoxAllocation<T> {
if mem::size_of::<T>() == 0 {
return BoxAllocation(ptr::null_mut());
}
let layout = alloc::Layout::new::<T>();
BoxAllocation(unsafe {
alloc::alloc(layout) as *mut T
})
}
}