1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#![no_std]

use core::marker::PhantomData;
use core::ops::*;

pub unsafe trait DropPtr {
    unsafe fn drop_ptr(*mut Self);
}

pub struct Box<'a, A: ?Sized + DropPtr>(*mut A, PhantomData<&'a mut ()>);

impl<'a, A: ?Sized + DropPtr> Box<'a, A> {
    #[inline]
    pub unsafe fn new(ptr: *mut A) -> Option<Self> {
        if 0 == ptr as *mut () as usize { None } else { Some(Box(ptr, PhantomData)) }
    }

    #[inline]
    pub unsafe fn new_unchecked(ptr: *mut A) -> Self { Box(ptr, PhantomData) }
}

impl<'a, A: ?Sized + DropPtr> Drop for Box<'a, A> {
    #[inline]
    fn drop(&mut self) { unsafe { A::drop_ptr(self.0) } }
}

impl<'a, A: ?Sized + DropPtr> Deref for Box<'a, A> {
    type Target = A;

    #[inline]
    fn deref(&self) -> &A { unsafe { &*self.0 } }
}

impl<'a, A: ?Sized + DropPtr> DerefMut for Box<'a, A> {
    #[inline]
    fn deref_mut(&mut self) -> &mut A { unsafe { &mut *self.0 } }
}