1 use crate::cell::UnsafeCell;
3 use crate::marker::PhantomData;
4 use crate::mem::MaybeUninit;
5 use crate::panic::{RefUnwindSafe, UnwindSafe};
8 /// A synchronization primitive which can be written to only once.
10 /// This type is a thread-safe [`OnceCell`], and can be used in statics.
12 /// [`OnceCell`]: crate::cell::OnceCell
17 /// #![feature(once_cell)]
19 /// use std::sync::OnceLock;
21 /// static CELL: OnceLock<String> = OnceLock::new();
22 /// assert!(CELL.get().is_none());
24 /// std::thread::spawn(|| {
25 /// let value: &String = CELL.get_or_init(|| {
26 /// "Hello, World!".to_string()
28 /// assert_eq!(value, "Hello, World!");
29 /// }).join().unwrap();
31 /// let value: Option<&String> = CELL.get();
32 /// assert!(value.is_some());
33 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
35 #[unstable(feature = "once_cell", issue = "74465")]
36 pub struct OnceLock<T> {
38 // Whether or not the value is initialized is tracked by `once.is_completed()`.
39 value: UnsafeCell<MaybeUninit<T>>,
40 /// `PhantomData` to make sure dropck understands we're dropping T in our Drop impl.
42 /// ```compile_fail,E0597
43 /// #![feature(once_cell)]
45 /// use std::sync::OnceLock;
47 /// struct A<'a>(&'a str);
49 /// impl<'a> Drop for A<'a> {
50 /// fn drop(&mut self) {}
53 /// let cell = OnceLock::new();
55 /// let s = String::new();
56 /// let _ = cell.set(A(&s));
59 _marker: PhantomData<T>,
63 /// Creates a new empty cell.
66 #[unstable(feature = "once_cell", issue = "74465")]
67 pub const fn new() -> OnceLock<T> {
70 value: UnsafeCell::new(MaybeUninit::uninit()),
75 /// Gets the reference to the underlying value.
77 /// Returns `None` if the cell is empty, or being initialized. This
78 /// method never blocks.
80 #[unstable(feature = "once_cell", issue = "74465")]
81 pub fn get(&self) -> Option<&T> {
82 if self.is_initialized() {
83 // Safe b/c checked is_initialized
84 Some(unsafe { self.get_unchecked() })
90 /// Gets the mutable reference to the underlying value.
92 /// Returns `None` if the cell is empty. This method never blocks.
94 #[unstable(feature = "once_cell", issue = "74465")]
95 pub fn get_mut(&mut self) -> Option<&mut T> {
96 if self.is_initialized() {
97 // Safe b/c checked is_initialized and we have a unique access
98 Some(unsafe { self.get_unchecked_mut() })
104 /// Sets the contents of this cell to `value`.
106 /// May block if another thread is currently attempting to initialize the cell. The cell is
107 /// guaranteed to contain a value when set returns, though not necessarily the one provided.
109 /// Returns `Ok(())` if the cell's value was set by this call.
114 /// #![feature(once_cell)]
116 /// use std::sync::OnceLock;
118 /// static CELL: OnceLock<i32> = OnceLock::new();
121 /// assert!(CELL.get().is_none());
123 /// std::thread::spawn(|| {
124 /// assert_eq!(CELL.set(92), Ok(()));
125 /// }).join().unwrap();
127 /// assert_eq!(CELL.set(62), Err(62));
128 /// assert_eq!(CELL.get(), Some(&92));
132 #[unstable(feature = "once_cell", issue = "74465")]
133 pub fn set(&self, value: T) -> Result<(), T> {
134 let mut value = Some(value);
135 self.get_or_init(|| value.take().unwrap());
138 Some(value) => Err(value),
142 /// Gets the contents of the cell, initializing it with `f` if the cell
145 /// Many threads may call `get_or_init` concurrently with different
146 /// initializing functions, but it is guaranteed that only one function
147 /// will be executed.
151 /// If `f` panics, the panic is propagated to the caller, and the cell
152 /// remains uninitialized.
154 /// It is an error to reentrantly initialize the cell from `f`. The
155 /// exact outcome is unspecified. Current implementation deadlocks, but
156 /// this may be changed to a panic in the future.
161 /// #![feature(once_cell)]
163 /// use std::sync::OnceLock;
165 /// let cell = OnceLock::new();
166 /// let value = cell.get_or_init(|| 92);
167 /// assert_eq!(value, &92);
168 /// let value = cell.get_or_init(|| unreachable!());
169 /// assert_eq!(value, &92);
172 #[unstable(feature = "once_cell", issue = "74465")]
173 pub fn get_or_init<F>(&self, f: F) -> &T
177 match self.get_or_try_init(|| Ok::<T, !>(f())) {
182 /// Gets the contents of the cell, initializing it with `f` if
183 /// the cell was empty. If the cell was empty and `f` failed, an
184 /// error is returned.
188 /// If `f` panics, the panic is propagated to the caller, and
189 /// the cell remains uninitialized.
191 /// It is an error to reentrantly initialize the cell from `f`.
192 /// The exact outcome is unspecified. Current implementation
193 /// deadlocks, but this may be changed to a panic in the future.
198 /// #![feature(once_cell)]
200 /// use std::sync::OnceLock;
202 /// let cell = OnceLock::new();
203 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
204 /// assert!(cell.get().is_none());
205 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
208 /// assert_eq!(value, Ok(&92));
209 /// assert_eq!(cell.get(), Some(&92))
212 #[unstable(feature = "once_cell", issue = "74465")]
213 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
215 F: FnOnce() -> Result<T, E>,
218 // NOTE: We need to perform an acquire on the state in this method
219 // in order to correctly synchronize `LazyLock::force`. This is
220 // currently done by calling `self.get()`, which in turn calls
221 // `self.is_initialized()`, which in turn performs the acquire.
222 if let Some(value) = self.get() {
227 debug_assert!(self.is_initialized());
229 // SAFETY: The inner value has been initialized
230 Ok(unsafe { self.get_unchecked() })
233 /// Consumes the `OnceLock`, returning the wrapped value. Returns
234 /// `None` if the cell was empty.
239 /// #![feature(once_cell)]
241 /// use std::sync::OnceLock;
243 /// let cell: OnceLock<String> = OnceLock::new();
244 /// assert_eq!(cell.into_inner(), None);
246 /// let cell = OnceLock::new();
247 /// cell.set("hello".to_string()).unwrap();
248 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
251 #[unstable(feature = "once_cell", issue = "74465")]
252 pub fn into_inner(mut self) -> Option<T> {
256 /// Takes the value out of this `OnceLock`, moving it back to an uninitialized state.
258 /// Has no effect and returns `None` if the `OnceLock` hasn't been initialized.
260 /// Safety is guaranteed by requiring a mutable reference.
265 /// #![feature(once_cell)]
267 /// use std::sync::OnceLock;
269 /// let mut cell: OnceLock<String> = OnceLock::new();
270 /// assert_eq!(cell.take(), None);
272 /// let mut cell = OnceLock::new();
273 /// cell.set("hello".to_string()).unwrap();
274 /// assert_eq!(cell.take(), Some("hello".to_string()));
275 /// assert_eq!(cell.get(), None);
278 #[unstable(feature = "once_cell", issue = "74465")]
279 pub fn take(&mut self) -> Option<T> {
280 if self.is_initialized() {
281 self.once = Once::new();
282 // SAFETY: `self.value` is initialized and contains a valid `T`.
283 // `self.once` is reset, so `is_initialized()` will be false again
284 // which prevents the value from being read twice.
285 unsafe { Some((&mut *self.value.get()).assume_init_read()) }
292 fn is_initialized(&self) -> bool {
293 self.once.is_completed()
297 fn initialize<F, E>(&self, f: F) -> Result<(), E>
299 F: FnOnce() -> Result<T, E>,
301 let mut res: Result<(), E> = Ok(());
302 let slot = &self.value;
304 // Ignore poisoning from other threads
305 // If another thread panics, then we'll be able to run our closure
306 self.once.call_once_force(|p| {
309 unsafe { (&mut *slot.get()).write(value) };
314 // Treat the underlying `Once` as poisoned since we
315 // failed to initialize our value. Calls
325 /// The value must be initialized
327 unsafe fn get_unchecked(&self) -> &T {
328 debug_assert!(self.is_initialized());
329 (&*self.value.get()).assume_init_ref()
334 /// The value must be initialized
336 unsafe fn get_unchecked_mut(&mut self) -> &mut T {
337 debug_assert!(self.is_initialized());
338 (&mut *self.value.get()).assume_init_mut()
342 // Why do we need `T: Send`?
343 // Thread A creates a `OnceLock` and shares it with
344 // scoped thread B, which fills the cell, which is
345 // then destroyed by A. That is, destructor observes
347 #[unstable(feature = "once_cell", issue = "74465")]
348 unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
349 #[unstable(feature = "once_cell", issue = "74465")]
350 unsafe impl<T: Send> Send for OnceLock<T> {}
352 #[unstable(feature = "once_cell", issue = "74465")]
353 impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T> {}
354 #[unstable(feature = "once_cell", issue = "74465")]
355 impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {}
357 #[unstable(feature = "once_cell", issue = "74465")]
358 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
359 impl<T> const Default for OnceLock<T> {
360 /// Creates a new empty cell.
365 /// #![feature(once_cell)]
367 /// use std::sync::OnceLock;
370 /// assert_eq!(OnceLock::<()>::new(), OnceLock::default());
374 fn default() -> OnceLock<T> {
379 #[unstable(feature = "once_cell", issue = "74465")]
380 impl<T: fmt::Debug> fmt::Debug for OnceLock<T> {
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 Some(v) => f.debug_tuple("Once").field(v).finish(),
384 None => f.write_str("Once(Uninit)"),
389 #[unstable(feature = "once_cell", issue = "74465")]
390 impl<T: Clone> Clone for OnceLock<T> {
392 fn clone(&self) -> OnceLock<T> {
393 let cell = Self::new();
394 if let Some(value) = self.get() {
395 match cell.set(value.clone()) {
397 Err(_) => unreachable!(),
404 #[unstable(feature = "once_cell", issue = "74465")]
405 impl<T> From<T> for OnceLock<T> {
406 /// Create a new cell with its contents set to `value`.
411 /// #![feature(once_cell)]
413 /// use std::sync::OnceLock;
415 /// # fn main() -> Result<(), i32> {
416 /// let a = OnceLock::from(3);
417 /// let b = OnceLock::new();
419 /// assert_eq!(a, b);
424 fn from(value: T) -> Self {
425 let cell = Self::new();
426 match cell.set(value) {
428 Err(_) => unreachable!(),
433 #[unstable(feature = "once_cell", issue = "74465")]
434 impl<T: PartialEq> PartialEq for OnceLock<T> {
436 fn eq(&self, other: &OnceLock<T>) -> bool {
437 self.get() == other.get()
441 #[unstable(feature = "once_cell", issue = "74465")]
442 impl<T: Eq> Eq for OnceLock<T> {}
444 #[unstable(feature = "once_cell", issue = "74465")]
445 unsafe impl<#[may_dangle] T> Drop for OnceLock<T> {
448 if self.is_initialized() {
449 // SAFETY: The cell is initialized and being dropped, so it can't
450 // be accessed again. We also don't touch the `T` other than
451 // dropping it, which validates our usage of #[may_dangle].
452 unsafe { (&mut *self.value.get()).assume_init_drop() };