Skip to main content

hazard3_sync/
lazy_lock.rs

1//! Synchronization primitive for initializing a value once, allowing others to get a reference to the value.
2
3use core::cell::UnsafeCell;
4use core::mem::ManuallyDrop;
5#[cfg(not(feature = "portable-atomic"))]
6use core::sync::atomic::{AtomicBool, Ordering};
7
8#[cfg(feature = "portable-atomic")]
9use portable_atomic::{AtomicBool, Ordering};
10
11/// The `LazyLock` is a synchronization primitive that allows for
12/// initializing a value once, and allowing others to obtain a
13/// reference to the value. This is useful for lazy initialization of
14/// a static value.
15///
16/// # Example
17/// ```
18/// use futures_executor::block_on;
19/// use hazard3_sync::lazy_lock::LazyLock;
20///
21/// // Define a static value that will be lazily initialized
22/// // at runtime at the first access.
23/// static VALUE: LazyLock<u32> = LazyLock::new(|| 20);
24///
25/// let reference = VALUE.get();
26/// assert_eq!(reference, &20);
27/// ```
28#[derive(Debug)]
29pub struct LazyLock<T, F = fn() -> T> {
30    init: AtomicBool,
31    data: UnsafeCell<Data<T, F>>,
32}
33
34union Data<T, F> {
35    value: ManuallyDrop<T>,
36    f: ManuallyDrop<F>,
37}
38
39unsafe impl<T, F> Sync for LazyLock<T, F>
40where
41    T: Sync,
42    F: Sync,
43{
44}
45
46impl<T, F: FnOnce() -> T> LazyLock<T, F> {
47    /// Create a new uninitialized `StaticLock`.
48    pub const fn new(init_fn: F) -> Self {
49        Self {
50            init: AtomicBool::new(false),
51            data: UnsafeCell::new(Data {
52                f: ManuallyDrop::new(init_fn),
53            }),
54        }
55    }
56
57    /// Get a reference to the underlying value, initializing it if it
58    /// has not been done already.
59    #[inline]
60    pub fn get(&self) -> &T {
61        self.ensure_init_fast();
62        unsafe { &(*self.data.get()).value }
63    }
64
65    /// Get a mutable reference to the underlying value, initializing it if it
66    /// has not been done already.
67    #[inline]
68    pub fn get_mut(&mut self) -> &mut T {
69        self.ensure_init_fast();
70        unsafe { &mut (*self.data.get()).value }
71    }
72
73    /// Consume the `LazyLock`, returning the underlying value. The
74    /// initialization function will be called if it has not been
75    /// already.
76    #[inline]
77    pub fn into_inner(self) -> T {
78        self.ensure_init_fast();
79        let this = ManuallyDrop::new(self);
80        let data = unsafe { core::ptr::read(&this.data) }.into_inner();
81
82        ManuallyDrop::into_inner(unsafe { data.value })
83    }
84
85    /// Initialize the `LazyLock` if it has not been initialized yet.
86    /// This function is a fast track to [`Self::ensure_init`]
87    /// which does not require a critical section in most cases when
88    /// the value has been initialized already.
89    /// When this function returns, `self.data` is guaranteed to be
90    /// initialized and visible on the current core.
91    #[inline]
92    fn ensure_init_fast(&self) {
93        if !self.init.load(Ordering::Acquire) {
94            self.ensure_init();
95        }
96    }
97
98    /// Initialize the `LazyLock` if it has not been initialized yet.
99    /// When this function returns, `self.data` is guaranteed to be
100    /// initialized and visible on the current core.
101    fn ensure_init(&self) {
102        critical_section::with(|_| {
103            if !self.init.load(Ordering::Acquire) {
104                let data = unsafe { &mut *self.data.get() };
105                let f = unsafe { ManuallyDrop::take(&mut data.f) };
106                let value = f();
107                data.value = ManuallyDrop::new(value);
108
109                self.init.store(true, Ordering::Release);
110            }
111        });
112    }
113}
114
115impl<T, F> Drop for LazyLock<T, F> {
116    fn drop(&mut self) {
117        if self.init.load(Ordering::Acquire) {
118            unsafe { ManuallyDrop::drop(&mut self.data.get_mut().value) };
119        } else {
120            unsafe { ManuallyDrop::drop(&mut self.data.get_mut().f) };
121        }
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use core::sync::atomic::{AtomicU32, Ordering};
128
129    use super::*;
130
131    #[test]
132    fn test_lazy_lock() {
133        static VALUE: LazyLock<u32> = LazyLock::new(|| 20);
134        let reference = VALUE.get();
135        assert_eq!(reference, &20);
136    }
137    #[test]
138    fn test_lazy_lock_mutation() {
139        let mut value: LazyLock<u32> = LazyLock::new(|| 20);
140        *value.get_mut() = 21;
141        let reference = value.get();
142        assert_eq!(reference, &21);
143    }
144    #[test]
145    fn test_lazy_lock_into_inner() {
146        let lazy: LazyLock<u32> = LazyLock::new(|| 20);
147        let value = lazy.into_inner();
148        assert_eq!(value, 20);
149    }
150
151    static DROP_CHECKER: AtomicU32 = AtomicU32::new(0);
152    #[derive(Debug)]
153    struct DropCheck;
154
155    impl Drop for DropCheck {
156        fn drop(&mut self) {
157            DROP_CHECKER.fetch_add(1, Ordering::Acquire);
158        }
159    }
160
161    #[test]
162    fn test_lazy_drop() {
163        let lazy: LazyLock<DropCheck> = LazyLock::new(|| DropCheck);
164        assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 0);
165        lazy.get();
166        drop(lazy);
167        assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 1);
168
169        let dropper = DropCheck;
170        let lazy_fn: LazyLock<u32, _> = LazyLock::new(move || {
171            let _a = dropper;
172            20
173        });
174        assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 1);
175        drop(lazy_fn);
176        assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 2);
177    }
178}