embedded_threadsafe/
lazy.rs

1//! A lazily instantiated cell
2
3use core::cell::UnsafeCell;
4
5/// A lazily instantiated cell
6pub struct LazyCell<T, I = fn() -> T> {
7    /// A tuple containing the initializer and the value
8    inner: UnsafeCell<(Option<I>, Option<T>)>,
9}
10impl<T, I> LazyCell<T, I> {
11    /// Creates a new lazy cell with the given initializer
12    pub const fn new(init: I) -> Self {
13        let value = (Some(init), None);
14        Self { inner: UnsafeCell::new(value) }
15    }
16
17    /// Provides scoped access to the underlying value, initializes it if necessary
18    ///
19    /// # Safety
20    /// This function provides unchecked, mutable access to the underlying value, so incorrect use of this function may
21    /// lead to race conditions or undefined behavior.
22    #[inline]
23    pub unsafe fn scope<F, FR>(&self, scope: F) -> FR
24    where
25        I: FnOnce() -> T,
26        F: FnOnce(&mut T) -> FR,
27    {
28        // Get the inner state
29        let inner_ptr = self.inner.get();
30        let (init, value) = inner_ptr.as_mut().expect("unexpected NULL pointer inside cell");
31
32        // Initialize the value if necessary
33        if let Some(init) = init.take() {
34            let value_ = init();
35            *value = Some(value_);
36        }
37
38        // Take the initialized value
39        let Some(value) = value.as_mut() else {
40            unreachable!("initialized cell has not value");
41        };
42
43        // Call the scope
44        scope(value)
45    }
46
47    /// Provides scoped access to the underlying value, initializes it if necessary
48    #[inline]
49    pub fn scope_mut<F, FR>(&self, scope: F) -> FR
50    where
51        I: FnOnce() -> T,
52        F: FnOnce(&mut T) -> FR,
53    {
54        unsafe { self.scope(scope) }
55    }
56}