1use core::panic::{RefUnwindSafe, UnwindSafe};
2
3use atomic_polyfill::{AtomicBool, Ordering};
4use critical_section::{CriticalSection, Mutex};
5
6use crate::unsync;
7
8pub(crate) struct OnceCell<T> {
9    initialized: AtomicBool,
10    // Use `unsync::OnceCell` internally since `Mutex` does not provide
11    // interior mutability and to be able to re-use `get_or_try_init`.
12    value: Mutex<unsync::OnceCell<T>>,
13}
14
15// Why do we need `T: Send`?
16// Thread A creates a `OnceCell` and shares it with
17// scoped thread B, which fills the cell, which is
18// then destroyed by A. That is, destructor observes
19// a sent value.
20unsafe impl<T: Sync + Send> Sync for OnceCell<T> {}
21unsafe impl<T: Send> Send for OnceCell<T> {}
22
23impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceCell<T> {}
24impl<T: UnwindSafe> UnwindSafe for OnceCell<T> {}
25
26impl<T> OnceCell<T> {
27    pub(crate) const fn new() -> OnceCell<T> {
28        OnceCell { initialized: AtomicBool::new(false), value: Mutex::new(unsync::OnceCell::new()) }
29    }
30
31    pub(crate) const fn with_value(value: T) -> OnceCell<T> {
32        OnceCell {
33            initialized: AtomicBool::new(true),
34            value: Mutex::new(unsync::OnceCell::with_value(value)),
35        }
36    }
37
38    #[inline]
39    pub(crate) fn is_initialized(&self) -> bool {
40        self.initialized.load(Ordering::Acquire)
41    }
42
43    #[cold]
44    pub(crate) fn initialize<F, E>(&self, f: F) -> Result<(), E>
45    where
46        F: FnOnce() -> Result<T, E>,
47    {
48        critical_section::with(|cs| {
49            let cell = self.value.borrow(cs);
50            cell.get_or_try_init(f).map(|_| {
51                self.initialized.store(true, Ordering::Release);
52            })
53        })
54    }
55
56    /// Get the reference to the underlying value, without checking if the cell
57    /// is initialized.
58    ///
59    /// # Safety
60    ///
61    /// Caller must ensure that the cell is in initialized state, and that
62    /// the contents are acquired by (synchronized to) this thread.
63    pub(crate) unsafe fn get_unchecked(&self) -> &T {
64        debug_assert!(self.is_initialized());
65        // SAFETY: The caller ensures that the value is initialized and access synchronized.
66        crate::unwrap_unchecked(self.value.borrow(CriticalSection::new()).get())
67    }
68
69    #[inline]
70    pub(crate) fn get_mut(&mut self) -> Option<&mut T> {
71        self.value.get_mut().get_mut()
72    }
73
74    #[inline]
75    pub(crate) fn into_inner(self) -> Option<T> {
76        self.value.into_inner().into_inner()
77    }
78}
79