#![no_std]
use core::convert::From;
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use core::ptr::NonNull;
#[repr(transparent)]
pub struct Unique<T: ?Sized>(NonNull<T>, PhantomData<T>);
unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
impl<T: Sized> Unique<T> {
#[inline]
pub const fn dangling() -> Self {
unsafe { Unique::new_unchecked(mem::align_of::<T>() as *mut T) }
}
}
impl<T: ?Sized> Unique<T> {
#[inline]
pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
Unique (NonNull::new_unchecked(ptr), PhantomData)
}
#[inline]
pub fn new(ptr: *mut T) -> Option<Self> {
if !ptr.is_null() {
Some(unsafe { Self::new_unchecked(ptr) })
} else {
None
}
}
#[inline]
pub const fn as_ptr(self) -> *mut T {
self.0.as_ptr()
}
#[inline]
pub unsafe fn as_ref(&self) -> &T {
&*self.as_ptr()
}
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
&mut *self.as_ptr()
}
#[inline]
pub const fn cast<U>(self) -> Unique<U> {
unsafe { Unique::new_unchecked(self.as_ptr() as *mut U) }
}
}
impl<T: ?Sized> Clone for Unique<T> {
#[inline]
fn clone(&self) -> Self {
*self
}
}
impl<T: ?Sized> Copy for Unique<T> {}
impl<T: ?Sized> fmt::Debug for Unique<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&self.as_ptr(), f)
}
}
impl<T: ?Sized> fmt::Pointer for Unique<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&self.as_ptr(), f)
}
}
impl<T: ?Sized> From<&mut T> for Unique<T> {
#[inline]
fn from(reference: &mut T) -> Self {
unsafe { Unique::new_unchecked(reference as _) }
}
}
impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
#[inline]
fn from(unique: Unique<T>) -> Self {
unique.0
}
}