]> git.lizzy.rs Git - rust.git/blob - library/core/src/cell/lazy.rs
Revert "Implement allow-by-default multiple_supertrait_upcastable lint"
[rust.git] / library / core / src / cell / lazy.rs
1 use crate::cell::{Cell, OnceCell};
2 use crate::fmt;
3 use crate::ops::Deref;
4
5 /// A value which is initialized on the first access.
6 ///
7 /// For a thread-safe version of this struct, see [`std::sync::LazyLock`].
8 ///
9 /// [`std::sync::LazyLock`]: ../../std/sync/struct.LazyLock.html
10 ///
11 /// # Examples
12 ///
13 /// ```
14 /// #![feature(once_cell)]
15 ///
16 /// use std::cell::LazyCell;
17 ///
18 /// let lazy: LazyCell<i32> = LazyCell::new(|| {
19 ///     println!("initializing");
20 ///     92
21 /// });
22 /// println!("ready");
23 /// println!("{}", *lazy);
24 /// println!("{}", *lazy);
25 ///
26 /// // Prints:
27 /// //   ready
28 /// //   initializing
29 /// //   92
30 /// //   92
31 /// ```
32 #[unstable(feature = "once_cell", issue = "74465")]
33 pub struct LazyCell<T, F = fn() -> T> {
34     cell: OnceCell<T>,
35     init: Cell<Option<F>>,
36 }
37
38 impl<T, F: FnOnce() -> T> LazyCell<T, F> {
39     /// Creates a new lazy value with the given initializing function.
40     ///
41     /// # Examples
42     ///
43     /// ```
44     /// #![feature(once_cell)]
45     ///
46     /// use std::cell::LazyCell;
47     ///
48     /// let hello = "Hello, World!".to_string();
49     ///
50     /// let lazy = LazyCell::new(|| hello.to_uppercase());
51     ///
52     /// assert_eq!(&*lazy, "HELLO, WORLD!");
53     /// ```
54     #[unstable(feature = "once_cell", issue = "74465")]
55     pub const fn new(init: F) -> LazyCell<T, F> {
56         LazyCell { cell: OnceCell::new(), init: Cell::new(Some(init)) }
57     }
58
59     /// Forces the evaluation of this lazy value and returns a reference to
60     /// the result.
61     ///
62     /// This is equivalent to the `Deref` impl, but is explicit.
63     ///
64     /// # Examples
65     ///
66     /// ```
67     /// #![feature(once_cell)]
68     ///
69     /// use std::cell::LazyCell;
70     ///
71     /// let lazy = LazyCell::new(|| 92);
72     ///
73     /// assert_eq!(LazyCell::force(&lazy), &92);
74     /// assert_eq!(&*lazy, &92);
75     /// ```
76     #[unstable(feature = "once_cell", issue = "74465")]
77     pub fn force(this: &LazyCell<T, F>) -> &T {
78         this.cell.get_or_init(|| match this.init.take() {
79             Some(f) => f(),
80             None => panic!("`Lazy` instance has previously been poisoned"),
81         })
82     }
83 }
84
85 #[unstable(feature = "once_cell", issue = "74465")]
86 impl<T, F: FnOnce() -> T> Deref for LazyCell<T, F> {
87     type Target = T;
88     fn deref(&self) -> &T {
89         LazyCell::force(self)
90     }
91 }
92
93 #[unstable(feature = "once_cell", issue = "74465")]
94 impl<T: Default> Default for LazyCell<T> {
95     /// Creates a new lazy value using `Default` as the initializing function.
96     fn default() -> LazyCell<T> {
97         LazyCell::new(T::default)
98     }
99 }
100
101 #[unstable(feature = "once_cell", issue = "74465")]
102 impl<T: fmt::Debug, F> fmt::Debug for LazyCell<T, F> {
103     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104         f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
105     }
106 }