]> git.lizzy.rs Git - rust.git/blob - library/std/src/lazy.rs
Enable to ping RISC-V group via triagebot
[rust.git] / library / std / src / lazy.rs
1 //! Lazy values and one-time initialization of static data.
2
3 use crate::{
4     cell::{Cell, UnsafeCell},
5     fmt,
6     mem::{self, MaybeUninit},
7     ops::{Deref, Drop},
8     panic::{RefUnwindSafe, UnwindSafe},
9     sync::Once,
10 };
11
12 #[doc(inline)]
13 #[unstable(feature = "once_cell", issue = "74465")]
14 pub use core::lazy::*;
15
16 /// A synchronization primitive which can be written to only once.
17 ///
18 /// This type is a thread-safe `OnceCell`.
19 ///
20 /// # Examples
21 ///
22 /// ```
23 /// #![feature(once_cell)]
24 ///
25 /// use std::lazy::SyncOnceCell;
26 ///
27 /// static CELL: SyncOnceCell<String> = SyncOnceCell::new();
28 /// assert!(CELL.get().is_none());
29 ///
30 /// std::thread::spawn(|| {
31 ///     let value: &String = CELL.get_or_init(|| {
32 ///         "Hello, World!".to_string()
33 ///     });
34 ///     assert_eq!(value, "Hello, World!");
35 /// }).join().unwrap();
36 ///
37 /// let value: Option<&String> = CELL.get();
38 /// assert!(value.is_some());
39 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
40 /// ```
41 #[unstable(feature = "once_cell", issue = "74465")]
42 pub struct SyncOnceCell<T> {
43     once: Once,
44     // Whether or not the value is initialized is tracked by `state_and_queue`.
45     value: UnsafeCell<MaybeUninit<T>>,
46 }
47
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
52 // a sent value.
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> {}
57
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> {}
62
63 #[unstable(feature = "once_cell", issue = "74465")]
64 impl<T> Default for SyncOnceCell<T> {
65     fn default() -> SyncOnceCell<T> {
66         SyncOnceCell::new()
67     }
68 }
69
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 {
73         match self.get() {
74             Some(v) => f.debug_tuple("Once").field(v).finish(),
75             None => f.write_str("Once(Uninit)"),
76         }
77     }
78 }
79
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()) {
86                 Ok(()) => (),
87                 Err(_) => unreachable!(),
88             }
89         }
90         cell
91     }
92 }
93
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) {
99             Ok(()) => cell,
100             Err(_) => unreachable!(),
101         }
102     }
103 }
104
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()
109     }
110 }
111
112 #[unstable(feature = "once_cell", issue = "74465")]
113 impl<T: Eq> Eq for SyncOnceCell<T> {}
114
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()) }
120     }
121
122     /// Gets the reference to the underlying value.
123     ///
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() })
131         } else {
132             None
133         }
134     }
135
136     /// Gets the mutable reference to the underlying value.
137     ///
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() })
144         } else {
145             None
146         }
147     }
148
149     /// Sets the contents of this cell to `value`.
150     ///
151     /// Returns `Ok(())` if the cell's value was updated.
152     ///
153     /// # Examples
154     ///
155     /// ```
156     /// #![feature(once_cell)]
157     ///
158     /// use std::lazy::SyncOnceCell;
159     ///
160     /// static CELL: SyncOnceCell<i32> = SyncOnceCell::new();
161     ///
162     /// fn main() {
163     ///     assert!(CELL.get().is_none());
164     ///
165     ///     std::thread::spawn(|| {
166     ///         assert_eq!(CELL.set(92), Ok(()));
167     ///     }).join().unwrap();
168     ///
169     ///     assert_eq!(CELL.set(62), Err(62));
170     ///     assert_eq!(CELL.get(), Some(&92));
171     /// }
172     /// ```
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());
177         match value {
178             None => Ok(()),
179             Some(value) => Err(value),
180         }
181     }
182
183     /// Gets the contents of the cell, initializing it with `f` if the cell
184     /// was empty.
185     ///
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.
189     ///
190     /// # Panics
191     ///
192     /// If `f` panics, the panic is propagated to the caller, and the cell
193     /// remains uninitialized.
194     ///
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.
198     ///
199     /// # Examples
200     ///
201     /// ```
202     /// #![feature(once_cell)]
203     ///
204     /// use std::lazy::SyncOnceCell;
205     ///
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);
211     /// ```
212     #[unstable(feature = "once_cell", issue = "74465")]
213     pub fn get_or_init<F>(&self, f: F) -> &T
214     where
215         F: FnOnce() -> T,
216     {
217         match self.get_or_try_init(|| Ok::<T, !>(f())) {
218             Ok(val) => val,
219         }
220     }
221
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.
225     ///
226     /// # Panics
227     ///
228     /// If `f` panics, the panic is propagated to the caller, and
229     /// the cell remains uninitialized.
230     ///
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.
234     ///
235     /// # Examples
236     ///
237     /// ```
238     /// #![feature(once_cell)]
239     ///
240     /// use std::lazy::SyncOnceCell;
241     ///
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, ()> {
246     ///     Ok(92)
247     /// });
248     /// assert_eq!(value, Ok(&92));
249     /// assert_eq!(cell.get(), Some(&92))
250     /// ```
251     #[unstable(feature = "once_cell", issue = "74465")]
252     pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
253     where
254         F: FnOnce() -> Result<T, E>,
255     {
256         // Fast path check
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() {
262             return Ok(value);
263         }
264         self.initialize(f)?;
265
266         debug_assert!(self.is_initialized());
267
268         // Safety: The inner value has been initialized
269         Ok(unsafe { self.get_unchecked() })
270     }
271
272     /// Consumes the `SyncOnceCell`, returning the wrapped value. Returns
273     /// `None` if the cell was empty.
274     ///
275     /// # Examples
276     ///
277     /// ```
278     /// #![feature(once_cell)]
279     ///
280     /// use std::lazy::SyncOnceCell;
281     ///
282     /// let cell: SyncOnceCell<String> = SyncOnceCell::new();
283     /// assert_eq!(cell.into_inner(), None);
284     ///
285     /// let cell = SyncOnceCell::new();
286     /// cell.set("hello".to_string()).unwrap();
287     /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
288     /// ```
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() };
293
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);
297         inner
298     }
299
300     /// Takes the value out of this `SyncOnceCell`, moving it back to an uninitialized state.
301     ///
302     /// Has no effect and returns `None` if the `SyncOnceCell` hasn't been initialized.
303     ///
304     /// Safety is guaranteed by requiring a mutable reference.
305     ///
306     /// # Examples
307     ///
308     /// ```
309     /// #![feature(once_cell)]
310     ///
311     /// use std::lazy::SyncOnceCell;
312     ///
313     /// let mut cell: SyncOnceCell<String> = SyncOnceCell::new();
314     /// assert_eq!(cell.take(), None);
315     ///
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);
320     /// ```
321     #[unstable(feature = "once_cell", issue = "74465")]
322     pub fn take(&mut self) -> Option<T> {
323         mem::take(self).into_inner()
324     }
325
326     /// Takes the wrapped value out of a `SyncOnceCell`.
327     /// Afterwards the cell is no longer initialized.
328     ///
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())
339         } else {
340             None
341         }
342     }
343
344     #[inline]
345     fn is_initialized(&self) -> bool {
346         self.once.is_completed()
347     }
348
349     #[cold]
350     fn initialize<F, E>(&self, f: F) -> Result<(), E>
351     where
352         F: FnOnce() -> Result<T, E>,
353     {
354         let mut res: Result<(), E> = Ok(());
355         let slot = &self.value;
356
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| {
360             match f() {
361                 Ok(value) => {
362                     unsafe { (&mut *slot.get()).write(value) };
363                 }
364                 Err(e) => {
365                     res = Err(e);
366
367                     // Treat the underlying `Once` as poisoned since we
368                     // failed to initialize our value. Calls
369                     p.poison();
370                 }
371             }
372         });
373         res
374     }
375
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()
380     }
381
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()
386     }
387 }
388
389 impl<T> Drop for SyncOnceCell<T> {
390     fn drop(&mut self) {
391         // Safety: The cell is being dropped, so it can't be accessed again
392         unsafe { self.take_inner() };
393     }
394 }
395
396 /// A value which is initialized on the first access.
397 ///
398 /// This type is a thread-safe `Lazy`, and can be used in statics.
399 ///
400 /// # Examples
401 ///
402 /// ```
403 /// #![feature(once_cell)]
404 ///
405 /// use std::collections::HashMap;
406 ///
407 /// use std::lazy::SyncLazy;
408 ///
409 /// static HASHMAP: SyncLazy<HashMap<i32, String>> = SyncLazy::new(|| {
410 ///     println!("initializing");
411 ///     let mut m = HashMap::new();
412 ///     m.insert(13, "Spica".to_string());
413 ///     m.insert(74, "Hoyten".to_string());
414 ///     m
415 /// });
416 ///
417 /// fn main() {
418 ///     println!("ready");
419 ///     std::thread::spawn(|| {
420 ///         println!("{:?}", HASHMAP.get(&13));
421 ///     }).join().unwrap();
422 ///     println!("{:?}", HASHMAP.get(&74));
423 ///
424 ///     // Prints:
425 ///     //   ready
426 ///     //   initializing
427 ///     //   Some("Spica")
428 ///     //   Some("Hoyten")
429 /// }
430 /// ```
431 #[unstable(feature = "once_cell", issue = "74465")]
432 pub struct SyncLazy<T, F = fn() -> T> {
433     cell: SyncOnceCell<T>,
434     init: Cell<Option<F>>,
435 }
436
437 #[unstable(feature = "once_cell", issue = "74465")]
438 impl<T: fmt::Debug, F> fmt::Debug for SyncLazy<T, F> {
439     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440         f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
441     }
442 }
443
444 // We never create a `&F` from a `&SyncLazy<T, F>` so it is fine
445 // to not impl `Sync` for `F`
446 // we do create a `&mut Option<F>` in `force`, but this is
447 // properly synchronized, so it only happens once
448 // so it also does not contribute to this impl.
449 #[unstable(feature = "once_cell", issue = "74465")]
450 unsafe impl<T, F: Send> Sync for SyncLazy<T, F> where SyncOnceCell<T>: Sync {}
451 // auto-derived `Send` impl is OK.
452
453 #[unstable(feature = "once_cell", issue = "74465")]
454 impl<T, F: RefUnwindSafe> RefUnwindSafe for SyncLazy<T, F> where SyncOnceCell<T>: RefUnwindSafe {}
455
456 impl<T, F> SyncLazy<T, F> {
457     /// Creates a new lazy value with the given initializing
458     /// function.
459     #[unstable(feature = "once_cell", issue = "74465")]
460     pub const fn new(f: F) -> SyncLazy<T, F> {
461         SyncLazy { cell: SyncOnceCell::new(), init: Cell::new(Some(f)) }
462     }
463 }
464
465 impl<T, F: FnOnce() -> T> SyncLazy<T, F> {
466     /// Forces the evaluation of this lazy value and
467     /// returns a reference to result. This is equivalent
468     /// to the `Deref` impl, but is explicit.
469     ///
470     /// # Examples
471     ///
472     /// ```
473     /// #![feature(once_cell)]
474     ///
475     /// use std::lazy::SyncLazy;
476     ///
477     /// let lazy = SyncLazy::new(|| 92);
478     ///
479     /// assert_eq!(SyncLazy::force(&lazy), &92);
480     /// assert_eq!(&*lazy, &92);
481     /// ```
482     #[unstable(feature = "once_cell", issue = "74465")]
483     pub fn force(this: &SyncLazy<T, F>) -> &T {
484         this.cell.get_or_init(|| match this.init.take() {
485             Some(f) => f(),
486             None => panic!("Lazy instance has previously been poisoned"),
487         })
488     }
489 }
490
491 #[unstable(feature = "once_cell", issue = "74465")]
492 impl<T, F: FnOnce() -> T> Deref for SyncLazy<T, F> {
493     type Target = T;
494     fn deref(&self) -> &T {
495         SyncLazy::force(self)
496     }
497 }
498
499 #[unstable(feature = "once_cell", issue = "74465")]
500 impl<T: Default> Default for SyncLazy<T> {
501     /// Creates a new lazy value using `Default` as the initializing function.
502     fn default() -> SyncLazy<T> {
503         SyncLazy::new(T::default)
504     }
505 }
506
507 #[cfg(test)]
508 mod tests {
509     use crate::{
510         lazy::{Lazy, SyncLazy, SyncOnceCell},
511         panic,
512         sync::{
513             atomic::{AtomicUsize, Ordering::SeqCst},
514             mpsc::channel,
515             Mutex,
516         },
517     };
518
519     #[test]
520     fn lazy_default() {
521         static CALLED: AtomicUsize = AtomicUsize::new(0);
522
523         struct Foo(u8);
524         impl Default for Foo {
525             fn default() -> Self {
526                 CALLED.fetch_add(1, SeqCst);
527                 Foo(42)
528             }
529         }
530
531         let lazy: Lazy<Mutex<Foo>> = <_>::default();
532
533         assert_eq!(CALLED.load(SeqCst), 0);
534
535         assert_eq!(lazy.lock().unwrap().0, 42);
536         assert_eq!(CALLED.load(SeqCst), 1);
537
538         lazy.lock().unwrap().0 = 21;
539
540         assert_eq!(lazy.lock().unwrap().0, 21);
541         assert_eq!(CALLED.load(SeqCst), 1);
542     }
543
544     #[test]
545     fn lazy_poisoning() {
546         let x: Lazy<String> = Lazy::new(|| panic!("kaboom"));
547         for _ in 0..2 {
548             let res = panic::catch_unwind(panic::AssertUnwindSafe(|| x.len()));
549             assert!(res.is_err());
550         }
551     }
552
553     // miri doesn't support threads
554     #[cfg(not(miri))]
555     fn spawn_and_wait<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> R {
556         crate::thread::spawn(f).join().unwrap()
557     }
558
559     #[cfg(not(miri))]
560     fn spawn(f: impl FnOnce() + Send + 'static) {
561         let _ = crate::thread::spawn(f);
562     }
563
564     // "stub threads" for Miri
565     #[cfg(miri)]
566     fn spawn_and_wait<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> R {
567         f(())
568     }
569
570     #[cfg(miri)]
571     fn spawn(f: impl FnOnce() + Send + 'static) {
572         f(())
573     }
574
575     #[test]
576     fn sync_once_cell() {
577         static ONCE_CELL: SyncOnceCell<i32> = SyncOnceCell::new();
578
579         assert!(ONCE_CELL.get().is_none());
580
581         spawn_and_wait(|| {
582             ONCE_CELL.get_or_init(|| 92);
583             assert_eq!(ONCE_CELL.get(), Some(&92));
584         });
585
586         ONCE_CELL.get_or_init(|| panic!("Kabom!"));
587         assert_eq!(ONCE_CELL.get(), Some(&92));
588     }
589
590     #[test]
591     fn sync_once_cell_get_mut() {
592         let mut c = SyncOnceCell::new();
593         assert!(c.get_mut().is_none());
594         c.set(90).unwrap();
595         *c.get_mut().unwrap() += 2;
596         assert_eq!(c.get_mut(), Some(&mut 92));
597     }
598
599     #[test]
600     fn sync_once_cell_get_unchecked() {
601         let c = SyncOnceCell::new();
602         c.set(92).unwrap();
603         unsafe {
604             assert_eq!(c.get_unchecked(), &92);
605         }
606     }
607
608     #[test]
609     fn sync_once_cell_drop() {
610         static DROP_CNT: AtomicUsize = AtomicUsize::new(0);
611         struct Dropper;
612         impl Drop for Dropper {
613             fn drop(&mut self) {
614                 DROP_CNT.fetch_add(1, SeqCst);
615             }
616         }
617
618         let x = SyncOnceCell::new();
619         spawn_and_wait(move || {
620             x.get_or_init(|| Dropper);
621             assert_eq!(DROP_CNT.load(SeqCst), 0);
622             drop(x);
623         });
624
625         assert_eq!(DROP_CNT.load(SeqCst), 1);
626     }
627
628     #[test]
629     fn sync_once_cell_drop_empty() {
630         let x = SyncOnceCell::<String>::new();
631         drop(x);
632     }
633
634     #[test]
635     fn clone() {
636         let s = SyncOnceCell::new();
637         let c = s.clone();
638         assert!(c.get().is_none());
639
640         s.set("hello".to_string()).unwrap();
641         let c = s.clone();
642         assert_eq!(c.get().map(String::as_str), Some("hello"));
643     }
644
645     #[test]
646     fn get_or_try_init() {
647         let cell: SyncOnceCell<String> = SyncOnceCell::new();
648         assert!(cell.get().is_none());
649
650         let res = panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() }));
651         assert!(res.is_err());
652         assert!(!cell.is_initialized());
653         assert!(cell.get().is_none());
654
655         assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
656
657         assert_eq!(
658             cell.get_or_try_init(|| Ok::<_, ()>("hello".to_string())),
659             Ok(&"hello".to_string())
660         );
661         assert_eq!(cell.get(), Some(&"hello".to_string()));
662     }
663
664     #[test]
665     fn from_impl() {
666         assert_eq!(SyncOnceCell::from("value").get(), Some(&"value"));
667         assert_ne!(SyncOnceCell::from("foo").get(), Some(&"bar"));
668     }
669
670     #[test]
671     fn partialeq_impl() {
672         assert!(SyncOnceCell::from("value") == SyncOnceCell::from("value"));
673         assert!(SyncOnceCell::from("foo") != SyncOnceCell::from("bar"));
674
675         assert!(SyncOnceCell::<String>::new() == SyncOnceCell::new());
676         assert!(SyncOnceCell::<String>::new() != SyncOnceCell::from("value".to_owned()));
677     }
678
679     #[test]
680     fn into_inner() {
681         let cell: SyncOnceCell<String> = SyncOnceCell::new();
682         assert_eq!(cell.into_inner(), None);
683         let cell = SyncOnceCell::new();
684         cell.set("hello".to_string()).unwrap();
685         assert_eq!(cell.into_inner(), Some("hello".to_string()));
686     }
687
688     #[test]
689     fn sync_lazy_new() {
690         static CALLED: AtomicUsize = AtomicUsize::new(0);
691         static SYNC_LAZY: SyncLazy<i32> = SyncLazy::new(|| {
692             CALLED.fetch_add(1, SeqCst);
693             92
694         });
695
696         assert_eq!(CALLED.load(SeqCst), 0);
697
698         spawn_and_wait(|| {
699             let y = *SYNC_LAZY - 30;
700             assert_eq!(y, 62);
701             assert_eq!(CALLED.load(SeqCst), 1);
702         });
703
704         let y = *SYNC_LAZY - 30;
705         assert_eq!(y, 62);
706         assert_eq!(CALLED.load(SeqCst), 1);
707     }
708
709     #[test]
710     fn sync_lazy_default() {
711         static CALLED: AtomicUsize = AtomicUsize::new(0);
712
713         struct Foo(u8);
714         impl Default for Foo {
715             fn default() -> Self {
716                 CALLED.fetch_add(1, SeqCst);
717                 Foo(42)
718             }
719         }
720
721         let lazy: SyncLazy<Mutex<Foo>> = <_>::default();
722
723         assert_eq!(CALLED.load(SeqCst), 0);
724
725         assert_eq!(lazy.lock().unwrap().0, 42);
726         assert_eq!(CALLED.load(SeqCst), 1);
727
728         lazy.lock().unwrap().0 = 21;
729
730         assert_eq!(lazy.lock().unwrap().0, 21);
731         assert_eq!(CALLED.load(SeqCst), 1);
732     }
733
734     #[test]
735     #[cfg_attr(miri, ignore)] // leaks memory
736     fn static_sync_lazy() {
737         static XS: SyncLazy<Vec<i32>> = SyncLazy::new(|| {
738             let mut xs = Vec::new();
739             xs.push(1);
740             xs.push(2);
741             xs.push(3);
742             xs
743         });
744
745         spawn_and_wait(|| {
746             assert_eq!(&*XS, &vec![1, 2, 3]);
747         });
748
749         assert_eq!(&*XS, &vec![1, 2, 3]);
750     }
751
752     #[test]
753     #[cfg_attr(miri, ignore)] // leaks memory
754     fn static_sync_lazy_via_fn() {
755         fn xs() -> &'static Vec<i32> {
756             static XS: SyncOnceCell<Vec<i32>> = SyncOnceCell::new();
757             XS.get_or_init(|| {
758                 let mut xs = Vec::new();
759                 xs.push(1);
760                 xs.push(2);
761                 xs.push(3);
762                 xs
763             })
764         }
765         assert_eq!(xs(), &vec![1, 2, 3]);
766     }
767
768     #[test]
769     fn sync_lazy_poisoning() {
770         let x: SyncLazy<String> = SyncLazy::new(|| panic!("kaboom"));
771         for _ in 0..2 {
772             let res = panic::catch_unwind(|| x.len());
773             assert!(res.is_err());
774         }
775     }
776
777     #[test]
778     fn is_sync_send() {
779         fn assert_traits<T: Send + Sync>() {}
780         assert_traits::<SyncOnceCell<String>>();
781         assert_traits::<SyncLazy<String>>();
782     }
783
784     #[test]
785     fn eval_once_macro() {
786         macro_rules! eval_once {
787             (|| -> $ty:ty {
788                 $($body:tt)*
789             }) => {{
790                 static ONCE_CELL: SyncOnceCell<$ty> = SyncOnceCell::new();
791                 fn init() -> $ty {
792                     $($body)*
793                 }
794                 ONCE_CELL.get_or_init(init)
795             }};
796         }
797
798         let fib: &'static Vec<i32> = eval_once! {
799             || -> Vec<i32> {
800                 let mut res = vec![1, 1];
801                 for i in 0..10 {
802                     let next = res[i] + res[i + 1];
803                     res.push(next);
804                 }
805                 res
806             }
807         };
808         assert_eq!(fib[5], 8)
809     }
810
811     #[test]
812     #[cfg_attr(miri, ignore)] // deadlocks without real threads
813     fn sync_once_cell_does_not_leak_partially_constructed_boxes() {
814         static ONCE_CELL: SyncOnceCell<String> = SyncOnceCell::new();
815
816         let n_readers = 10;
817         let n_writers = 3;
818         const MSG: &str = "Hello, World";
819
820         let (tx, rx) = channel();
821
822         for _ in 0..n_readers {
823             let tx = tx.clone();
824             spawn(move || {
825                 loop {
826                     if let Some(msg) = ONCE_CELL.get() {
827                         tx.send(msg).unwrap();
828                         break;
829                     }
830                     #[cfg(target_env = "sgx")]
831                     crate::thread::yield_now();
832                 }
833             });
834         }
835         for _ in 0..n_writers {
836             spawn(move || {
837                 let _ = ONCE_CELL.set(MSG.to_owned());
838             });
839         }
840
841         for _ in 0..n_readers {
842             let msg = rx.recv().unwrap();
843             assert_eq!(msg, MSG);
844         }
845     }
846 }