Skip to main content

hazard3_sync/
once_lock.rs

1//! Synchronization primitive for initializing a value once, allowing others to await a reference to the value.
2
3use core::cell::Cell;
4use core::fmt::{Debug, Formatter};
5use core::future::{Future, poll_fn};
6use core::mem::MaybeUninit;
7#[cfg(not(feature = "portable-atomic"))]
8use core::sync::atomic::{AtomicBool, Ordering};
9use core::task::Poll;
10
11#[cfg(feature = "portable-atomic")]
12use portable_atomic::{AtomicBool, Ordering};
13
14/// The `OnceLock` is a synchronization primitive that allows for
15/// initializing a value once, and allowing others to `.await` a
16/// reference to the value. This is useful for lazy initialization of
17/// a static value.
18///
19/// **Note**: this implementation uses a busy loop to poll the value,
20/// which is not as efficient as registering a dedicated `Waker`.
21/// However, if the usecase for it is to initialize a static variable
22/// relatively early in the program life cycle, it should be fine.
23///
24/// # Example
25/// ```
26/// use futures_executor::block_on;
27/// use hazard3_sync::once_lock::OnceLock;
28///
29/// // Define a static value that will be lazily initialized
30/// static VALUE: OnceLock<u32> = OnceLock::new();
31///
32/// let f = async {
33///
34/// // Initialize the value
35/// let reference = VALUE.get_or_init(|| 20);
36/// assert_eq!(reference, &20);
37///
38/// // Wait for the value to be initialized
39/// // and get a static reference it
40/// assert_eq!(VALUE.get().await, &20);
41///
42/// };
43/// block_on(f)
44/// ```
45pub struct OnceLock<T> {
46    init: AtomicBool,
47    data: Cell<MaybeUninit<T>>,
48}
49
50impl<T> Debug for OnceLock<T> {
51    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
52        f.debug_struct("OnceLock")
53            .field("init", &self.init)
54            .field("data", &"Cell<MaybeUninit<{unprintable}>>")
55            .finish()
56    }
57}
58
59unsafe impl<T> Sync for OnceLock<T> where T: Sync {}
60
61impl<T> OnceLock<T> {
62    /// Create a new uninitialized `OnceLock`.
63    pub const fn new() -> Self {
64        Self {
65            init: AtomicBool::new(false),
66            data: Cell::new(MaybeUninit::zeroed()),
67        }
68    }
69
70    /// Get a reference to the underlying value, waiting for it to be set.
71    /// If the value is already set, this will return immediately.
72    pub fn get(&self) -> impl Future<Output = &T> {
73        poll_fn(|cx| match self.try_get() {
74            Some(data) => Poll::Ready(data),
75            None => {
76                cx.waker().wake_by_ref();
77                Poll::Pending
78            }
79        })
80    }
81
82    /// Try to get a reference to the underlying value if it exists.
83    pub fn try_get(&self) -> Option<&T> {
84        if self.init.load(Ordering::Acquire) {
85            Some(unsafe { self.get_ref_unchecked() })
86        } else {
87            None
88        }
89    }
90
91    /// Set the underlying value. If the value is already set, this will return an error with the given value.
92    pub fn init(&self, value: T) -> Result<(), T> {
93        // Critical section is required to ensure that the value is
94        // not simultaneously initialized elsewhere at the same time.
95        critical_section::with(|_| {
96            // If the value is not set, set it and return Ok.
97            if !self.init.load(Ordering::Relaxed) {
98                self.data.set(MaybeUninit::new(value));
99                self.init.store(true, Ordering::Release);
100                Ok(())
101
102            // Otherwise return an error with the given value.
103            } else {
104                Err(value)
105            }
106        })
107    }
108
109    /// Get a reference to the underlying value, initializing it if it does not exist.
110    pub fn get_or_init<F>(&self, f: F) -> &T
111    where
112        F: FnOnce() -> T,
113    {
114        // Critical section is required to ensure that the value is
115        // not simultaneously initialized elsewhere at the same time.
116        critical_section::with(|_| {
117            // If the value is not set, set it.
118            if !self.init.load(Ordering::Relaxed) {
119                self.data.set(MaybeUninit::new(f()));
120                self.init.store(true, Ordering::Release);
121            }
122        });
123
124        // Return a reference to the value.
125        unsafe { self.get_ref_unchecked() }
126    }
127
128    /// Consume the `OnceLock`, returning the underlying value if it was initialized.
129    pub fn into_inner(self) -> Option<T> {
130        if self.init.load(Ordering::Relaxed) {
131            Some(unsafe { self.data.into_inner().assume_init() })
132        } else {
133            None
134        }
135    }
136
137    /// Take the underlying value if it was initialized, uninitializing the `OnceLock` in the process.
138    pub fn take(&mut self) -> Option<T> {
139        // If the value is set, uninitialize the lock and return the value.
140        critical_section::with(|_| {
141            if self.init.load(Ordering::Relaxed) {
142                let val = unsafe { self.data.replace(MaybeUninit::zeroed()).assume_init() };
143                self.init.store(false, Ordering::Relaxed);
144                Some(val)
145
146            // Otherwise return None.
147            } else {
148                None
149            }
150        })
151    }
152
153    /// Check if the value has been set.
154    pub fn is_set(&self) -> bool {
155        self.init.load(Ordering::Relaxed)
156    }
157
158    /// Get a reference to the underlying value.
159    /// # Safety
160    /// Must only be used if a value has been set.
161    unsafe fn get_ref_unchecked(&self) -> &T {
162        (*self.data.as_ptr()).assume_init_ref()
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn once_lock() {
172        let lock = OnceLock::new();
173        assert_eq!(lock.try_get(), None);
174        assert_eq!(lock.is_set(), false);
175
176        let v = 42;
177        assert_eq!(lock.init(v), Ok(()));
178        assert_eq!(lock.is_set(), true);
179        assert_eq!(lock.try_get(), Some(&v));
180        assert_eq!(lock.try_get(), Some(&v));
181
182        let v = 43;
183        assert_eq!(lock.init(v), Err(v));
184        assert_eq!(lock.is_set(), true);
185        assert_eq!(lock.try_get(), Some(&42));
186    }
187
188    #[test]
189    fn once_lock_get_or_init() {
190        let lock = OnceLock::new();
191        assert_eq!(lock.try_get(), None);
192        assert_eq!(lock.is_set(), false);
193
194        let v = lock.get_or_init(|| 42);
195        assert_eq!(v, &42);
196        assert_eq!(lock.is_set(), true);
197        assert_eq!(lock.try_get(), Some(&42));
198
199        let v = lock.get_or_init(|| 43);
200        assert_eq!(v, &42);
201        assert_eq!(lock.is_set(), true);
202        assert_eq!(lock.try_get(), Some(&42));
203    }
204
205    #[test]
206    fn once_lock_static() {
207        static LOCK: OnceLock<i32> = OnceLock::new();
208
209        let v: &'static i32 = LOCK.get_or_init(|| 42);
210        assert_eq!(v, &42);
211
212        let v: &'static i32 = LOCK.get_or_init(|| 43);
213        assert_eq!(v, &42);
214    }
215
216    #[futures_test::test]
217    async fn once_lock_async() {
218        static LOCK: OnceLock<i32> = OnceLock::new();
219
220        assert!(LOCK.init(42).is_ok());
221
222        let v: &'static i32 = LOCK.get().await;
223        assert_eq!(v, &42);
224    }
225
226    #[test]
227    fn once_lock_into_inner() {
228        let lock: OnceLock<i32> = OnceLock::new();
229
230        let v = lock.get_or_init(|| 42);
231        assert_eq!(v, &42);
232
233        assert_eq!(lock.into_inner(), Some(42));
234    }
235
236    #[test]
237    fn once_lock_take_init() {
238        let mut lock: OnceLock<i32> = OnceLock::new();
239
240        assert_eq!(lock.get_or_init(|| 42), &42);
241        assert_eq!(lock.is_set(), true);
242
243        assert_eq!(lock.take(), Some(42));
244        assert_eq!(lock.is_set(), false);
245
246        assert_eq!(lock.get_or_init(|| 43), &43);
247        assert_eq!(lock.is_set(), true);
248    }
249}