1use core::cell::UnsafeCell;
23pub(crate) type LazyResult<T> = LazyCell<Result<T, crate::Error>>;
45pub(crate) struct LazyCell<T> {
6 contents: UnsafeCell<Option<T>>,
7}
89impl<T> LazyCell<T> {
10pub(crate) fn new() -> LazyCell<T> {
11 LazyCell {
12 contents: UnsafeCell::new(None),
13 }
14 }
1516pub(crate) fn borrow(&self) -> Option<&T> {
17unsafe { &*self.contents.get() }.as_ref()
18 }
1920pub(crate) fn borrow_with(&self, closure: impl FnOnce() -> T) -> &T {
21// First check if we're already initialized...
22let ptr = self.contents.get();
23if let Some(val) = unsafe { &*ptr } {
24return val;
25 }
26// Note that while we're executing `closure` our `borrow_with` may
27 // be called recursively. This means we need to check again after
28 // the closure has executed. For that we use the `get_or_insert`
29 // method which will only perform mutation if we aren't already
30 // `Some`.
31let val = closure();
32unsafe { (*ptr).get_or_insert(val) }
33 }
34}