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