]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/once_lock.rs
Rollup merge of #104512 - jyn514:download-ci-llvm-default, r=Mark-Simulacrum
[rust.git] / library / std / src / sync / once_lock.rs
1 use crate::cell::UnsafeCell;
2 use crate::fmt;
3 use crate::marker::PhantomData;
4 use crate::mem::MaybeUninit;
5 use crate::panic::{RefUnwindSafe, UnwindSafe};
6 use crate::sync::Once;
7
8 /// A synchronization primitive which can be written to only once.
9 ///
10 /// This type is a thread-safe [`OnceCell`], and can be used in statics.
11 ///
12 /// [`OnceCell`]: crate::cell::OnceCell
13 ///
14 /// # Examples
15 ///
16 /// ```
17 /// #![feature(once_cell)]
18 ///
19 /// use std::sync::OnceLock;
20 ///
21 /// static CELL: OnceLock<String> = OnceLock::new();
22 /// assert!(CELL.get().is_none());
23 ///
24 /// std::thread::spawn(|| {
25 ///     let value: &String = CELL.get_or_init(|| {
26 ///         "Hello, World!".to_string()
27 ///     });
28 ///     assert_eq!(value, "Hello, World!");
29 /// }).join().unwrap();
30 ///
31 /// let value: Option<&String> = CELL.get();
32 /// assert!(value.is_some());
33 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
34 /// ```
35 #[unstable(feature = "once_cell", issue = "74465")]
36 pub struct OnceLock<T> {
37     once: Once,
38     // Whether or not the value is initialized is tracked by `once.is_completed()`.
39     value: UnsafeCell<MaybeUninit<T>>,
40     /// `PhantomData` to make sure dropck understands we're dropping T in our Drop impl.
41     ///
42     /// ```compile_fail,E0597
43     /// #![feature(once_cell)]
44     ///
45     /// use std::sync::OnceLock;
46     ///
47     /// struct A<'a>(&'a str);
48     ///
49     /// impl<'a> Drop for A<'a> {
50     ///     fn drop(&mut self) {}
51     /// }
52     ///
53     /// let cell = OnceLock::new();
54     /// {
55     ///     let s = String::new();
56     ///     let _ = cell.set(A(&s));
57     /// }
58     /// ```
59     _marker: PhantomData<T>,
60 }
61
62 impl<T> OnceLock<T> {
63     /// Creates a new empty cell.
64     #[unstable(feature = "once_cell", issue = "74465")]
65     #[must_use]
66     pub const fn new() -> OnceLock<T> {
67         OnceLock {
68             once: Once::new(),
69             value: UnsafeCell::new(MaybeUninit::uninit()),
70             _marker: PhantomData,
71         }
72     }
73
74     /// Gets the reference to the underlying value.
75     ///
76     /// Returns `None` if the cell is empty, or being initialized. This
77     /// method never blocks.
78     #[unstable(feature = "once_cell", issue = "74465")]
79     pub fn get(&self) -> Option<&T> {
80         if self.is_initialized() {
81             // Safe b/c checked is_initialized
82             Some(unsafe { self.get_unchecked() })
83         } else {
84             None
85         }
86     }
87
88     /// Gets the mutable reference to the underlying value.
89     ///
90     /// Returns `None` if the cell is empty. This method never blocks.
91     #[unstable(feature = "once_cell", issue = "74465")]
92     pub fn get_mut(&mut self) -> Option<&mut T> {
93         if self.is_initialized() {
94             // Safe b/c checked is_initialized and we have a unique access
95             Some(unsafe { self.get_unchecked_mut() })
96         } else {
97             None
98         }
99     }
100
101     /// Sets the contents of this cell to `value`.
102     ///
103     /// May block if another thread is currently attempting to initialize the cell. The cell is
104     /// guaranteed to contain a value when set returns, though not necessarily the one provided.
105     ///
106     /// Returns `Ok(())` if the cell's value was set by this call.
107     ///
108     /// # Examples
109     ///
110     /// ```
111     /// #![feature(once_cell)]
112     ///
113     /// use std::sync::OnceLock;
114     ///
115     /// static CELL: OnceLock<i32> = OnceLock::new();
116     ///
117     /// fn main() {
118     ///     assert!(CELL.get().is_none());
119     ///
120     ///     std::thread::spawn(|| {
121     ///         assert_eq!(CELL.set(92), Ok(()));
122     ///     }).join().unwrap();
123     ///
124     ///     assert_eq!(CELL.set(62), Err(62));
125     ///     assert_eq!(CELL.get(), Some(&92));
126     /// }
127     /// ```
128     #[unstable(feature = "once_cell", issue = "74465")]
129     pub fn set(&self, value: T) -> Result<(), T> {
130         let mut value = Some(value);
131         self.get_or_init(|| value.take().unwrap());
132         match value {
133             None => Ok(()),
134             Some(value) => Err(value),
135         }
136     }
137
138     /// Gets the contents of the cell, initializing it with `f` if the cell
139     /// was empty.
140     ///
141     /// Many threads may call `get_or_init` concurrently with different
142     /// initializing functions, but it is guaranteed that only one function
143     /// will be executed.
144     ///
145     /// # Panics
146     ///
147     /// If `f` panics, the panic is propagated to the caller, and the cell
148     /// remains uninitialized.
149     ///
150     /// It is an error to reentrantly initialize the cell from `f`. The
151     /// exact outcome is unspecified. Current implementation deadlocks, but
152     /// this may be changed to a panic in the future.
153     ///
154     /// # Examples
155     ///
156     /// ```
157     /// #![feature(once_cell)]
158     ///
159     /// use std::sync::OnceLock;
160     ///
161     /// let cell = OnceLock::new();
162     /// let value = cell.get_or_init(|| 92);
163     /// assert_eq!(value, &92);
164     /// let value = cell.get_or_init(|| unreachable!());
165     /// assert_eq!(value, &92);
166     /// ```
167     #[unstable(feature = "once_cell", issue = "74465")]
168     pub fn get_or_init<F>(&self, f: F) -> &T
169     where
170         F: FnOnce() -> T,
171     {
172         match self.get_or_try_init(|| Ok::<T, !>(f())) {
173             Ok(val) => val,
174         }
175     }
176
177     /// Gets the contents of the cell, initializing it with `f` if
178     /// the cell was empty. If the cell was empty and `f` failed, an
179     /// error is returned.
180     ///
181     /// # Panics
182     ///
183     /// If `f` panics, the panic is propagated to the caller, and
184     /// the cell remains uninitialized.
185     ///
186     /// It is an error to reentrantly initialize the cell from `f`.
187     /// The exact outcome is unspecified. Current implementation
188     /// deadlocks, but this may be changed to a panic in the future.
189     ///
190     /// # Examples
191     ///
192     /// ```
193     /// #![feature(once_cell)]
194     ///
195     /// use std::sync::OnceLock;
196     ///
197     /// let cell = OnceLock::new();
198     /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
199     /// assert!(cell.get().is_none());
200     /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
201     ///     Ok(92)
202     /// });
203     /// assert_eq!(value, Ok(&92));
204     /// assert_eq!(cell.get(), Some(&92))
205     /// ```
206     #[unstable(feature = "once_cell", issue = "74465")]
207     pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
208     where
209         F: FnOnce() -> Result<T, E>,
210     {
211         // Fast path check
212         // NOTE: We need to perform an acquire on the state in this method
213         // in order to correctly synchronize `LazyLock::force`. This is
214         // currently done by calling `self.get()`, which in turn calls
215         // `self.is_initialized()`, which in turn performs the acquire.
216         if let Some(value) = self.get() {
217             return Ok(value);
218         }
219         self.initialize(f)?;
220
221         debug_assert!(self.is_initialized());
222
223         // SAFETY: The inner value has been initialized
224         Ok(unsafe { self.get_unchecked() })
225     }
226
227     /// Consumes the `OnceLock`, returning the wrapped value. Returns
228     /// `None` if the cell was empty.
229     ///
230     /// # Examples
231     ///
232     /// ```
233     /// #![feature(once_cell)]
234     ///
235     /// use std::sync::OnceLock;
236     ///
237     /// let cell: OnceLock<String> = OnceLock::new();
238     /// assert_eq!(cell.into_inner(), None);
239     ///
240     /// let cell = OnceLock::new();
241     /// cell.set("hello".to_string()).unwrap();
242     /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
243     /// ```
244     #[unstable(feature = "once_cell", issue = "74465")]
245     pub fn into_inner(mut self) -> Option<T> {
246         self.take()
247     }
248
249     /// Takes the value out of this `OnceLock`, moving it back to an uninitialized state.
250     ///
251     /// Has no effect and returns `None` if the `OnceLock` hasn't been initialized.
252     ///
253     /// Safety is guaranteed by requiring a mutable reference.
254     ///
255     /// # Examples
256     ///
257     /// ```
258     /// #![feature(once_cell)]
259     ///
260     /// use std::sync::OnceLock;
261     ///
262     /// let mut cell: OnceLock<String> = OnceLock::new();
263     /// assert_eq!(cell.take(), None);
264     ///
265     /// let mut cell = OnceLock::new();
266     /// cell.set("hello".to_string()).unwrap();
267     /// assert_eq!(cell.take(), Some("hello".to_string()));
268     /// assert_eq!(cell.get(), None);
269     /// ```
270     #[unstable(feature = "once_cell", issue = "74465")]
271     pub fn take(&mut self) -> Option<T> {
272         if self.is_initialized() {
273             self.once = Once::new();
274             // SAFETY: `self.value` is initialized and contains a valid `T`.
275             // `self.once` is reset, so `is_initialized()` will be false again
276             // which prevents the value from being read twice.
277             unsafe { Some((&mut *self.value.get()).assume_init_read()) }
278         } else {
279             None
280         }
281     }
282
283     #[inline]
284     fn is_initialized(&self) -> bool {
285         self.once.is_completed()
286     }
287
288     #[cold]
289     fn initialize<F, E>(&self, f: F) -> Result<(), E>
290     where
291         F: FnOnce() -> Result<T, E>,
292     {
293         let mut res: Result<(), E> = Ok(());
294         let slot = &self.value;
295
296         // Ignore poisoning from other threads
297         // If another thread panics, then we'll be able to run our closure
298         self.once.call_once_force(|p| {
299             match f() {
300                 Ok(value) => {
301                     unsafe { (&mut *slot.get()).write(value) };
302                 }
303                 Err(e) => {
304                     res = Err(e);
305
306                     // Treat the underlying `Once` as poisoned since we
307                     // failed to initialize our value. Calls
308                     p.poison();
309                 }
310             }
311         });
312         res
313     }
314
315     /// # Safety
316     ///
317     /// The value must be initialized
318     unsafe fn get_unchecked(&self) -> &T {
319         debug_assert!(self.is_initialized());
320         (&*self.value.get()).assume_init_ref()
321     }
322
323     /// # Safety
324     ///
325     /// The value must be initialized
326     unsafe fn get_unchecked_mut(&mut self) -> &mut T {
327         debug_assert!(self.is_initialized());
328         (&mut *self.value.get()).assume_init_mut()
329     }
330 }
331
332 // Why do we need `T: Send`?
333 // Thread A creates a `OnceLock` and shares it with
334 // scoped thread B, which fills the cell, which is
335 // then destroyed by A. That is, destructor observes
336 // a sent value.
337 #[unstable(feature = "once_cell", issue = "74465")]
338 unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
339 #[unstable(feature = "once_cell", issue = "74465")]
340 unsafe impl<T: Send> Send for OnceLock<T> {}
341
342 #[unstable(feature = "once_cell", issue = "74465")]
343 impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T> {}
344 #[unstable(feature = "once_cell", issue = "74465")]
345 impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {}
346
347 #[unstable(feature = "once_cell", issue = "74465")]
348 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
349 impl<T> const Default for OnceLock<T> {
350     /// Creates a new empty cell.
351     ///
352     /// # Example
353     ///
354     /// ```
355     /// #![feature(once_cell)]
356     ///
357     /// use std::sync::OnceLock;
358     ///
359     /// fn main() {
360     ///     assert_eq!(OnceLock::<()>::new(), OnceLock::default());
361     /// }
362     /// ```
363     fn default() -> OnceLock<T> {
364         OnceLock::new()
365     }
366 }
367
368 #[unstable(feature = "once_cell", issue = "74465")]
369 impl<T: fmt::Debug> fmt::Debug for OnceLock<T> {
370     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371         match self.get() {
372             Some(v) => f.debug_tuple("Once").field(v).finish(),
373             None => f.write_str("Once(Uninit)"),
374         }
375     }
376 }
377
378 #[unstable(feature = "once_cell", issue = "74465")]
379 impl<T: Clone> Clone for OnceLock<T> {
380     fn clone(&self) -> OnceLock<T> {
381         let cell = Self::new();
382         if let Some(value) = self.get() {
383             match cell.set(value.clone()) {
384                 Ok(()) => (),
385                 Err(_) => unreachable!(),
386             }
387         }
388         cell
389     }
390 }
391
392 #[unstable(feature = "once_cell", issue = "74465")]
393 impl<T> From<T> for OnceLock<T> {
394     /// Create a new cell with its contents set to `value`.
395     ///
396     /// # Example
397     ///
398     /// ```
399     /// #![feature(once_cell)]
400     ///
401     /// use std::sync::OnceLock;
402     ///
403     /// # fn main() -> Result<(), i32> {
404     /// let a = OnceLock::from(3);
405     /// let b = OnceLock::new();
406     /// b.set(3)?;
407     /// assert_eq!(a, b);
408     /// Ok(())
409     /// # }
410     /// ```
411     fn from(value: T) -> Self {
412         let cell = Self::new();
413         match cell.set(value) {
414             Ok(()) => cell,
415             Err(_) => unreachable!(),
416         }
417     }
418 }
419
420 #[unstable(feature = "once_cell", issue = "74465")]
421 impl<T: PartialEq> PartialEq for OnceLock<T> {
422     fn eq(&self, other: &OnceLock<T>) -> bool {
423         self.get() == other.get()
424     }
425 }
426
427 #[unstable(feature = "once_cell", issue = "74465")]
428 impl<T: Eq> Eq for OnceLock<T> {}
429
430 #[unstable(feature = "once_cell", issue = "74465")]
431 unsafe impl<#[may_dangle] T> Drop for OnceLock<T> {
432     fn drop(&mut self) {
433         if self.is_initialized() {
434             // SAFETY: The cell is initialized and being dropped, so it can't
435             // be accessed again. We also don't touch the `T` other than
436             // dropping it, which validates our usage of #[may_dangle].
437             unsafe { (&mut *self.value.get()).assume_init_drop() };
438         }
439     }
440 }
441
442 #[cfg(test)]
443 mod tests;