]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/lazy_lock.rs
Rollup merge of #101486 - asquared31415:invalid_repr_list, r=estebank
[rust.git] / library / std / src / sync / lazy_lock.rs
1 use crate::cell::Cell;
2 use crate::fmt;
3 use crate::ops::Deref;
4 use crate::panic::{RefUnwindSafe, UnwindSafe};
5 use crate::sync::OnceLock;
6
7 /// A value which is initialized on the first access.
8 ///
9 /// This type is a thread-safe `Lazy`, and can be used in statics.
10 ///
11 /// # Examples
12 ///
13 /// ```
14 /// #![feature(once_cell)]
15 ///
16 /// use std::collections::HashMap;
17 ///
18 /// use std::sync::LazyLock;
19 ///
20 /// static HASHMAP: LazyLock<HashMap<i32, String>> = LazyLock::new(|| {
21 ///     println!("initializing");
22 ///     let mut m = HashMap::new();
23 ///     m.insert(13, "Spica".to_string());
24 ///     m.insert(74, "Hoyten".to_string());
25 ///     m
26 /// });
27 ///
28 /// fn main() {
29 ///     println!("ready");
30 ///     std::thread::spawn(|| {
31 ///         println!("{:?}", HASHMAP.get(&13));
32 ///     }).join().unwrap();
33 ///     println!("{:?}", HASHMAP.get(&74));
34 ///
35 ///     // Prints:
36 ///     //   ready
37 ///     //   initializing
38 ///     //   Some("Spica")
39 ///     //   Some("Hoyten")
40 /// }
41 /// ```
42 #[unstable(feature = "once_cell", issue = "74465")]
43 pub struct LazyLock<T, F = fn() -> T> {
44     cell: OnceLock<T>,
45     init: Cell<Option<F>>,
46 }
47
48 impl<T, F> LazyLock<T, F> {
49     /// Creates a new lazy value with the given initializing
50     /// function.
51     #[unstable(feature = "once_cell", issue = "74465")]
52     pub const fn new(f: F) -> LazyLock<T, F> {
53         LazyLock { cell: OnceLock::new(), init: Cell::new(Some(f)) }
54     }
55 }
56
57 impl<T, F: FnOnce() -> T> LazyLock<T, F> {
58     /// Forces the evaluation of this lazy value and
59     /// returns a reference to result. This is equivalent
60     /// to the `Deref` impl, but is explicit.
61     ///
62     /// # Examples
63     ///
64     /// ```
65     /// #![feature(once_cell)]
66     ///
67     /// use std::sync::LazyLock;
68     ///
69     /// let lazy = LazyLock::new(|| 92);
70     ///
71     /// assert_eq!(LazyLock::force(&lazy), &92);
72     /// assert_eq!(&*lazy, &92);
73     /// ```
74     #[unstable(feature = "once_cell", issue = "74465")]
75     pub fn force(this: &LazyLock<T, F>) -> &T {
76         this.cell.get_or_init(|| match this.init.take() {
77             Some(f) => f(),
78             None => panic!("Lazy instance has previously been poisoned"),
79         })
80     }
81 }
82
83 #[unstable(feature = "once_cell", issue = "74465")]
84 impl<T, F: FnOnce() -> T> Deref for LazyLock<T, F> {
85     type Target = T;
86     fn deref(&self) -> &T {
87         LazyLock::force(self)
88     }
89 }
90
91 #[unstable(feature = "once_cell", issue = "74465")]
92 impl<T: Default> Default for LazyLock<T> {
93     /// Creates a new lazy value using `Default` as the initializing function.
94     fn default() -> LazyLock<T> {
95         LazyLock::new(T::default)
96     }
97 }
98
99 #[unstable(feature = "once_cell", issue = "74465")]
100 impl<T: fmt::Debug, F> fmt::Debug for LazyLock<T, F> {
101     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102         f.debug_struct("Lazy").field("cell", &self.cell).finish_non_exhaustive()
103     }
104 }
105
106 // We never create a `&F` from a `&LazyLock<T, F>` so it is fine
107 // to not impl `Sync` for `F`
108 // we do create a `&mut Option<F>` in `force`, but this is
109 // properly synchronized, so it only happens once
110 // so it also does not contribute to this impl.
111 #[unstable(feature = "once_cell", issue = "74465")]
112 unsafe impl<T, F: Send> Sync for LazyLock<T, F> where OnceLock<T>: Sync {}
113 // auto-derived `Send` impl is OK.
114
115 #[unstable(feature = "once_cell", issue = "74465")]
116 impl<T, F: UnwindSafe> RefUnwindSafe for LazyLock<T, F> where OnceLock<T>: RefUnwindSafe {}
117 #[unstable(feature = "once_cell", issue = "74465")]
118 impl<T, F: UnwindSafe> UnwindSafe for LazyLock<T, F> where OnceLock<T>: UnwindSafe {}
119
120 #[cfg(test)]
121 mod tests;