cycle_ptr 0.1.1

Smart pointers, with cycles
Documentation
//! Module holding the [NonNull] type.
use std::fmt::{Debug, Formatter};

/// This is like the standard-library NonNull, except it holds on to a const pointer and does not allow any mutable access.
pub(crate) struct NonNull<T>
where
    T: ?Sized,
{
    /// Actual pointer.
    ///
    /// We use [std::ptr::NonNull] internally, to be granted the `null` optimization.
    ptr: std::ptr::NonNull<T>,
}

impl<T> NonNull<T>
where
    T: ?Sized,
{
    /// Create [NonNull] from a reference.
    pub(crate) const fn from_ref(r: &T) -> Self {
        unsafe {
            NonNull {
                ptr: std::ptr::NonNull::new_unchecked(r as *const T as *mut T),
            }
        }
    }

    /// Construct from a raw pointer.
    pub(crate) const fn from_ptr(p: *const T) -> Self {
        NonNull {
            ptr: std::ptr::NonNull::new(p as *mut T).expect("pointer is not null"),
        }
    }

    /// Dereference this pointer.
    ///
    /// SAFETY: caller must ensure the object lifetime is valid.
    pub(crate) const unsafe fn into_ref<'a>(self) -> &'a T {
        unsafe { self.as_ref() }
    }

    /// Dereference the underlying pointer.
    ///
    /// SAFETY: caller must ensure the object lifetime is valid.
    pub(crate) const unsafe fn as_ref<'a>(&self) -> &'a T {
        unsafe { self.ptr.as_ref() }
    }

    /// Retrieve the raw pointer.
    pub(crate) const fn as_ptr(&self) -> *const T {
        self.ptr.as_ptr()
    }
}

impl<T> Clone for NonNull<T>
where
    T: ?Sized,
{
    fn clone(&self) -> Self {
        NonNull { ptr: self.ptr }
    }
}

impl<T> PartialEq for NonNull<T>
where
    T: ?Sized,
{
    fn eq(&self, other: &NonNull<T>) -> bool {
        std::ptr::eq(self.as_ptr(), other.as_ptr())
    }
}

impl<T> Eq for NonNull<T> where T: ?Sized {}

impl<T> Debug for NonNull<T>
where
    T: ?Sized,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.ptr, f)
    }
}

unsafe impl<T> Send for NonNull<T> where T: Send + Sync + ?Sized {}
unsafe impl<T> Sync for NonNull<T> where T: Send + Sync + ?Sized {}