use core::cell::UnsafeCell;
pub struct LazyCell<T, I = fn() -> T> {
inner: UnsafeCell<(Option<I>, Option<T>)>,
}
impl<T, I> LazyCell<T, I> {
pub const fn new(init: I) -> Self {
let value = (Some(init), None);
Self { inner: UnsafeCell::new(value) }
}
#[inline]
pub unsafe fn scope<F, FR>(&self, scope: F) -> FR
where
I: FnOnce() -> T,
F: FnOnce(&mut T) -> FR,
{
let inner_ptr = self.inner.get();
let (init, value) = inner_ptr.as_mut().expect("unexpected NULL pointer inside cell");
if let Some(init) = init.take() {
let value_ = init();
*value = Some(value_);
}
let Some(value) = value.as_mut() else {
unreachable!("initialized cell has not value");
};
scope(value)
}
#[inline]
pub fn scope_mut<F, FR>(&self, scope: F) -> FR
where
I: FnOnce() -> T,
F: FnOnce(&mut T) -> FR,
{
unsafe { self.scope(scope) }
}
}