#[cfg(loom)]
pub use loom::cell::{ConstPtr, MutPtr, UnsafeCell};
#[cfg(not(loom))]
#[derive(Debug)]
pub struct UnsafeCell<T: ?Sized>(::core::cell::UnsafeCell<T>);
#[cfg(not(loom))]
impl<T> UnsafeCell<T> {
pub fn new(data: T) -> UnsafeCell<T> {
UnsafeCell(::core::cell::UnsafeCell::new(data))
}
pub fn with<R>(&self, f: impl FnOnce(*const T) -> R) -> R {
f(self.0.get())
}
pub fn with_mut<R>(&self, f: impl FnOnce(*mut T) -> R) -> R {
f(self.0.get())
}
pub fn get(&self) -> ConstPtr<T> {
ConstPtr { ptr: self.0.get() }
}
pub fn get_mut(&self) -> MutPtr<T> {
MutPtr { ptr: self.0.get() }
}
}
#[cfg(not(loom))]
pub struct ConstPtr<T: ?Sized> {
ptr: *const T,
}
#[cfg(not(loom))]
impl<T: ?Sized> ConstPtr<T> {
pub unsafe fn deref(&self) -> &T {
&*self.ptr
}
}
#[cfg(not(loom))]
pub struct MutPtr<T: ?Sized> {
ptr: *mut T,
}
#[cfg(not(loom))]
impl<T: ?Sized> MutPtr<T> {
#[expect(clippy::mut_from_ref, reason = "UnsafeCell is allowed to create &mut from &")]
pub unsafe fn deref(&self) -> &mut T {
&mut *self.ptr
}
}
pub trait UnsafeCellExt<T: ?Sized> {
unsafe fn as_ref_unchecked(&self) -> &T;
#[expect(clippy::mut_from_ref, reason = "UnsafeCell is allowed to create &mut from &")]
unsafe fn as_mut_unchecked(&self) -> &mut T;
}
#[cfg(not(loom))]
impl<T: ?Sized> UnsafeCellExt<T> for UnsafeCell<T> {
unsafe fn as_ref_unchecked(&self) -> &T {
&*self.0.get()
}
unsafe fn as_mut_unchecked(&self) -> &mut T {
&mut *self.0.get()
}
}
#[cfg(loom)]
impl<T: ?Sized> UnsafeCellExt<T> for UnsafeCell<T> {
unsafe fn as_ref_unchecked(&self) -> &T {
panic!("UnsafeCellExt::as_ref_unchecked() is unavailable for loom::cel::UnsafeCell");
}
unsafe fn as_mut_unchecked(&self) -> &mut T {
panic!("UnsafeCellExt::as_mut_unchecked() is unavailable for loom::cel::UnsafeCell");
}
}