addr2line/
lazy.rs

1use core::cell::UnsafeCell;
2
3pub(crate) type LazyResult<T> = LazyCell<Result<T, crate::Error>>;
4
5pub(crate) struct LazyCell<T> {
6    contents: UnsafeCell<Option<T>>,
7}
8
9impl<T> LazyCell<T> {
10    pub(crate) fn new() -> LazyCell<T> {
11        LazyCell {
12            contents: UnsafeCell::new(None),
13        }
14    }
15
16    pub(crate) fn borrow(&self) -> Option<&T> {
17        unsafe { &*self.contents.get() }.as_ref()
18    }
19
20    pub(crate) fn borrow_with(&self, closure: impl FnOnce() -> T) -> &T {
21        // First check if we're already initialized...
22        let ptr = self.contents.get();
23        if let Some(val) = unsafe { &*ptr } {
24            return 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`.
31        let val = closure();
32        unsafe { (*ptr).get_or_insert(val) }
33    }
34}