std/sync/once_lock.rs
1use super::once::OnceExclusiveState;
2use crate::cell::UnsafeCell;
3use crate::fmt;
4use crate::marker::PhantomData;
5use crate::mem::MaybeUninit;
6use crate::panic::{RefUnwindSafe, UnwindSafe};
7use crate::sync::Once;
8
9/// A synchronization primitive which can nominally be written to only once.
10///
11/// This type is a thread-safe [`OnceCell`], and can be used in statics.
12/// In many simple cases, you can use [`LazyLock<T, F>`] instead to get the benefits of this type
13/// with less effort: `LazyLock<T, F>` "looks like" `&T` because it initializes with `F` on deref!
14/// Where OnceLock shines is when LazyLock is too simple to support a given case, as LazyLock
15/// doesn't allow additional inputs to its function after you call [`LazyLock::new(|| ...)`].
16///
17/// A `OnceLock` can be thought of as a safe abstraction over uninitialized data that becomes
18/// initialized once written.
19///
20/// Unlike [`Mutex`](crate::sync::Mutex), `OnceLock` is never poisoned on panic.
21///
22/// [`OnceCell`]: crate::cell::OnceCell
23/// [`LazyLock<T, F>`]: crate::sync::LazyLock
24/// [`LazyLock::new(|| ...)`]: crate::sync::LazyLock::new
25///
26/// # Examples
27///
28/// Writing to a `OnceLock` from a separate thread:
29///
30/// ```
31/// use std::sync::OnceLock;
32///
33/// static CELL: OnceLock<usize> = OnceLock::new();
34///
35/// // `OnceLock` has not been written to yet.
36/// assert!(CELL.get().is_none());
37///
38/// // Spawn a thread and write to `OnceLock`.
39/// std::thread::spawn(|| {
40/// let value = CELL.get_or_init(|| 12345);
41/// assert_eq!(value, &12345);
42/// })
43/// .join()
44/// .unwrap();
45///
46/// // `OnceLock` now contains the value.
47/// assert_eq!(
48/// CELL.get(),
49/// Some(&12345),
50/// );
51/// ```
52///
53/// You can use `OnceLock` to implement a type that requires "append-only" logic:
54///
55/// ```
56/// use std::sync::{OnceLock, atomic::{AtomicU32, Ordering}};
57/// use std::thread;
58///
59/// struct OnceList<T> {
60/// data: OnceLock<T>,
61/// next: OnceLock<Box<OnceList<T>>>,
62/// }
63/// impl<T> OnceList<T> {
64/// const fn new() -> OnceList<T> {
65/// OnceList { data: OnceLock::new(), next: OnceLock::new() }
66/// }
67/// fn push(&self, value: T) {
68/// // FIXME: this impl is concise, but is also slow for long lists or many threads.
69/// // as an exercise, consider how you might improve on it while preserving the behavior
70/// if let Err(value) = self.data.set(value) {
71/// let next = self.next.get_or_init(|| Box::new(OnceList::new()));
72/// next.push(value)
73/// };
74/// }
75/// fn contains(&self, example: &T) -> bool
76/// where
77/// T: PartialEq,
78/// {
79/// self.data.get().map(|item| item == example).filter(|v| *v).unwrap_or_else(|| {
80/// self.next.get().map(|next| next.contains(example)).unwrap_or(false)
81/// })
82/// }
83/// }
84///
85/// // Let's exercise this new Sync append-only list by doing a little counting
86/// static LIST: OnceList<u32> = OnceList::new();
87/// static COUNTER: AtomicU32 = AtomicU32::new(0);
88///
89/// # const LEN: u32 = if cfg!(miri) { 50 } else { 1000 };
90/// # /*
91/// const LEN: u32 = 1000;
92/// # */
93/// thread::scope(|s| {
94/// for _ in 0..thread::available_parallelism().unwrap().get() {
95/// s.spawn(|| {
96/// while let i @ 0..LEN = COUNTER.fetch_add(1, Ordering::Relaxed) {
97/// LIST.push(i);
98/// }
99/// });
100/// }
101/// });
102///
103/// for i in 0..LEN {
104/// assert!(LIST.contains(&i));
105/// }
106///
107/// ```
108#[stable(feature = "once_cell", since = "1.70.0")]
109pub struct OnceLock<#[rustc_assert_variance(invariant)] T> {
110 // FIXME(nonpoison_once): switch to nonpoison version once it is available
111 once: Once,
112 // Whether or not the value is initialized is tracked by `once.is_completed()`.
113 value: UnsafeCell<MaybeUninit<T>>,
114 /// `PhantomData` to make sure dropck understands we're dropping T in our Drop impl.
115 ///
116 /// ```compile_fail,E0597
117 /// use std::sync::OnceLock;
118 ///
119 /// struct A<'a>(&'a str);
120 ///
121 /// impl<'a> Drop for A<'a> {
122 /// fn drop(&mut self) {}
123 /// }
124 ///
125 /// let cell = OnceLock::new();
126 /// {
127 /// let s = String::new();
128 /// let _ = cell.set(A(&s));
129 /// }
130 /// ```
131 _marker: PhantomData<T>,
132}
133
134impl<T> OnceLock<T> {
135 /// Creates a new uninitialized cell.
136 #[ferrocene::prevalidated]
137 #[inline]
138 #[must_use]
139 #[stable(feature = "once_cell", since = "1.70.0")]
140 #[rustc_const_stable(feature = "once_cell", since = "1.70.0")]
141 pub const fn new() -> OnceLock<T> {
142 OnceLock {
143 once: Once::new(),
144 value: UnsafeCell::new(MaybeUninit::uninit()),
145 _marker: PhantomData,
146 }
147 }
148
149 /// Creates a new initialized cell.
150 ///
151 /// This is equivalent to `OnceLock::from(value)`, but can be used in
152 /// const contexts, unlike the `From` implementation.
153 ///
154 /// # Examples
155 ///
156 /// ```
157 /// #![feature(once_lock_new_init)]
158 /// use std::sync::OnceLock;
159 ///
160 /// static CELL: OnceLock<i32> = OnceLock::new_init(1);
161 ///
162 /// assert_eq!(CELL.get(), Some(&1));
163 ///
164 /// // Already initialized, so this closure never runs.
165 /// assert_eq!(CELL.get_or_init(|| panic!("Kaboom!")), &1);
166 /// ```
167 #[inline]
168 #[must_use]
169 #[unstable(feature = "once_lock_new_init", issue = "159860")]
170 pub const fn new_init(init_value: T) -> OnceLock<T> {
171 OnceLock {
172 once: Once::new_complete(),
173 value: UnsafeCell::new(MaybeUninit::new(init_value)),
174 _marker: PhantomData,
175 }
176 }
177
178 /// Gets the reference to the underlying value.
179 ///
180 /// Returns `None` if the cell is uninitialized, or being initialized.
181 /// This method never blocks.
182 #[inline]
183 #[stable(feature = "once_cell", since = "1.70.0")]
184 #[lint::should_not_be_called_on_const_items]
185 pub fn get(&self) -> Option<&T> {
186 if self.initialized() {
187 // Safe b/c checked initialized
188 Some(unsafe { self.get_unchecked() })
189 } else {
190 None
191 }
192 }
193
194 /// Gets the mutable reference to the underlying value.
195 ///
196 /// Returns `None` if the cell is uninitialized.
197 ///
198 /// This method never blocks. Since it borrows the `OnceLock` mutably,
199 /// it is statically guaranteed that no active borrows to the `OnceLock`
200 /// exist, including from other threads.
201 #[inline]
202 #[stable(feature = "once_cell", since = "1.70.0")]
203 pub fn get_mut(&mut self) -> Option<&mut T> {
204 if self.initialized_mut() {
205 // Safe b/c checked initialized and we have a unique access
206 Some(unsafe { self.get_unchecked_mut() })
207 } else {
208 None
209 }
210 }
211
212 /// Blocks the current thread until the cell is initialized.
213 ///
214 /// # Example
215 ///
216 /// Waiting for a computation on another thread to finish:
217 /// ```rust
218 /// use std::thread;
219 /// use std::sync::OnceLock;
220 ///
221 /// let value = OnceLock::new();
222 ///
223 /// thread::scope(|s| {
224 /// s.spawn(|| value.set(1 + 1));
225 ///
226 /// let result = value.wait();
227 /// assert_eq!(result, &2);
228 /// })
229 /// ```
230 #[inline]
231 #[stable(feature = "once_wait", since = "1.86.0")]
232 #[lint::should_not_be_called_on_const_items]
233 pub fn wait(&self) -> &T {
234 self.once.wait_force();
235
236 unsafe { self.get_unchecked() }
237 }
238
239 /// Initializes the contents of the cell to `value`.
240 ///
241 /// May block if another thread is currently attempting to initialize the cell. The cell is
242 /// guaranteed to contain a value when `set` returns, though not necessarily the one provided.
243 ///
244 /// Returns `Ok(())` if the cell was uninitialized and
245 /// `Err(value)` if the cell was already initialized.
246 ///
247 /// # Examples
248 ///
249 /// ```
250 /// use std::sync::OnceLock;
251 ///
252 /// static CELL: OnceLock<i32> = OnceLock::new();
253 ///
254 /// fn main() {
255 /// assert!(CELL.get().is_none());
256 ///
257 /// std::thread::spawn(|| {
258 /// assert_eq!(CELL.set(92), Ok(()));
259 /// }).join().unwrap();
260 ///
261 /// assert_eq!(CELL.set(62), Err(62));
262 /// assert_eq!(CELL.get(), Some(&92));
263 /// }
264 /// ```
265 #[inline]
266 #[stable(feature = "once_cell", since = "1.70.0")]
267 #[lint::should_not_be_called_on_const_items]
268 pub fn set(&self, value: T) -> Result<(), T> {
269 match self.try_insert(value) {
270 Ok(_) => Ok(()),
271 Err((_, value)) => Err(value),
272 }
273 }
274
275 /// Initializes the contents of the cell to `value` if the cell was uninitialized,
276 /// then returns a reference to it.
277 ///
278 /// May block if another thread is currently attempting to initialize the cell. The cell is
279 /// guaranteed to contain a value when `try_insert` returns, though not necessarily the
280 /// one provided.
281 ///
282 /// Returns `Ok(&value)` if the cell was uninitialized and
283 /// `Err((¤t_value, value))` if it was already initialized.
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// #![feature(once_cell_try_insert)]
289 ///
290 /// use std::sync::OnceLock;
291 ///
292 /// static CELL: OnceLock<i32> = OnceLock::new();
293 ///
294 /// fn main() {
295 /// assert!(CELL.get().is_none());
296 ///
297 /// std::thread::spawn(|| {
298 /// assert_eq!(CELL.try_insert(92), Ok(&92));
299 /// }).join().unwrap();
300 ///
301 /// assert_eq!(CELL.try_insert(62), Err((&92, 62)));
302 /// assert_eq!(CELL.get(), Some(&92));
303 /// }
304 /// ```
305 #[inline]
306 #[unstable(feature = "once_cell_try_insert", issue = "116693")]
307 #[lint::should_not_be_called_on_const_items]
308 pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
309 let mut value = Some(value);
310 let res = self.get_or_init(|| value.take().unwrap());
311 match value {
312 None => Ok(res),
313 Some(value) => Err((res, value)),
314 }
315 }
316
317 /// Gets the contents of the cell, initializing it to `f()` if the cell
318 /// was uninitialized.
319 ///
320 /// Many threads may call `get_or_init` concurrently with different
321 /// initializing functions, but it is guaranteed that only one function
322 /// will be executed if the function doesn't panic.
323 ///
324 /// # Panics
325 ///
326 /// If `f()` panics, the panic is propagated to the caller, and the cell
327 /// remains uninitialized.
328 ///
329 /// It is an error to reentrantly initialize the cell from `f`. The
330 /// exact outcome is unspecified. Current implementation deadlocks, but
331 /// this may be changed to a panic in the future.
332 ///
333 /// # Examples
334 ///
335 /// ```
336 /// use std::sync::OnceLock;
337 ///
338 /// let cell = OnceLock::new();
339 /// let value = cell.get_or_init(|| 92);
340 /// assert_eq!(value, &92);
341 /// let value = cell.get_or_init(|| unreachable!());
342 /// assert_eq!(value, &92);
343 /// ```
344 #[inline]
345 #[stable(feature = "once_cell", since = "1.70.0")]
346 #[lint::should_not_be_called_on_const_items]
347 pub fn get_or_init<F>(&self, f: F) -> &T
348 where
349 F: FnOnce() -> T,
350 {
351 match self.get_or_try_init(|| Ok::<T, !>(f())) {
352 Ok(val) => val,
353 }
354 }
355
356 /// Gets the mutable reference of the contents of the cell, initializing
357 /// it to `f()` if the cell was uninitialized.
358 ///
359 /// This method never blocks. Since it borrows the `OnceLock` mutably,
360 /// it is statically guaranteed that no active borrows to the `OnceLock`
361 /// exist, including from other threads.
362 ///
363 /// # Panics
364 ///
365 /// If `f()` panics, the panic is propagated to the caller, and the cell
366 /// remains uninitialized.
367 ///
368 /// # Examples
369 ///
370 /// ```
371 /// #![feature(once_cell_get_mut)]
372 ///
373 /// use std::sync::OnceLock;
374 ///
375 /// let mut cell = OnceLock::new();
376 /// let value = cell.get_mut_or_init(|| 92);
377 /// assert_eq!(*value, 92);
378 ///
379 /// *value += 2;
380 /// assert_eq!(*value, 94);
381 ///
382 /// let value = cell.get_mut_or_init(|| unreachable!());
383 /// assert_eq!(*value, 94);
384 /// ```
385 #[inline]
386 #[unstable(feature = "once_cell_get_mut", issue = "121641")]
387 pub fn get_mut_or_init<F>(&mut self, f: F) -> &mut T
388 where
389 F: FnOnce() -> T,
390 {
391 match self.get_mut_or_try_init(|| Ok::<T, !>(f())) {
392 Ok(val) => val,
393 }
394 }
395
396 /// Gets the contents of the cell, initializing it to `f()` if
397 /// the cell was uninitialized. If the cell was uninitialized
398 /// and `f()` failed, an error is returned.
399 ///
400 /// # Panics
401 ///
402 /// If `f()` panics, the panic is propagated to the caller, and
403 /// the cell remains uninitialized.
404 ///
405 /// It is an error to reentrantly initialize the cell from `f`.
406 /// The exact outcome is unspecified. Current implementation
407 /// deadlocks, but this may be changed to a panic in the future.
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// #![feature(once_cell_try)]
413 ///
414 /// use std::sync::OnceLock;
415 ///
416 /// let cell = OnceLock::new();
417 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
418 /// assert!(cell.get().is_none());
419 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
420 /// Ok(92)
421 /// });
422 /// assert_eq!(value, Ok(&92));
423 /// assert_eq!(cell.get(), Some(&92))
424 /// ```
425 #[inline]
426 #[unstable(feature = "once_cell_try", issue = "109737")]
427 #[lint::should_not_be_called_on_const_items]
428 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
429 where
430 F: FnOnce() -> Result<T, E>,
431 {
432 // Fast path check
433 // NOTE: We need to perform an acquire on the state in this method
434 // in order to correctly synchronize `LazyLock::force`. This is
435 // currently done by calling `self.get()`, which in turn calls
436 // `self.initialized()`, which in turn performs the acquire.
437 if let Some(value) = self.get() {
438 return Ok(value);
439 }
440 self.initialize(f)?;
441
442 // SAFETY: The inner value has been initialized
443 Ok(unsafe { self.get_unchecked() })
444 }
445
446 /// Gets the mutable reference of the contents of the cell, initializing
447 /// it to `f()` if the cell was uninitialized. If the cell was uninitialized
448 /// and `f()` failed, an error is returned.
449 ///
450 /// This method never blocks. Since it borrows the `OnceLock` mutably,
451 /// it is statically guaranteed that no active borrows to the `OnceLock`
452 /// exist, including from other threads.
453 ///
454 /// # Panics
455 ///
456 /// If `f()` panics, the panic is propagated to the caller, and
457 /// the cell remains uninitialized.
458 ///
459 /// # Examples
460 ///
461 /// ```
462 /// #![feature(once_cell_get_mut)]
463 ///
464 /// use std::sync::OnceLock;
465 ///
466 /// let mut cell: OnceLock<u32> = OnceLock::new();
467 ///
468 /// // Failed attempts to initialize the cell do not change its contents
469 /// assert!(cell.get_mut_or_try_init(|| "not a number!".parse()).is_err());
470 /// assert!(cell.get().is_none());
471 ///
472 /// let value = cell.get_mut_or_try_init(|| "1234".parse());
473 /// assert_eq!(value, Ok(&mut 1234));
474 /// *value.unwrap() += 2;
475 /// assert_eq!(cell.get(), Some(&1236))
476 /// ```
477 #[inline]
478 #[unstable(feature = "once_cell_get_mut", issue = "121641")]
479 pub fn get_mut_or_try_init<F, E>(&mut self, f: F) -> Result<&mut T, E>
480 where
481 F: FnOnce() -> Result<T, E>,
482 {
483 if self.get_mut().is_none() {
484 self.initialize(f)?;
485 }
486
487 // SAFETY: The inner value has been initialized
488 Ok(unsafe { self.get_unchecked_mut() })
489 }
490
491 /// Consumes the `OnceLock`, returning the wrapped value. Returns
492 /// `None` if the cell was uninitialized.
493 ///
494 /// # Examples
495 ///
496 /// ```
497 /// use std::sync::OnceLock;
498 ///
499 /// let cell: OnceLock<String> = OnceLock::new();
500 /// assert_eq!(cell.into_inner(), None);
501 ///
502 /// let cell = OnceLock::new();
503 /// cell.set("hello".to_string()).unwrap();
504 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
505 /// ```
506 #[inline]
507 #[stable(feature = "once_cell", since = "1.70.0")]
508 pub fn into_inner(mut self) -> Option<T> {
509 self.take()
510 }
511
512 /// Takes the value out of this `OnceLock`, moving it back to an uninitialized state.
513 ///
514 /// Has no effect and returns `None` if the `OnceLock` was uninitialized.
515 ///
516 /// Since this method borrows the `OnceLock` mutably, it is statically guaranteed that
517 /// no active borrows to the `OnceLock` exist, including from other threads.
518 ///
519 /// # Examples
520 ///
521 /// ```
522 /// use std::sync::OnceLock;
523 ///
524 /// let mut cell: OnceLock<String> = OnceLock::new();
525 /// assert_eq!(cell.take(), None);
526 ///
527 /// let mut cell = OnceLock::new();
528 /// cell.set("hello".to_string()).unwrap();
529 /// assert_eq!(cell.take(), Some("hello".to_string()));
530 /// assert_eq!(cell.get(), None);
531 /// ```
532 #[inline]
533 #[stable(feature = "once_cell", since = "1.70.0")]
534 pub fn take(&mut self) -> Option<T> {
535 if self.initialized_mut() {
536 self.once = Once::new();
537 // SAFETY: `self.value` is initialized and contains a valid `T`.
538 // `self.once` is reset, so `initialized()` will be false again
539 // which prevents the value from being read twice.
540 unsafe { Some(self.value.get_mut().assume_init_read()) }
541 } else {
542 None
543 }
544 }
545
546 #[inline]
547 fn initialized(&self) -> bool {
548 self.once.is_completed()
549 }
550
551 #[inline]
552 fn initialized_mut(&mut self) -> bool {
553 // `state()` does not perform an atomic load, so prefer it over `is_complete()`.
554 let state = self.once.state();
555 match state {
556 OnceExclusiveState::Complete => true,
557 _ => false,
558 }
559 }
560
561 #[cold]
562 #[optimize(size)]
563 fn initialize<F, E>(&self, f: F) -> Result<(), E>
564 where
565 F: FnOnce() -> Result<T, E>,
566 {
567 let mut res: Result<(), E> = Ok(());
568 let slot = &self.value;
569
570 // Ignore poisoning from other threads
571 // If another thread panics, then we'll be able to run our closure
572 self.once.call_once_force(|p| {
573 match f() {
574 Ok(value) => {
575 unsafe { (&mut *slot.get()).write(value) };
576 }
577 Err(e) => {
578 res = Err(e);
579
580 // Treat the underlying `Once` as poisoned since we
581 // failed to initialize our value.
582 p.poison();
583 }
584 }
585 });
586 res
587 }
588
589 /// Returns a reference to the value in the `OnceLock` without checking
590 /// whether it has been initialized.
591 ///
592 /// # Safety
593 ///
594 /// The `OnceLock` must be initialized before calling this function.
595 ///
596 /// # Examples
597 ///
598 /// ```
599 /// #![feature(once_lazy_lock_get_unchecked)]
600 ///
601 /// use std::sync::OnceLock;
602 ///
603 /// let cell = OnceLock::new();
604 /// cell.set(42).unwrap();
605 ///
606 /// let value = unsafe { cell.get_unchecked() };
607 /// assert_eq!(*value, 42);
608 /// ```
609 #[inline]
610 #[unstable(feature = "once_lazy_lock_get_unchecked", issue = "162716")]
611 pub unsafe fn get_unchecked(&self) -> &T {
612 debug_assert!(self.initialized());
613 unsafe { (&*self.value.get()).assume_init_ref() }
614 }
615
616 /// Returns a mutable reference to the value in the `OnceLock` without
617 /// checking whether it has been initialized.
618 ///
619 /// # Safety
620 ///
621 /// The `OnceLock` must be initialized before calling this function.
622 ///
623 /// # Examples
624 ///
625 /// ```
626 /// #![feature(once_lazy_lock_get_unchecked)]
627 ///
628 /// use std::sync::OnceLock;
629 ///
630 /// let mut cell = OnceLock::new();
631 /// cell.set(42).unwrap();
632 ///
633 /// let value = unsafe { cell.get_unchecked_mut() };
634 /// *value = 100;
635 ///
636 /// assert_eq!(*cell.get().unwrap(), 100);
637 /// ```
638 #[inline]
639 #[unstable(feature = "once_lazy_lock_get_unchecked", issue = "162716")]
640 pub unsafe fn get_unchecked_mut(&mut self) -> &mut T {
641 debug_assert!(self.initialized_mut());
642 unsafe { self.value.get_mut().assume_init_mut() }
643 }
644}
645
646// Why do we need `T: Send`?
647// Thread A creates a `OnceLock` and shares it with
648// scoped thread B, which fills the cell, which is
649// then destroyed by A. That is, destructor observes
650// a sent value.
651#[stable(feature = "once_cell", since = "1.70.0")]
652unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
653#[stable(feature = "once_cell", since = "1.70.0")]
654unsafe impl<T: Send> Send for OnceLock<T> {}
655
656#[stable(feature = "once_cell", since = "1.70.0")]
657impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T> {}
658#[stable(feature = "once_cell", since = "1.70.0")]
659impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {}
660
661#[stable(feature = "once_cell", since = "1.70.0")]
662#[rustc_const_unstable(feature = "const_default", issue = "143894")]
663const impl<T> Default for OnceLock<T> {
664 /// Creates a new uninitialized cell.
665 ///
666 /// # Example
667 ///
668 /// ```
669 /// use std::sync::OnceLock;
670 ///
671 /// fn main() {
672 /// assert_eq!(OnceLock::<()>::new(), OnceLock::default());
673 /// }
674 /// ```
675 #[inline]
676 fn default() -> OnceLock<T> {
677 OnceLock::new()
678 }
679}
680
681#[stable(feature = "once_cell", since = "1.70.0")]
682impl<T: fmt::Debug> fmt::Debug for OnceLock<T> {
683 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
684 let mut d = f.debug_tuple("OnceLock");
685 match self.get() {
686 Some(v) => d.field(v),
687 None => d.field(&format_args!("<uninit>")),
688 };
689 d.finish()
690 }
691}
692
693#[stable(feature = "once_cell", since = "1.70.0")]
694impl<T: Clone> Clone for OnceLock<T> {
695 #[inline]
696 fn clone(&self) -> OnceLock<T> {
697 self.get().cloned().map_or_default(Self::from)
698 }
699}
700
701#[stable(feature = "once_cell", since = "1.70.0")]
702impl<T> From<T> for OnceLock<T> {
703 /// Creates a new cell with its contents set to `value`.
704 ///
705 /// # Example
706 ///
707 /// ```
708 /// use std::sync::OnceLock;
709 ///
710 /// # fn main() -> Result<(), i32> {
711 /// let a = OnceLock::from(3);
712 /// let b = OnceLock::new();
713 /// b.set(3)?;
714 /// assert_eq!(a, b);
715 /// Ok(())
716 /// # }
717 /// ```
718 #[inline]
719 fn from(value: T) -> Self {
720 OnceLock {
721 once: Once::new_complete(),
722 value: UnsafeCell::new(MaybeUninit::new(value)),
723 _marker: PhantomData,
724 }
725 }
726}
727
728#[stable(feature = "once_cell", since = "1.70.0")]
729impl<T: PartialEq> PartialEq for OnceLock<T> {
730 /// Equality for two `OnceLock`s.
731 ///
732 /// Two `OnceLock`s are equal if they either both contain values and their
733 /// values are equal, or if neither contains a value.
734 ///
735 /// # Examples
736 ///
737 /// ```
738 /// use std::sync::OnceLock;
739 ///
740 /// let five = OnceLock::new();
741 /// five.set(5).unwrap();
742 ///
743 /// let also_five = OnceLock::new();
744 /// also_five.set(5).unwrap();
745 ///
746 /// assert!(five == also_five);
747 ///
748 /// assert!(OnceLock::<u32>::new() == OnceLock::<u32>::new());
749 /// ```
750 #[inline]
751 fn eq(&self, other: &OnceLock<T>) -> bool {
752 self.get() == other.get()
753 }
754}
755
756#[stable(feature = "once_cell", since = "1.70.0")]
757impl<T: Eq> Eq for OnceLock<T> {}
758
759#[stable(feature = "once_cell", since = "1.70.0")]
760unsafe impl<#[may_dangle] T> Drop for OnceLock<T> {
761 #[inline]
762 fn drop(&mut self) {
763 if self.initialized_mut() {
764 // SAFETY: The cell is initialized and being dropped, so it can't
765 // be accessed again. We also don't touch the `T` other than
766 // dropping it, which validates our usage of #[may_dangle].
767 unsafe { self.value.get_mut().assume_init_drop() };
768 }
769 }
770}