1 //! Lazy values and one-time initialization of static data.
4 cell::{Cell, UnsafeCell},
6 mem::{self, MaybeUninit},
8 panic::{RefUnwindSafe, UnwindSafe},
13 #[unstable(feature = "once_cell", issue = "74465")]
14 pub use core::lazy::*;
16 /// A synchronization primitive which can be written to only once.
18 /// This type is a thread-safe `OnceCell`.
23 /// #![feature(once_cell)]
25 /// use std::lazy::SyncOnceCell;
27 /// static CELL: SyncOnceCell<String> = SyncOnceCell::new();
28 /// assert!(CELL.get().is_none());
30 /// std::thread::spawn(|| {
31 /// let value: &String = CELL.get_or_init(|| {
32 /// "Hello, World!".to_string()
34 /// assert_eq!(value, "Hello, World!");
35 /// }).join().unwrap();
37 /// let value: Option<&String> = CELL.get();
38 /// assert!(value.is_some());
39 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
41 #[unstable(feature = "once_cell", issue = "74465")]
42 pub struct SyncOnceCell<T> {
44 // Whether or not the value is initialized is tracked by `state_and_queue`.
45 value: UnsafeCell<MaybeUninit<T>>,
48 // Why do we need `T: Send`?
49 // Thread A creates a `SyncOnceCell` and shares it with
50 // scoped thread B, which fills the cell, which is
51 // then destroyed by A. That is, destructor observes
53 #[unstable(feature = "once_cell", issue = "74465")]
54 unsafe impl<T: Sync + Send> Sync for SyncOnceCell<T> {}
55 #[unstable(feature = "once_cell", issue = "74465")]
56 unsafe impl<T: Send> Send for SyncOnceCell<T> {}
58 #[unstable(feature = "once_cell", issue = "74465")]
59 impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for SyncOnceCell<T> {}
60 #[unstable(feature = "once_cell", issue = "74465")]
61 impl<T: UnwindSafe> UnwindSafe for SyncOnceCell<T> {}
63 #[unstable(feature = "once_cell", issue = "74465")]
64 impl<T> Default for SyncOnceCell<T> {
65 fn default() -> SyncOnceCell<T> {
70 #[unstable(feature = "once_cell", issue = "74465")]
71 impl<T: fmt::Debug> fmt::Debug for SyncOnceCell<T> {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 Some(v) => f.debug_tuple("Once").field(v).finish(),
75 None => f.write_str("Once(Uninit)"),
80 #[unstable(feature = "once_cell", issue = "74465")]
81 impl<T: Clone> Clone for SyncOnceCell<T> {
82 fn clone(&self) -> SyncOnceCell<T> {
83 let cell = Self::new();
84 if let Some(value) = self.get() {
85 match cell.set(value.clone()) {
87 Err(_) => unreachable!(),
94 #[unstable(feature = "once_cell", issue = "74465")]
95 impl<T> From<T> for SyncOnceCell<T> {
96 fn from(value: T) -> Self {
97 let cell = Self::new();
98 match cell.set(value) {
100 Err(_) => unreachable!(),
105 #[unstable(feature = "once_cell", issue = "74465")]
106 impl<T: PartialEq> PartialEq for SyncOnceCell<T> {
107 fn eq(&self, other: &SyncOnceCell<T>) -> bool {
108 self.get() == other.get()
112 #[unstable(feature = "once_cell", issue = "74465")]
113 impl<T: Eq> Eq for SyncOnceCell<T> {}
115 impl<T> SyncOnceCell<T> {
116 /// Creates a new empty cell.
117 #[unstable(feature = "once_cell", issue = "74465")]
118 pub const fn new() -> SyncOnceCell<T> {
119 SyncOnceCell { once: Once::new(), value: UnsafeCell::new(MaybeUninit::uninit()) }
122 /// Gets the reference to the underlying value.
124 /// Returns `None` if the cell is empty, or being initialized. This
125 /// method never blocks.
126 #[unstable(feature = "once_cell", issue = "74465")]
127 pub fn get(&self) -> Option<&T> {
128 if self.is_initialized() {
129 // Safe b/c checked is_initialized
130 Some(unsafe { self.get_unchecked() })
136 /// Gets the mutable reference to the underlying value.
138 /// Returns `None` if the cell is empty. This method never blocks.
139 #[unstable(feature = "once_cell", issue = "74465")]
140 pub fn get_mut(&mut self) -> Option<&mut T> {
141 if self.is_initialized() {
142 // Safe b/c checked is_initialized and we have a unique access
143 Some(unsafe { self.get_unchecked_mut() })
149 /// Sets the contents of this cell to `value`.
151 /// Returns `Ok(())` if the cell's value was updated.
156 /// #![feature(once_cell)]
158 /// use std::lazy::SyncOnceCell;
160 /// static CELL: SyncOnceCell<i32> = SyncOnceCell::new();
163 /// assert!(CELL.get().is_none());
165 /// std::thread::spawn(|| {
166 /// assert_eq!(CELL.set(92), Ok(()));
167 /// }).join().unwrap();
169 /// assert_eq!(CELL.set(62), Err(62));
170 /// assert_eq!(CELL.get(), Some(&92));
173 #[unstable(feature = "once_cell", issue = "74465")]
174 pub fn set(&self, value: T) -> Result<(), T> {
175 let mut value = Some(value);
176 self.get_or_init(|| value.take().unwrap());
179 Some(value) => Err(value),
183 /// Gets the contents of the cell, initializing it with `f` if the cell
186 /// Many threads may call `get_or_init` concurrently with different
187 /// initializing functions, but it is guaranteed that only one function
188 /// will be executed.
192 /// If `f` panics, the panic is propagated to the caller, and the cell
193 /// remains uninitialized.
195 /// It is an error to reentrantly initialize the cell from `f`. The
196 /// exact outcome is unspecified. Current implementation deadlocks, but
197 /// this may be changed to a panic in the future.
202 /// #![feature(once_cell)]
204 /// use std::lazy::SyncOnceCell;
206 /// let cell = SyncOnceCell::new();
207 /// let value = cell.get_or_init(|| 92);
208 /// assert_eq!(value, &92);
209 /// let value = cell.get_or_init(|| unreachable!());
210 /// assert_eq!(value, &92);
212 #[unstable(feature = "once_cell", issue = "74465")]
213 pub fn get_or_init<F>(&self, f: F) -> &T
217 match self.get_or_try_init(|| Ok::<T, !>(f())) {
222 /// Gets the contents of the cell, initializing it with `f` if
223 /// the cell was empty. If the cell was empty and `f` failed, an
224 /// error is returned.
228 /// If `f` panics, the panic is propagated to the caller, and
229 /// the cell remains uninitialized.
231 /// It is an error to reentrantly initialize the cell from `f`.
232 /// The exact outcome is unspecified. Current implementation
233 /// deadlocks, but this may be changed to a panic in the future.
238 /// #![feature(once_cell)]
240 /// use std::lazy::SyncOnceCell;
242 /// let cell = SyncOnceCell::new();
243 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
244 /// assert!(cell.get().is_none());
245 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
248 /// assert_eq!(value, Ok(&92));
249 /// assert_eq!(cell.get(), Some(&92))
251 #[unstable(feature = "once_cell", issue = "74465")]
252 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
254 F: FnOnce() -> Result<T, E>,
257 // NOTE: We need to perform an acquire on the state in this method
258 // in order to correctly synchronize `SyncLazy::force`. This is
259 // currently done by calling `self.get()`, which in turn calls
260 // `self.is_initialized()`, which in turn performs the acquire.
261 if let Some(value) = self.get() {
266 debug_assert!(self.is_initialized());
268 // Safety: The inner value has been initialized
269 Ok(unsafe { self.get_unchecked() })
272 /// Consumes the `SyncOnceCell`, returning the wrapped value. Returns
273 /// `None` if the cell was empty.
278 /// #![feature(once_cell)]
280 /// use std::lazy::SyncOnceCell;
282 /// let cell: SyncOnceCell<String> = SyncOnceCell::new();
283 /// assert_eq!(cell.into_inner(), None);
285 /// let cell = SyncOnceCell::new();
286 /// cell.set("hello".to_string()).unwrap();
287 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
289 #[unstable(feature = "once_cell", issue = "74465")]
290 pub fn into_inner(mut self) -> Option<T> {
291 // Safety: Safe because we immediately free `self` without dropping
292 let inner = unsafe { self.take_inner() };
294 // Don't drop this `SyncOnceCell`. We just moved out one of the fields, but didn't set
295 // the state to uninitialized.
296 mem::ManuallyDrop::new(self);
300 /// Takes the value out of this `SyncOnceCell`, moving it back to an uninitialized state.
302 /// Has no effect and returns `None` if the `SyncOnceCell` hasn't been initialized.
304 /// Safety is guaranteed by requiring a mutable reference.
309 /// #![feature(once_cell)]
311 /// use std::lazy::SyncOnceCell;
313 /// let mut cell: SyncOnceCell<String> = SyncOnceCell::new();
314 /// assert_eq!(cell.take(), None);
316 /// let mut cell = SyncOnceCell::new();
317 /// cell.set("hello".to_string()).unwrap();
318 /// assert_eq!(cell.take(), Some("hello".to_string()));
319 /// assert_eq!(cell.get(), None);
321 #[unstable(feature = "once_cell", issue = "74465")]
322 pub fn take(&mut self) -> Option<T> {
323 mem::take(self).into_inner()
326 /// Takes the wrapped value out of a `SyncOnceCell`.
327 /// Afterwards the cell is no longer initialized.
329 /// Safety: The cell must now be free'd WITHOUT dropping. No other usages of the cell
330 /// are valid. Only used by `into_inner` and `drop`.
331 unsafe fn take_inner(&mut self) -> Option<T> {
332 // The mutable reference guarantees there are no other threads that can observe us
333 // taking out the wrapped value.
334 // Right after this function `self` is supposed to be freed, so it makes little sense
335 // to atomically set the state to uninitialized.
336 if self.is_initialized() {
337 let value = mem::replace(&mut self.value, UnsafeCell::new(MaybeUninit::uninit()));
338 Some(value.into_inner().assume_init())
345 fn is_initialized(&self) -> bool {
346 self.once.is_completed()
350 fn initialize<F, E>(&self, f: F) -> Result<(), E>
352 F: FnOnce() -> Result<T, E>,
354 let mut res: Result<(), E> = Ok(());
355 let slot = &self.value;
357 // Ignore poisoning from other threads
358 // If another thread panics, then we'll be able to run our closure
359 self.once.call_once_force(|p| {
362 unsafe { (&mut *slot.get()).write(value) };
367 // Treat the underlying `Once` as poisoned since we
368 // failed to initialize our value. Calls
376 /// Safety: The value must be initialized
377 unsafe fn get_unchecked(&self) -> &T {
378 debug_assert!(self.is_initialized());
379 (&*self.value.get()).get_ref()
382 /// Safety: The value must be initialized
383 unsafe fn get_unchecked_mut(&mut self) -> &mut T {
384 debug_assert!(self.is_initialized());
385 (&mut *self.value.get()).get_mut()
389 unsafe impl<#[may_dangle] T> Drop for SyncOnceCell<T> {
391 // Safety: The cell is being dropped, so it can't be accessed again.
392 // We also don't touch the `T`, which validates our usage of #[may_dangle].
393 unsafe { self.take_inner() };
397 /// A value which is initialized on the first access.
399 /// This type is a thread-safe `Lazy`, and can be used in statics.
404 /// #![feature(once_cell)]
406 /// use std::collections::HashMap;
408 /// use std::lazy::SyncLazy;
410 /// static HASHMAP: SyncLazy<HashMap<i32, String>> = SyncLazy::new(|| {
411 /// println!("initializing");
412 /// let mut m = HashMap::new();
413 /// m.insert(13, "Spica".to_string());
414 /// m.insert(74, "Hoyten".to_string());
419 /// println!("ready");
420 /// std::thread::spawn(|| {
421 /// println!("{:?}", HASHMAP.get(&13));
422 /// }).join().unwrap();
423 /// println!("{:?}", HASHMAP.get(&74));
429 /// // Some("Hoyten")
432 #[unstable(feature = "once_cell", issue = "74465")]
433 pub struct SyncLazy<T, F = fn() -> T> {
434 cell: SyncOnceCell<T>,
435 init: Cell<Option<F>>,
438 #[unstable(feature = "once_cell", issue = "74465")]
439 impl<T: fmt::Debug, F> fmt::Debug for SyncLazy<T, F> {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
445 // We never create a `&F` from a `&SyncLazy<T, F>` so it is fine
446 // to not impl `Sync` for `F`
447 // we do create a `&mut Option<F>` in `force`, but this is
448 // properly synchronized, so it only happens once
449 // so it also does not contribute to this impl.
450 #[unstable(feature = "once_cell", issue = "74465")]
451 unsafe impl<T, F: Send> Sync for SyncLazy<T, F> where SyncOnceCell<T>: Sync {}
452 // auto-derived `Send` impl is OK.
454 #[unstable(feature = "once_cell", issue = "74465")]
455 impl<T, F: UnwindSafe> RefUnwindSafe for SyncLazy<T, F> where SyncOnceCell<T>: RefUnwindSafe {}
456 #[unstable(feature = "once_cell", issue = "74465")]
457 impl<T, F: UnwindSafe> UnwindSafe for SyncLazy<T, F> where SyncOnceCell<T>: UnwindSafe {}
459 impl<T, F> SyncLazy<T, F> {
460 /// Creates a new lazy value with the given initializing
462 #[unstable(feature = "once_cell", issue = "74465")]
463 pub const fn new(f: F) -> SyncLazy<T, F> {
464 SyncLazy { cell: SyncOnceCell::new(), init: Cell::new(Some(f)) }
468 impl<T, F: FnOnce() -> T> SyncLazy<T, F> {
469 /// Forces the evaluation of this lazy value and
470 /// returns a reference to result. This is equivalent
471 /// to the `Deref` impl, but is explicit.
476 /// #![feature(once_cell)]
478 /// use std::lazy::SyncLazy;
480 /// let lazy = SyncLazy::new(|| 92);
482 /// assert_eq!(SyncLazy::force(&lazy), &92);
483 /// assert_eq!(&*lazy, &92);
485 #[unstable(feature = "once_cell", issue = "74465")]
486 pub fn force(this: &SyncLazy<T, F>) -> &T {
487 this.cell.get_or_init(|| match this.init.take() {
489 None => panic!("Lazy instance has previously been poisoned"),
494 #[unstable(feature = "once_cell", issue = "74465")]
495 impl<T, F: FnOnce() -> T> Deref for SyncLazy<T, F> {
497 fn deref(&self) -> &T {
498 SyncLazy::force(self)
502 #[unstable(feature = "once_cell", issue = "74465")]
503 impl<T: Default> Default for SyncLazy<T> {
504 /// Creates a new lazy value using `Default` as the initializing function.
505 fn default() -> SyncLazy<T> {
506 SyncLazy::new(T::default)
513 lazy::{Lazy, SyncLazy, SyncOnceCell},
516 atomic::{AtomicUsize, Ordering::SeqCst},
525 static CALLED: AtomicUsize = AtomicUsize::new(0);
528 impl Default for Foo {
529 fn default() -> Self {
530 CALLED.fetch_add(1, SeqCst);
535 let lazy: Lazy<Mutex<Foo>> = <_>::default();
537 assert_eq!(CALLED.load(SeqCst), 0);
539 assert_eq!(lazy.lock().unwrap().0, 42);
540 assert_eq!(CALLED.load(SeqCst), 1);
542 lazy.lock().unwrap().0 = 21;
544 assert_eq!(lazy.lock().unwrap().0, 21);
545 assert_eq!(CALLED.load(SeqCst), 1);
549 fn lazy_poisoning() {
550 let x: Lazy<String> = Lazy::new(|| panic!("kaboom"));
552 let res = panic::catch_unwind(panic::AssertUnwindSafe(|| x.len()));
553 assert!(res.is_err());
557 fn spawn_and_wait<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> R {
558 thread::spawn(f).join().unwrap()
562 fn sync_once_cell() {
563 static ONCE_CELL: SyncOnceCell<i32> = SyncOnceCell::new();
565 assert!(ONCE_CELL.get().is_none());
568 ONCE_CELL.get_or_init(|| 92);
569 assert_eq!(ONCE_CELL.get(), Some(&92));
572 ONCE_CELL.get_or_init(|| panic!("Kabom!"));
573 assert_eq!(ONCE_CELL.get(), Some(&92));
577 fn sync_once_cell_get_mut() {
578 let mut c = SyncOnceCell::new();
579 assert!(c.get_mut().is_none());
581 *c.get_mut().unwrap() += 2;
582 assert_eq!(c.get_mut(), Some(&mut 92));
586 fn sync_once_cell_get_unchecked() {
587 let c = SyncOnceCell::new();
590 assert_eq!(c.get_unchecked(), &92);
595 fn sync_once_cell_drop() {
596 static DROP_CNT: AtomicUsize = AtomicUsize::new(0);
598 impl Drop for Dropper {
600 DROP_CNT.fetch_add(1, SeqCst);
604 let x = SyncOnceCell::new();
605 spawn_and_wait(move || {
606 x.get_or_init(|| Dropper);
607 assert_eq!(DROP_CNT.load(SeqCst), 0);
611 assert_eq!(DROP_CNT.load(SeqCst), 1);
615 fn sync_once_cell_drop_empty() {
616 let x = SyncOnceCell::<String>::new();
622 let s = SyncOnceCell::new();
624 assert!(c.get().is_none());
626 s.set("hello".to_string()).unwrap();
628 assert_eq!(c.get().map(String::as_str), Some("hello"));
632 fn get_or_try_init() {
633 let cell: SyncOnceCell<String> = SyncOnceCell::new();
634 assert!(cell.get().is_none());
636 let res = panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() }));
637 assert!(res.is_err());
638 assert!(!cell.is_initialized());
639 assert!(cell.get().is_none());
641 assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
644 cell.get_or_try_init(|| Ok::<_, ()>("hello".to_string())),
645 Ok(&"hello".to_string())
647 assert_eq!(cell.get(), Some(&"hello".to_string()));
652 assert_eq!(SyncOnceCell::from("value").get(), Some(&"value"));
653 assert_ne!(SyncOnceCell::from("foo").get(), Some(&"bar"));
657 fn partialeq_impl() {
658 assert!(SyncOnceCell::from("value") == SyncOnceCell::from("value"));
659 assert!(SyncOnceCell::from("foo") != SyncOnceCell::from("bar"));
661 assert!(SyncOnceCell::<String>::new() == SyncOnceCell::new());
662 assert!(SyncOnceCell::<String>::new() != SyncOnceCell::from("value".to_owned()));
667 let cell: SyncOnceCell<String> = SyncOnceCell::new();
668 assert_eq!(cell.into_inner(), None);
669 let cell = SyncOnceCell::new();
670 cell.set("hello".to_string()).unwrap();
671 assert_eq!(cell.into_inner(), Some("hello".to_string()));
676 static CALLED: AtomicUsize = AtomicUsize::new(0);
677 static SYNC_LAZY: SyncLazy<i32> = SyncLazy::new(|| {
678 CALLED.fetch_add(1, SeqCst);
682 assert_eq!(CALLED.load(SeqCst), 0);
685 let y = *SYNC_LAZY - 30;
687 assert_eq!(CALLED.load(SeqCst), 1);
690 let y = *SYNC_LAZY - 30;
692 assert_eq!(CALLED.load(SeqCst), 1);
696 fn sync_lazy_default() {
697 static CALLED: AtomicUsize = AtomicUsize::new(0);
700 impl Default for Foo {
701 fn default() -> Self {
702 CALLED.fetch_add(1, SeqCst);
707 let lazy: SyncLazy<Mutex<Foo>> = <_>::default();
709 assert_eq!(CALLED.load(SeqCst), 0);
711 assert_eq!(lazy.lock().unwrap().0, 42);
712 assert_eq!(CALLED.load(SeqCst), 1);
714 lazy.lock().unwrap().0 = 21;
716 assert_eq!(lazy.lock().unwrap().0, 21);
717 assert_eq!(CALLED.load(SeqCst), 1);
721 fn static_sync_lazy() {
722 static XS: SyncLazy<Vec<i32>> = SyncLazy::new(|| {
723 let mut xs = Vec::new();
731 assert_eq!(&*XS, &vec![1, 2, 3]);
734 assert_eq!(&*XS, &vec![1, 2, 3]);
738 fn static_sync_lazy_via_fn() {
739 fn xs() -> &'static Vec<i32> {
740 static XS: SyncOnceCell<Vec<i32>> = SyncOnceCell::new();
742 let mut xs = Vec::new();
749 assert_eq!(xs(), &vec![1, 2, 3]);
753 fn sync_lazy_poisoning() {
754 let x: SyncLazy<String> = SyncLazy::new(|| panic!("kaboom"));
756 let res = panic::catch_unwind(|| x.len());
757 assert!(res.is_err());
763 fn assert_traits<T: Send + Sync>() {}
764 assert_traits::<SyncOnceCell<String>>();
765 assert_traits::<SyncLazy<String>>();
769 fn eval_once_macro() {
770 macro_rules! eval_once {
774 static ONCE_CELL: SyncOnceCell<$ty> = SyncOnceCell::new();
778 ONCE_CELL.get_or_init(init)
782 let fib: &'static Vec<i32> = eval_once! {
784 let mut res = vec![1, 1];
786 let next = res[i] + res[i + 1];
792 assert_eq!(fib[5], 8)
796 fn sync_once_cell_does_not_leak_partially_constructed_boxes() {
797 static ONCE_CELL: SyncOnceCell<String> = SyncOnceCell::new();
801 const MSG: &str = "Hello, World";
803 let (tx, rx) = channel();
805 for _ in 0..n_readers {
807 thread::spawn(move || {
809 if let Some(msg) = ONCE_CELL.get() {
810 tx.send(msg).unwrap();
813 #[cfg(target_env = "sgx")]
814 crate::thread::yield_now();
818 for _ in 0..n_writers {
819 thread::spawn(move || {
820 let _ = ONCE_CELL.set(MSG.to_owned());
824 for _ in 0..n_readers {
825 let msg = rx.recv().unwrap();
826 assert_eq!(msg, MSG);
832 let cell = SyncOnceCell::new();
834 let s = String::new();
835 cell.set(&s).unwrap();