#[cfg(feature = "alloc")]
use crate::alloc::boxed::Box;
use core::borrow::Borrow;
use core::fmt;
use core::ops::Deref;
use core::ptr::NonNull;
pub struct UnsafeRef<T: ?Sized> {
ptr: NonNull<T>,
}
impl<T: ?Sized> UnsafeRef<T> {
#[inline]
pub unsafe fn from_raw(val: *const T) -> UnsafeRef<T> {
UnsafeRef {
ptr: NonNull::new_unchecked(val as *mut _),
}
}
#[inline]
pub fn into_raw(ptr: Self) -> *mut T {
ptr.ptr.as_ptr()
}
}
#[cfg(feature = "alloc")]
impl<T: ?Sized> UnsafeRef<T> {
#[inline]
pub fn from_box(val: Box<T>) -> UnsafeRef<T> {
unsafe { UnsafeRef::from_raw(Box::into_raw(val)) }
}
#[inline]
pub unsafe fn into_box(ptr: Self) -> Box<T> {
Box::from_raw(UnsafeRef::into_raw(ptr))
}
}
impl<T: ?Sized> Clone for UnsafeRef<T> {
#[inline]
fn clone(&self) -> UnsafeRef<T> {
UnsafeRef { ptr: self.ptr }
}
}
impl<T: ?Sized> Deref for UnsafeRef<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
self.as_ref()
}
}
impl<T: ?Sized> AsRef<T> for UnsafeRef<T> {
#[inline]
fn as_ref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
impl<T: ?Sized> Borrow<T> for UnsafeRef<T> {
#[inline]
fn borrow(&self) -> &T {
self.as_ref()
}
}
impl<T: fmt::Debug + ?Sized> fmt::Debug for UnsafeRef<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_ref(), f)
}
}
unsafe impl<T: ?Sized + Send> Send for UnsafeRef<T> {}
unsafe impl<T: ?Sized + Sync> Sync for UnsafeRef<T> {}