ptrait 0.1.0

A small crate providing traits for pointer-like types, such as references and smart pointers.
Documentation
use core::ptr;

use crate::{NonNullMutPtr, NonNullPtr, Ptr, PtrMut};

#[inline]
unsafe fn reborrow<'b, T: ?Sized>(r: &T) -> &'b T {
    unsafe { &*ptr::from_ref(r) }
}
#[inline]
unsafe fn reborrow_mut<'b, T: ?Sized>(r: &mut T) -> &'b mut T {
    unsafe { &mut *ptr::from_mut(r) }
}

impl<T: ?Sized> Ptr for &T {
    type Target = T;

    #[inline]
    fn as_ptr(&self) -> *const T {
        ptr::from_ref(self)
    }

    #[inline]
    fn is_null(&self) -> bool {
        false
    }

    #[inline]
    fn is_aligned(&self) -> bool {
        true
    }

    #[inline]
    unsafe fn as_ref<'b>(&self) -> Option<&'b Self::Target> {
        Some(unsafe { reborrow(*self) })
    }

    #[inline]
    unsafe fn as_ref_unchecked<'b>(&self) -> &'b Self::Target {
        unsafe { reborrow(*self) }
    }
}

unsafe impl<T: ?Sized> NonNullPtr for &T {}

impl<T: ?Sized> Ptr for &mut T {
    type Target = T;

    #[inline]
    fn as_ptr(&self) -> *const T {
        ptr::from_ref(*self)
    }

    #[inline]
    fn is_null(&self) -> bool {
        false
    }

    #[inline]
    fn is_aligned(&self) -> bool {
        true
    }

    #[inline]
    unsafe fn as_ref<'b>(&self) -> Option<&'b Self::Target> {
        Some(unsafe { reborrow(*self) })
    }

    #[inline]
    unsafe fn as_ref_unchecked<'b>(&self) -> &'b Self::Target {
        unsafe { reborrow(*self) }
    }
}
impl<T: ?Sized> PtrMut for &mut T {
    #[inline]
    fn as_mut_ptr(&mut self) -> *mut T {
        ptr::from_mut(*self)
    }

    #[inline]
    unsafe fn as_mut<'b>(&mut self) -> Option<&'b mut Self::Target> {
        Some(unsafe { reborrow_mut(self) })
    }

    #[inline]
    unsafe fn as_mut_unchecked<'b>(&mut self) -> &'b mut Self::Target {
        unsafe { reborrow_mut(self) }
    }
}

unsafe impl<T: ?Sized> NonNullPtr for &mut T {}
unsafe impl<T: ?Sized> NonNullMutPtr for &mut T {}