use core::{
cell::Cell,
fmt::{Debug, Formatter, Result},
marker::PhantomPinned,
pin::Pin,
};
pub type Shared<'a, T> = Pin<&'a mut SharedCell<'a, T>>;
#[doc = include_str!("../examples/shared_cell.rs")]
#[doc = include_str!("../examples/should_fail/shared_cell.rs")]
pub struct SharedCell<'a, T: ?Sized>(&'a Cell<T>, PhantomPinned);
impl<T: ?Sized> Debug for SharedCell<'_, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_tuple("SharedCell")
.field(&format_args!("_"))
.finish()
}
}
impl<'a, T: ?Sized> SharedCell<'a, T> {
pub fn new(value: &'a mut T) -> Self {
Self(Cell::from_mut(value), PhantomPinned)
}
pub unsafe fn duplicate(&mut self) -> Self {
Self(self.0, PhantomPinned)
}
pub fn with<R>(
self: &mut Pin<&mut Self>,
f: impl FnOnce(&mut T) -> R,
) -> R {
unsafe { f(&mut *self.0.as_ptr()) }
}
pub fn into_inner(self) -> &'a mut T {
unsafe { &mut *self.0.as_ptr() }
}
}