1 use crate::cell::UnsafeCell;
3 use crate::marker::PhantomData;
4 use crate::mem::MaybeUninit;
5 use crate::panic::{RefUnwindSafe, UnwindSafe};
8 /// A synchronization primitive which can be written to only once.
10 /// This type is a thread-safe [`OnceCell`], and can be used in statics.
12 /// [`OnceCell`]: crate::cell::OnceCell
17 /// #![feature(once_cell)]
19 /// use std::sync::OnceLock;
21 /// static CELL: OnceLock<String> = OnceLock::new();
22 /// assert!(CELL.get().is_none());
24 /// std::thread::spawn(|| {
25 /// let value: &String = CELL.get_or_init(|| {
26 /// "Hello, World!".to_string()
28 /// assert_eq!(value, "Hello, World!");
29 /// }).join().unwrap();
31 /// let value: Option<&String> = CELL.get();
32 /// assert!(value.is_some());
33 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
35 #[unstable(feature = "once_cell", issue = "74465")]
36 pub struct OnceLock<T> {
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.
42 /// ```compile_fail,E0597
43 /// #![feature(once_cell)]
45 /// use std::sync::OnceLock;
47 /// struct A<'a>(&'a str);
49 /// impl<'a> Drop for A<'a> {
50 /// fn drop(&mut self) {}
53 /// let cell = OnceLock::new();
55 /// let s = String::new();
56 /// let _ = cell.set(A(&s));
59 _marker: PhantomData<T>,
63 /// Creates a new empty cell.
64 #[unstable(feature = "once_cell", issue = "74465")]
66 pub const fn new() -> OnceLock<T> {
69 value: UnsafeCell::new(MaybeUninit::uninit()),
74 /// Gets the reference to the underlying value.
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() })
88 /// Gets the mutable reference to the underlying value.
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() })
101 /// Sets the contents of this cell to `value`.
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.
106 /// Returns `Ok(())` if the cell's value was set by this call.
111 /// #![feature(once_cell)]
113 /// use std::sync::OnceLock;
115 /// static CELL: OnceLock<i32> = OnceLock::new();
118 /// assert!(CELL.get().is_none());
120 /// std::thread::spawn(|| {
121 /// assert_eq!(CELL.set(92), Ok(()));
122 /// }).join().unwrap();
124 /// assert_eq!(CELL.set(62), Err(62));
125 /// assert_eq!(CELL.get(), Some(&92));
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());
134 Some(value) => Err(value),
138 /// Gets the contents of the cell, initializing it with `f` if the cell
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.
147 /// If `f` panics, the panic is propagated to the caller, and the cell
148 /// remains uninitialized.
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.
157 /// #![feature(once_cell)]
159 /// use std::sync::OnceLock;
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);
167 #[unstable(feature = "once_cell", issue = "74465")]
168 pub fn get_or_init<F>(&self, f: F) -> &T
172 match self.get_or_try_init(|| Ok::<T, !>(f())) {
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.
183 /// If `f` panics, the panic is propagated to the caller, and
184 /// the cell remains uninitialized.
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.
193 /// #![feature(once_cell)]
195 /// use std::sync::OnceLock;
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, ()> {
203 /// assert_eq!(value, Ok(&92));
204 /// assert_eq!(cell.get(), Some(&92))
206 #[unstable(feature = "once_cell", issue = "74465")]
207 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
209 F: FnOnce() -> Result<T, E>,
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() {
221 debug_assert!(self.is_initialized());
223 // SAFETY: The inner value has been initialized
224 Ok(unsafe { self.get_unchecked() })
227 /// Consumes the `OnceLock`, returning the wrapped value. Returns
228 /// `None` if the cell was empty.
233 /// #![feature(once_cell)]
235 /// use std::sync::OnceLock;
237 /// let cell: OnceLock<String> = OnceLock::new();
238 /// assert_eq!(cell.into_inner(), None);
240 /// let cell = OnceLock::new();
241 /// cell.set("hello".to_string()).unwrap();
242 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
244 #[unstable(feature = "once_cell", issue = "74465")]
245 pub fn into_inner(mut self) -> Option<T> {
249 /// Takes the value out of this `OnceLock`, moving it back to an uninitialized state.
251 /// Has no effect and returns `None` if the `OnceLock` hasn't been initialized.
253 /// Safety is guaranteed by requiring a mutable reference.
258 /// #![feature(once_cell)]
260 /// use std::sync::OnceLock;
262 /// let mut cell: OnceLock<String> = OnceLock::new();
263 /// assert_eq!(cell.take(), None);
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);
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()) }
284 fn is_initialized(&self) -> bool {
285 self.once.is_completed()
289 fn initialize<F, E>(&self, f: F) -> Result<(), E>
291 F: FnOnce() -> Result<T, E>,
293 let mut res: Result<(), E> = Ok(());
294 let slot = &self.value;
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| {
301 unsafe { (&mut *slot.get()).write(value) };
306 // Treat the underlying `Once` as poisoned since we
307 // failed to initialize our value. Calls
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()
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()
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
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> {}
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> {}
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.
355 /// #![feature(once_cell)]
357 /// use std::sync::OnceLock;
360 /// assert_eq!(OnceLock::<()>::new(), OnceLock::default());
363 fn default() -> OnceLock<T> {
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 {
372 Some(v) => f.debug_tuple("Once").field(v).finish(),
373 None => f.write_str("Once(Uninit)"),
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()) {
385 Err(_) => unreachable!(),
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`.
399 /// #![feature(once_cell)]
401 /// use std::sync::OnceLock;
403 /// # fn main() -> Result<(), i32> {
404 /// let a = OnceLock::from(3);
405 /// let b = OnceLock::new();
407 /// assert_eq!(a, b);
411 fn from(value: T) -> Self {
412 let cell = Self::new();
413 match cell.set(value) {
415 Err(_) => unreachable!(),
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()
427 #[unstable(feature = "once_cell", issue = "74465")]
428 impl<T: Eq> Eq for OnceLock<T> {}
430 #[unstable(feature = "once_cell", issue = "74465")]
431 unsafe impl<#[may_dangle] T> Drop for OnceLock<T> {
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() };