use core::cell::UnsafeCell;
pub struct LazyCell<T> {
contents: UnsafeCell<Option<T>>,
}
impl<T> LazyCell<T> {
pub fn new() -> LazyCell<T> {
LazyCell {
contents: UnsafeCell::new(None),
}
}
pub fn borrow_with(&self, closure: impl FnOnce() -> T) -> &T {
unsafe {
let ptr = self.contents.get();
if let Some(val) = &*ptr {
return val;
}
let val = closure();
(*ptr).get_or_insert(val)
}
}
}