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