use core::fmt;
use core::marker::PhantomData;
use crate::ptr::NonNull;
#[doc(hidden)]
#[repr(transparent)]
pub struct Unique<T: ?Sized> {
pointer: NonNull<T>,
_marker: 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> {
#[must_use]
#[inline]
pub const fn dangling() -> Self {
Unique {
pointer: NonNull::dangling(),
_marker: PhantomData,
}
}
}
impl<T> Unique<[T]> {
#[must_use]
#[inline]
pub(crate) fn dangling_empty_slice() -> Self {
let pointer = NonNull::<T>::dangling();
Unique {
pointer: NonNull::slice_from_raw_parts(pointer, 0),
_marker: PhantomData,
}
}
}
impl<T: ?Sized> Unique<T> {
#[inline]
pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
unsafe {
Unique {
pointer: NonNull::new_unchecked(ptr),
_marker: PhantomData,
}
}
}
#[inline]
pub fn new(ptr: *mut T) -> Option<Self> {
NonNull::new(ptr).map(|pointer| Unique {
pointer,
_marker: PhantomData,
})
}
#[must_use = "`self` will be dropped if the result is not used"]
#[inline]
pub const fn as_ptr(self) -> *mut T {
self.pointer.as_ptr()
}
#[must_use]
#[inline]
pub unsafe fn as_ref(&self) -> &T {
unsafe { self.pointer.as_ref() }
}
#[must_use]
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
unsafe { self.pointer.as_mut() }
}
#[must_use = "`self` will be dropped if the result is not used"]
#[inline]
pub const fn cast<U>(self) -> Unique<U> {
unsafe { Unique::new_unchecked(self.pointer.cast().as_ptr()) }
}
}
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 {
Self::from(NonNull::from(reference))
}
}
impl<T: ?Sized> From<NonNull<T>> for Unique<T> {
#[inline]
fn from(pointer: NonNull<T>) -> Self {
Unique {
pointer,
_marker: PhantomData,
}
}
}
impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
#[inline]
fn from(unique: Unique<T>) -> Self {
unsafe { NonNull::new_unchecked(unique.as_ptr()) }
}
}