]> git.lizzy.rs Git - rust.git/blob - library/std/src/lazy.rs
Fix font color for help button in ayu and dark themes
[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 unsafe impl<#[may_dangle] 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         // We also don't touch the `T`, which validates our usage of #[may_dangle].
393         unsafe { self.take_inner() };
394     }
395 }
396
397 /// A value which is initialized on the first access.
398 ///
399 /// This type is a thread-safe `Lazy`, and can be used in statics.
400 ///
401 /// # Examples
402 ///
403 /// ```
404 /// #![feature(once_cell)]
405 ///
406 /// use std::collections::HashMap;
407 ///
408 /// use std::lazy::SyncLazy;
409 ///
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());
415 ///     m
416 /// });
417 ///
418 /// fn main() {
419 ///     println!("ready");
420 ///     std::thread::spawn(|| {
421 ///         println!("{:?}", HASHMAP.get(&13));
422 ///     }).join().unwrap();
423 ///     println!("{:?}", HASHMAP.get(&74));
424 ///
425 ///     // Prints:
426 ///     //   ready
427 ///     //   initializing
428 ///     //   Some("Spica")
429 ///     //   Some("Hoyten")
430 /// }
431 /// ```
432 #[unstable(feature = "once_cell", issue = "74465")]
433 pub struct SyncLazy<T, F = fn() -> T> {
434     cell: SyncOnceCell<T>,
435     init: Cell<Option<F>>,
436 }
437
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()
442     }
443 }
444
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.
453
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 {}
458
459 impl<T, F> SyncLazy<T, F> {
460     /// Creates a new lazy value with the given initializing
461     /// function.
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)) }
465     }
466 }
467
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.
472     ///
473     /// # Examples
474     ///
475     /// ```
476     /// #![feature(once_cell)]
477     ///
478     /// use std::lazy::SyncLazy;
479     ///
480     /// let lazy = SyncLazy::new(|| 92);
481     ///
482     /// assert_eq!(SyncLazy::force(&lazy), &92);
483     /// assert_eq!(&*lazy, &92);
484     /// ```
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() {
488             Some(f) => f(),
489             None => panic!("Lazy instance has previously been poisoned"),
490         })
491     }
492 }
493
494 #[unstable(feature = "once_cell", issue = "74465")]
495 impl<T, F: FnOnce() -> T> Deref for SyncLazy<T, F> {
496     type Target = T;
497     fn deref(&self) -> &T {
498         SyncLazy::force(self)
499     }
500 }
501
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)
507     }
508 }
509
510 #[cfg(test)]
511 mod tests {
512     use crate::{
513         lazy::{Lazy, SyncLazy, SyncOnceCell},
514         panic,
515         sync::{
516             atomic::{AtomicUsize, Ordering::SeqCst},
517             mpsc::channel,
518             Mutex,
519         },
520         thread,
521     };
522
523     #[test]
524     fn lazy_default() {
525         static CALLED: AtomicUsize = AtomicUsize::new(0);
526
527         struct Foo(u8);
528         impl Default for Foo {
529             fn default() -> Self {
530                 CALLED.fetch_add(1, SeqCst);
531                 Foo(42)
532             }
533         }
534
535         let lazy: Lazy<Mutex<Foo>> = <_>::default();
536
537         assert_eq!(CALLED.load(SeqCst), 0);
538
539         assert_eq!(lazy.lock().unwrap().0, 42);
540         assert_eq!(CALLED.load(SeqCst), 1);
541
542         lazy.lock().unwrap().0 = 21;
543
544         assert_eq!(lazy.lock().unwrap().0, 21);
545         assert_eq!(CALLED.load(SeqCst), 1);
546     }
547
548     #[test]
549     fn lazy_poisoning() {
550         let x: Lazy<String> = Lazy::new(|| panic!("kaboom"));
551         for _ in 0..2 {
552             let res = panic::catch_unwind(panic::AssertUnwindSafe(|| x.len()));
553             assert!(res.is_err());
554         }
555     }
556
557     fn spawn_and_wait<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> R {
558         thread::spawn(f).join().unwrap()
559     }
560
561     #[test]
562     fn sync_once_cell() {
563         static ONCE_CELL: SyncOnceCell<i32> = SyncOnceCell::new();
564
565         assert!(ONCE_CELL.get().is_none());
566
567         spawn_and_wait(|| {
568             ONCE_CELL.get_or_init(|| 92);
569             assert_eq!(ONCE_CELL.get(), Some(&92));
570         });
571
572         ONCE_CELL.get_or_init(|| panic!("Kabom!"));
573         assert_eq!(ONCE_CELL.get(), Some(&92));
574     }
575
576     #[test]
577     fn sync_once_cell_get_mut() {
578         let mut c = SyncOnceCell::new();
579         assert!(c.get_mut().is_none());
580         c.set(90).unwrap();
581         *c.get_mut().unwrap() += 2;
582         assert_eq!(c.get_mut(), Some(&mut 92));
583     }
584
585     #[test]
586     fn sync_once_cell_get_unchecked() {
587         let c = SyncOnceCell::new();
588         c.set(92).unwrap();
589         unsafe {
590             assert_eq!(c.get_unchecked(), &92);
591         }
592     }
593
594     #[test]
595     fn sync_once_cell_drop() {
596         static DROP_CNT: AtomicUsize = AtomicUsize::new(0);
597         struct Dropper;
598         impl Drop for Dropper {
599             fn drop(&mut self) {
600                 DROP_CNT.fetch_add(1, SeqCst);
601             }
602         }
603
604         let x = SyncOnceCell::new();
605         spawn_and_wait(move || {
606             x.get_or_init(|| Dropper);
607             assert_eq!(DROP_CNT.load(SeqCst), 0);
608             drop(x);
609         });
610
611         assert_eq!(DROP_CNT.load(SeqCst), 1);
612     }
613
614     #[test]
615     fn sync_once_cell_drop_empty() {
616         let x = SyncOnceCell::<String>::new();
617         drop(x);
618     }
619
620     #[test]
621     fn clone() {
622         let s = SyncOnceCell::new();
623         let c = s.clone();
624         assert!(c.get().is_none());
625
626         s.set("hello".to_string()).unwrap();
627         let c = s.clone();
628         assert_eq!(c.get().map(String::as_str), Some("hello"));
629     }
630
631     #[test]
632     fn get_or_try_init() {
633         let cell: SyncOnceCell<String> = SyncOnceCell::new();
634         assert!(cell.get().is_none());
635
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());
640
641         assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
642
643         assert_eq!(
644             cell.get_or_try_init(|| Ok::<_, ()>("hello".to_string())),
645             Ok(&"hello".to_string())
646         );
647         assert_eq!(cell.get(), Some(&"hello".to_string()));
648     }
649
650     #[test]
651     fn from_impl() {
652         assert_eq!(SyncOnceCell::from("value").get(), Some(&"value"));
653         assert_ne!(SyncOnceCell::from("foo").get(), Some(&"bar"));
654     }
655
656     #[test]
657     fn partialeq_impl() {
658         assert!(SyncOnceCell::from("value") == SyncOnceCell::from("value"));
659         assert!(SyncOnceCell::from("foo") != SyncOnceCell::from("bar"));
660
661         assert!(SyncOnceCell::<String>::new() == SyncOnceCell::new());
662         assert!(SyncOnceCell::<String>::new() != SyncOnceCell::from("value".to_owned()));
663     }
664
665     #[test]
666     fn into_inner() {
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()));
672     }
673
674     #[test]
675     fn sync_lazy_new() {
676         static CALLED: AtomicUsize = AtomicUsize::new(0);
677         static SYNC_LAZY: SyncLazy<i32> = SyncLazy::new(|| {
678             CALLED.fetch_add(1, SeqCst);
679             92
680         });
681
682         assert_eq!(CALLED.load(SeqCst), 0);
683
684         spawn_and_wait(|| {
685             let y = *SYNC_LAZY - 30;
686             assert_eq!(y, 62);
687             assert_eq!(CALLED.load(SeqCst), 1);
688         });
689
690         let y = *SYNC_LAZY - 30;
691         assert_eq!(y, 62);
692         assert_eq!(CALLED.load(SeqCst), 1);
693     }
694
695     #[test]
696     fn sync_lazy_default() {
697         static CALLED: AtomicUsize = AtomicUsize::new(0);
698
699         struct Foo(u8);
700         impl Default for Foo {
701             fn default() -> Self {
702                 CALLED.fetch_add(1, SeqCst);
703                 Foo(42)
704             }
705         }
706
707         let lazy: SyncLazy<Mutex<Foo>> = <_>::default();
708
709         assert_eq!(CALLED.load(SeqCst), 0);
710
711         assert_eq!(lazy.lock().unwrap().0, 42);
712         assert_eq!(CALLED.load(SeqCst), 1);
713
714         lazy.lock().unwrap().0 = 21;
715
716         assert_eq!(lazy.lock().unwrap().0, 21);
717         assert_eq!(CALLED.load(SeqCst), 1);
718     }
719
720     #[test]
721     fn static_sync_lazy() {
722         static XS: SyncLazy<Vec<i32>> = SyncLazy::new(|| {
723             let mut xs = Vec::new();
724             xs.push(1);
725             xs.push(2);
726             xs.push(3);
727             xs
728         });
729
730         spawn_and_wait(|| {
731             assert_eq!(&*XS, &vec![1, 2, 3]);
732         });
733
734         assert_eq!(&*XS, &vec![1, 2, 3]);
735     }
736
737     #[test]
738     fn static_sync_lazy_via_fn() {
739         fn xs() -> &'static Vec<i32> {
740             static XS: SyncOnceCell<Vec<i32>> = SyncOnceCell::new();
741             XS.get_or_init(|| {
742                 let mut xs = Vec::new();
743                 xs.push(1);
744                 xs.push(2);
745                 xs.push(3);
746                 xs
747             })
748         }
749         assert_eq!(xs(), &vec![1, 2, 3]);
750     }
751
752     #[test]
753     fn sync_lazy_poisoning() {
754         let x: SyncLazy<String> = SyncLazy::new(|| panic!("kaboom"));
755         for _ in 0..2 {
756             let res = panic::catch_unwind(|| x.len());
757             assert!(res.is_err());
758         }
759     }
760
761     #[test]
762     fn is_sync_send() {
763         fn assert_traits<T: Send + Sync>() {}
764         assert_traits::<SyncOnceCell<String>>();
765         assert_traits::<SyncLazy<String>>();
766     }
767
768     #[test]
769     fn eval_once_macro() {
770         macro_rules! eval_once {
771             (|| -> $ty:ty {
772                 $($body:tt)*
773             }) => {{
774                 static ONCE_CELL: SyncOnceCell<$ty> = SyncOnceCell::new();
775                 fn init() -> $ty {
776                     $($body)*
777                 }
778                 ONCE_CELL.get_or_init(init)
779             }};
780         }
781
782         let fib: &'static Vec<i32> = eval_once! {
783             || -> Vec<i32> {
784                 let mut res = vec![1, 1];
785                 for i in 0..10 {
786                     let next = res[i] + res[i + 1];
787                     res.push(next);
788                 }
789                 res
790             }
791         };
792         assert_eq!(fib[5], 8)
793     }
794
795     #[test]
796     fn sync_once_cell_does_not_leak_partially_constructed_boxes() {
797         static ONCE_CELL: SyncOnceCell<String> = SyncOnceCell::new();
798
799         let n_readers = 10;
800         let n_writers = 3;
801         const MSG: &str = "Hello, World";
802
803         let (tx, rx) = channel();
804
805         for _ in 0..n_readers {
806             let tx = tx.clone();
807             thread::spawn(move || {
808                 loop {
809                     if let Some(msg) = ONCE_CELL.get() {
810                         tx.send(msg).unwrap();
811                         break;
812                     }
813                     #[cfg(target_env = "sgx")]
814                     crate::thread::yield_now();
815                 }
816             });
817         }
818         for _ in 0..n_writers {
819             thread::spawn(move || {
820                 let _ = ONCE_CELL.set(MSG.to_owned());
821             });
822         }
823
824         for _ in 0..n_readers {
825             let msg = rx.recv().unwrap();
826             assert_eq!(msg, MSG);
827         }
828     }
829
830     #[test]
831     fn dropck() {
832         let cell = SyncOnceCell::new();
833         {
834             let s = String::new();
835             cell.set(&s).unwrap();
836         }
837     }
838 }