leetcode_tui_shared/
ro_cell.rsuse std::{
cell::UnsafeCell,
fmt::{self, Display},
};
pub struct RoCell<T>(UnsafeCell<Option<T>>);
unsafe impl<T> Sync for RoCell<T> {}
impl<T> RoCell<T> {
#[inline]
pub const fn new() -> Self {
Self(UnsafeCell::new(None))
}
#[inline]
pub fn init(&self, value: T) {
unsafe {
*self.0.get() = Some(value);
}
}
#[inline]
pub fn with<F>(&self, f: F)
where
F: FnOnce() -> T,
{
self.init(f());
}
}
impl<T> AsRef<T> for RoCell<T> {
fn as_ref(&self) -> &T {
unsafe { (*self.0.get()).as_ref().unwrap() }
}
}
impl<T> Display for RoCell<T>
where
T: Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_ref().fmt(f)
}
}