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
#![no_std]

use core::ops::*;

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

pub struct Ptr<A: ?Sized + DropPtr>(*mut A);

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

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

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

impl<A: ?Sized + DropPtr> Deref for Ptr<A> {
    type Target = A;

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

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