use core::{marker::PhantomData, ptr::NonNull};
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,
}
}
}
#[allow(dead_code)]
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 const fn new(ptr: *mut T) -> Option<Self> {
if let Some(pointer) = NonNull::new(ptr) {
Some(Unique {
pointer,
_marker: PhantomData,
})
} else {
None
}
}
#[inline]
pub const fn from_non_null(pointer: NonNull<T>) -> Self {
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 = "`self` will be dropped if the result is not used"]
#[inline]
pub const fn as_non_null_ptr(self) -> NonNull<T> {
self.pointer
}
#[must_use]
#[inline]
pub const unsafe fn as_ref(&self) -> &T {
unsafe { self.pointer.as_ref() }
}
#[must_use]
#[inline]
pub const 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> {
Unique {
pointer: self.pointer.cast(),
_marker: PhantomData,
}
}
}
impl<T: ?Sized> Clone for Unique<T> {
#[inline]
fn clone(&self) -> Self {
*self
}
}
impl<T: ?Sized> Copy for Unique<T> {}
impl<T: ?Sized> core::fmt::Debug for Unique<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Pointer::fmt(&self.as_ptr(), f)
}
}
impl<T: ?Sized> core::fmt::Pointer for Unique<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::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::from_non_null(pointer)
}
}