once_cell/lib.rs
1//! # Overview
2//!
3//! `once_cell` provides two new cell-like types, [`unsync::OnceCell`] and
4//! [`sync::OnceCell`]. A `OnceCell` might store arbitrary non-`Copy` types, can
5//! be assigned to at most once and provides direct access to the stored
6//! contents. The core API looks *roughly* like this (and there's much more
7//! inside, read on!):
8//!
9//! ```rust,ignore
10//! impl<T> OnceCell<T> {
11//! const fn new() -> OnceCell<T> { ... }
12//! fn set(&self, value: T) -> Result<(), T> { ... }
13//! fn get(&self) -> Option<&T> { ... }
14//! }
15//! ```
16//!
17//! Note that, like with [`RefCell`] and [`Mutex`], the `set` method requires
18//! only a shared reference. Because of the single assignment restriction `get`
19//! can return a `&T` instead of `Ref<T>` or `MutexGuard<T>`.
20//!
21//! The `sync` flavor is thread-safe (that is, implements the [`Sync`] trait),
22//! while the `unsync` one is not.
23//!
24//! [`unsync::OnceCell`]: unsync/struct.OnceCell.html
25//! [`sync::OnceCell`]: sync/struct.OnceCell.html
26//! [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
27//! [`Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
28//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
29//!
30//! # Recipes
31//!
32//! `OnceCell` might be useful for a variety of patterns.
33//!
34//! ## Safe Initialization of Global Data
35//!
36//! ```rust
37//! # #[cfg(any(feature = "std", feature = "critical-section"))] {
38//! use std::{env, io};
39//!
40//! use once_cell::sync::OnceCell;
41//!
42//! #[derive(Debug)]
43//! pub struct Logger {
44//! // ...
45//! }
46//! static INSTANCE: OnceCell<Logger> = OnceCell::new();
47//!
48//! impl Logger {
49//! pub fn global() -> &'static Logger {
50//! INSTANCE.get().expect("logger is not initialized")
51//! }
52//!
53//! fn from_cli(args: env::Args) -> Result<Logger, std::io::Error> {
54//! // ...
55//! # Ok(Logger {})
56//! }
57//! }
58//!
59//! fn main() {
60//! let logger = Logger::from_cli(env::args()).unwrap();
61//! INSTANCE.set(logger).unwrap();
62//! // use `Logger::global()` from now on
63//! }
64//! # }
65//! ```
66//!
67//! ## Lazy Initialized Global Data
68//!
69//! This is essentially the `lazy_static!` macro, but without a macro.
70//!
71//! ```rust
72//! # #[cfg(any(feature = "std", feature = "critical-section"))] {
73//! use std::{sync::Mutex, collections::HashMap};
74//!
75//! use once_cell::sync::OnceCell;
76//!
77//! fn global_data() -> &'static Mutex<HashMap<i32, String>> {
78//! static INSTANCE: OnceCell<Mutex<HashMap<i32, String>>> = OnceCell::new();
79//! INSTANCE.get_or_init(|| {
80//! let mut m = HashMap::new();
81//! m.insert(13, "Spica".to_string());
82//! m.insert(74, "Hoyten".to_string());
83//! Mutex::new(m)
84//! })
85//! }
86//! # }
87//! ```
88//!
89//! There are also the [`sync::Lazy`] and [`unsync::Lazy`] convenience types to
90//! streamline this pattern:
91//!
92//! ```rust
93//! # #[cfg(any(feature = "std", feature = "critical-section"))] {
94//! use std::{sync::Mutex, collections::HashMap};
95//! use once_cell::sync::Lazy;
96//!
97//! static GLOBAL_DATA: Lazy<Mutex<HashMap<i32, String>>> = Lazy::new(|| {
98//! let mut m = HashMap::new();
99//! m.insert(13, "Spica".to_string());
100//! m.insert(74, "Hoyten".to_string());
101//! Mutex::new(m)
102//! });
103//!
104//! fn main() {
105//! println!("{:?}", GLOBAL_DATA.lock().unwrap());
106//! }
107//! # }
108//! ```
109//!
110//! Note that the variable that holds `Lazy` is declared as `static`, *not*
111//! `const`. This is important: using `const` instead compiles, but works wrong.
112//!
113//! [`sync::Lazy`]: sync/struct.Lazy.html
114//! [`unsync::Lazy`]: unsync/struct.Lazy.html
115//!
116//! ## General purpose lazy evaluation
117//!
118//! Unlike `lazy_static!`, `Lazy` works with local variables.
119//!
120//! ```rust
121//! use once_cell::unsync::Lazy;
122//!
123//! fn main() {
124//! let ctx = vec![1, 2, 3];
125//! let thunk = Lazy::new(|| {
126//! ctx.iter().sum::<i32>()
127//! });
128//! assert_eq!(*thunk, 6);
129//! }
130//! ```
131//!
132//! If you need a lazy field in a struct, you probably should use `OnceCell`
133//! directly, because that will allow you to access `self` during
134//! initialization.
135//!
136//! ```rust
137//! use std::{fs, path::PathBuf};
138//!
139//! use once_cell::unsync::OnceCell;
140//!
141//! struct Ctx {
142//! config_path: PathBuf,
143//! config: OnceCell<String>,
144//! }
145//!
146//! impl Ctx {
147//! pub fn get_config(&self) -> Result<&str, std::io::Error> {
148//! let cfg = self.config.get_or_try_init(|| {
149//! fs::read_to_string(&self.config_path)
150//! })?;
151//! Ok(cfg.as_str())
152//! }
153//! }
154//! ```
155//!
156//! ## Lazily Compiled Regex
157//!
158//! This is a `regex!` macro which takes a string literal and returns an
159//! *expression* that evaluates to a `&'static Regex`:
160//!
161//! ```
162//! macro_rules! regex {
163//! ($re:literal $(,)?) => {{
164//! static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
165//! RE.get_or_init(|| regex::Regex::new($re).unwrap())
166//! }};
167//! }
168//! ```
169//!
170//! This macro can be useful to avoid the "compile regex on every loop
171//! iteration" problem.
172//!
173//! ## Runtime `include_bytes!`
174//!
175//! The `include_bytes` macro is useful to include test resources, but it slows
176//! down test compilation a lot. An alternative is to load the resources at
177//! runtime:
178//!
179//! ```
180//! # #[cfg(any(feature = "std", feature = "critical-section"))] {
181//! use std::path::Path;
182//!
183//! use once_cell::sync::OnceCell;
184//!
185//! pub struct TestResource {
186//! path: &'static str,
187//! cell: OnceCell<Vec<u8>>,
188//! }
189//!
190//! impl TestResource {
191//! pub const fn new(path: &'static str) -> TestResource {
192//! TestResource { path, cell: OnceCell::new() }
193//! }
194//! pub fn bytes(&self) -> &[u8] {
195//! self.cell.get_or_init(|| {
196//! let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
197//! let path = Path::new(dir.as_str()).join(self.path);
198//! std::fs::read(&path).unwrap_or_else(|_err| {
199//! panic!("failed to load test resource: {}", path.display())
200//! })
201//! }).as_slice()
202//! }
203//! }
204//!
205//! static TEST_IMAGE: TestResource = TestResource::new("test_data/lena.png");
206//!
207//! #[test]
208//! fn test_sobel_filter() {
209//! let rgb: &[u8] = TEST_IMAGE.bytes();
210//! // ...
211//! # drop(rgb);
212//! }
213//! # }
214//! ```
215//!
216//! ## `lateinit`
217//!
218//! `LateInit` type for delayed initialization. It is reminiscent of Kotlin's
219//! `lateinit` keyword and allows construction of cyclic data structures:
220//!
221//!
222//! ```
223//! # #[cfg(any(feature = "std", feature = "critical-section"))] {
224//! use once_cell::sync::OnceCell;
225//!
226//! pub struct LateInit<T> { cell: OnceCell<T> }
227//!
228//! impl<T> LateInit<T> {
229//! pub fn init(&self, value: T) {
230//! assert!(self.cell.set(value).is_ok())
231//! }
232//! }
233//!
234//! impl<T> Default for LateInit<T> {
235//! fn default() -> Self { LateInit { cell: OnceCell::default() } }
236//! }
237//!
238//! impl<T> std::ops::Deref for LateInit<T> {
239//! type Target = T;
240//! fn deref(&self) -> &T {
241//! self.cell.get().unwrap()
242//! }
243//! }
244//!
245//! #[derive(Default)]
246//! struct A<'a> {
247//! b: LateInit<&'a B<'a>>,
248//! }
249//!
250//! #[derive(Default)]
251//! struct B<'a> {
252//! a: LateInit<&'a A<'a>>
253//! }
254//!
255//!
256//! fn build_cycle() {
257//! let a = A::default();
258//! let b = B::default();
259//! a.b.init(&b);
260//! b.a.init(&a);
261//!
262//! let _a = &a.b.a.b.a;
263//! }
264//! # }
265//! ```
266//!
267//! # Comparison with std
268//!
269//! |`!Sync` types | Access Mode | Drawbacks |
270//! |----------------------|------------------------|-----------------------------------------------|
271//! |`Cell<T>` | `T` | requires `T: Copy` for `get` |
272//! |`RefCell<T>` | `RefMut<T>` / `Ref<T>` | may panic at runtime |
273//! |`unsync::OnceCell<T>` | `&T` | assignable only once |
274//!
275//! |`Sync` types | Access Mode | Drawbacks |
276//! |----------------------|------------------------|-----------------------------------------------|
277//! |`AtomicT` | `T` | works only with certain `Copy` types |
278//! |`Mutex<T>` | `MutexGuard<T>` | may deadlock at runtime, may block the thread |
279//! |`sync::OnceCell<T>` | `&T` | assignable only once, may block the thread |
280//!
281//! Technically, calling `get_or_init` will also cause a panic or a deadlock if
282//! it recursively calls itself. However, because the assignment can happen only
283//! once, such cases should be more rare than equivalents with `RefCell` and
284//! `Mutex`.
285//!
286//! # Minimum Supported `rustc` Version
287//!
288//! If only the `std`, `alloc`, or `race` features are enabled, MSRV will be
289//! updated conservatively, supporting at least latest 8 versions of the compiler.
290//! When using other features, like `parking_lot`, MSRV might be updated more
291//! frequently, up to the latest stable. In both cases, increasing MSRV is *not*
292//! considered a semver-breaking change and requires only a minor version bump.
293//!
294//! # Implementation details
295//!
296//! The implementation is based on the
297//! [`lazy_static`](https://github.com/rust-lang-nursery/lazy-static.rs/) and
298//! [`lazy_cell`](https://github.com/indiv0/lazycell/) crates and
299//! [`std::sync::Once`]. In some sense, `once_cell` just streamlines and unifies
300//! those APIs.
301//!
302//! To implement a sync flavor of `OnceCell`, this crates uses either a custom
303//! re-implementation of `std::sync::Once` or `parking_lot::Mutex`. This is
304//! controlled by the `parking_lot` feature (disabled by default). Performance
305//! is the same for both cases, but the `parking_lot` based `OnceCell<T>` is
306//! smaller by up to 16 bytes.
307//!
308//! This crate uses `unsafe`.
309//!
310//! [`std::sync::Once`]: https://doc.rust-lang.org/std/sync/struct.Once.html
311//!
312//! # F.A.Q.
313//!
314//! **Should I use the sync or unsync flavor?**
315//!
316//! Because Rust compiler checks thread safety for you, it's impossible to
317//! accidentally use `unsync` where `sync` is required. So, use `unsync` in
318//! single-threaded code and `sync` in multi-threaded. It's easy to switch
319//! between the two if code becomes multi-threaded later.
320//!
321//! At the moment, `unsync` has an additional benefit that reentrant
322//! initialization causes a panic, which might be easier to debug than a
323//! deadlock.
324//!
325//! **Does this crate support async?**
326//!
327//! No, but you can use
328//! [`async_once_cell`](https://crates.io/crates/async_once_cell) instead.
329//!
330//! **Does this crate support `no_std`?**
331//!
332//! Yes, but with caveats. `OnceCell` is a synchronization primitive which
333//! _semantically_ relies on blocking. `OnceCell` guarantees that at most one
334//! `f` will be called to compute the value. If two threads of execution call
335//! `get_or_init` concurrently, one of them has to wait.
336//!
337//! Waiting fundamentally requires OS support. Execution environment needs to
338//! understand who waits on whom to prevent deadlocks due to priority inversion.
339//! You _could_ make code to compile by blindly using pure spinlocks, but the
340//! runtime behavior would be subtly wrong.
341//!
342//! Given these constraints, `once_cell` provides the following options:
343//!
344//! - The `race` module provides similar, but distinct synchronization primitive
345//! which is compatible with `no_std`. With `race`, the `f` function can be
346//! called multiple times by different threads, but only one thread will win
347//! to install the value.
348//! - `critical-section` feature (with a `-`, not `_`) uses `critical_section`
349//! to implement blocking.
350//!
351//! **Can I bring my own mutex?**
352//!
353//! There is [generic_once_cell](https://crates.io/crates/generic_once_cell) to
354//! allow just that.
355//!
356//! **Should I use `std::cell::OnceCell`, `once_cell`, or `lazy_static`?**
357//!
358//! If you can use `std` version (your MSRV is at least 1.70, and you don't need
359//! extra features `once_cell` provides), use `std`. Otherwise, use `once_cell`.
360//! Don't use `lazy_static`.
361//!
362//! # Related crates
363//!
364//! * Most of this crate's functionality is available in `std` starting with
365//! Rust 1.70. See `std::cell::OnceCell` and `std::sync::OnceLock`.
366//! * [double-checked-cell](https://github.com/niklasf/double-checked-cell)
367//! * [lazy-init](https://crates.io/crates/lazy-init)
368//! * [lazycell](https://crates.io/crates/lazycell)
369//! * [mitochondria](https://crates.io/crates/mitochondria)
370//! * [lazy_static](https://crates.io/crates/lazy_static)
371//! * [async_once_cell](https://crates.io/crates/async_once_cell)
372//! * [generic_once_cell](https://crates.io/crates/generic_once_cell) (bring
373//! your own mutex)
374
375#![cfg_attr(not(feature = "std"), no_std)]
376
377#[cfg(feature = "alloc")]
378extern crate alloc;
379
380#[cfg(all(feature = "critical-section", not(feature = "std")))]
381#[path = "imp_cs.rs"]
382mod imp;
383
384#[cfg(all(feature = "std", feature = "parking_lot"))]
385#[path = "imp_pl.rs"]
386mod imp;
387
388#[cfg(all(feature = "std", not(feature = "parking_lot")))]
389#[path = "imp_std.rs"]
390mod imp;
391
392/// Single-threaded version of `OnceCell`.
393pub mod unsync {
394 use core::{
395 cell::{Cell, UnsafeCell},
396 fmt, mem,
397 ops::{Deref, DerefMut},
398 panic::{RefUnwindSafe, UnwindSafe},
399 };
400
401 /// A cell which can be written to only once. It is not thread safe.
402 ///
403 /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&`
404 /// references to the contents.
405 ///
406 /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
407 ///
408 /// # Example
409 /// ```
410 /// use once_cell::unsync::OnceCell;
411 ///
412 /// let cell = OnceCell::new();
413 /// assert!(cell.get().is_none());
414 ///
415 /// let value: &String = cell.get_or_init(|| {
416 /// "Hello, World!".to_string()
417 /// });
418 /// assert_eq!(value, "Hello, World!");
419 /// assert!(cell.get().is_some());
420 /// ```
421 pub struct OnceCell<T> {
422 // Invariant: written to at most once.
423 inner: UnsafeCell<Option<T>>,
424 }
425
426 // Similarly to a `Sync` bound on `sync::OnceCell`, we can use
427 // `&unsync::OnceCell` to sneak a `T` through `catch_unwind`,
428 // by initializing the cell in closure and extracting the value in the
429 // `Drop`.
430 impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceCell<T> {}
431 impl<T: UnwindSafe> UnwindSafe for OnceCell<T> {}
432
433 impl<T> Default for OnceCell<T> {
434 fn default() -> Self {
435 Self::new()
436 }
437 }
438
439 impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
440 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441 match self.get() {
442 Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
443 None => f.write_str("OnceCell(Uninit)"),
444 }
445 }
446 }
447
448 impl<T: Clone> Clone for OnceCell<T> {
449 fn clone(&self) -> OnceCell<T> {
450 match self.get() {
451 Some(value) => OnceCell::with_value(value.clone()),
452 None => OnceCell::new(),
453 }
454 }
455
456 fn clone_from(&mut self, source: &Self) {
457 match (self.get_mut(), source.get()) {
458 (Some(this), Some(source)) => this.clone_from(source),
459 _ => *self = source.clone(),
460 }
461 }
462 }
463
464 impl<T: PartialEq> PartialEq for OnceCell<T> {
465 fn eq(&self, other: &Self) -> bool {
466 self.get() == other.get()
467 }
468 }
469
470 impl<T: Eq> Eq for OnceCell<T> {}
471
472 impl<T> From<T> for OnceCell<T> {
473 fn from(value: T) -> Self {
474 OnceCell::with_value(value)
475 }
476 }
477
478 impl<T> OnceCell<T> {
479 /// Creates a new empty cell.
480 pub const fn new() -> OnceCell<T> {
481 OnceCell { inner: UnsafeCell::new(None) }
482 }
483
484 /// Creates a new initialized cell.
485 pub const fn with_value(value: T) -> OnceCell<T> {
486 OnceCell { inner: UnsafeCell::new(Some(value)) }
487 }
488
489 /// Gets a reference to the underlying value.
490 ///
491 /// Returns `None` if the cell is empty.
492 #[inline]
493 pub fn get(&self) -> Option<&T> {
494 // Safe due to `inner`'s invariant of being written to at most once.
495 // Had multiple writes to `inner` been allowed, a reference to the
496 // value we return now would become dangling by a write of a
497 // different value later.
498 unsafe { &*self.inner.get() }.as_ref()
499 }
500
501 /// Gets a mutable reference to the underlying value.
502 ///
503 /// Returns `None` if the cell is empty.
504 ///
505 /// This method is allowed to violate the invariant of writing to a `OnceCell`
506 /// at most once because it requires `&mut` access to `self`. As with all
507 /// interior mutability, `&mut` access permits arbitrary modification:
508 ///
509 /// ```
510 /// use once_cell::unsync::OnceCell;
511 ///
512 /// let mut cell: OnceCell<u32> = OnceCell::new();
513 /// cell.set(92).unwrap();
514 /// *cell.get_mut().unwrap() = 93;
515 /// assert_eq!(cell.get(), Some(&93));
516 /// ```
517 #[inline]
518 pub fn get_mut(&mut self) -> Option<&mut T> {
519 // Safe because we have unique access
520 unsafe { &mut *self.inner.get() }.as_mut()
521 }
522
523 /// Sets the contents of this cell to `value`.
524 ///
525 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
526 /// full.
527 ///
528 /// # Example
529 /// ```
530 /// use once_cell::unsync::OnceCell;
531 ///
532 /// let cell = OnceCell::new();
533 /// assert!(cell.get().is_none());
534 ///
535 /// assert_eq!(cell.set(92), Ok(()));
536 /// assert_eq!(cell.set(62), Err(62));
537 ///
538 /// assert!(cell.get().is_some());
539 /// ```
540 pub fn set(&self, value: T) -> Result<(), T> {
541 match self.try_insert(value) {
542 Ok(_) => Ok(()),
543 Err((_, value)) => Err(value),
544 }
545 }
546
547 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
548 ///
549 /// # Example
550 /// ```
551 /// use once_cell::unsync::OnceCell;
552 ///
553 /// let cell = OnceCell::new();
554 /// assert!(cell.get().is_none());
555 ///
556 /// assert_eq!(cell.try_insert(92), Ok(&92));
557 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
558 ///
559 /// assert!(cell.get().is_some());
560 /// ```
561 pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
562 if let Some(old) = self.get() {
563 return Err((old, value));
564 }
565
566 let slot = unsafe { &mut *self.inner.get() };
567 // This is the only place where we set the slot, no races
568 // due to reentrancy/concurrency are possible, and we've
569 // checked that slot is currently `None`, so this write
570 // maintains the `inner`'s invariant.
571 *slot = Some(value);
572 Ok(unsafe { slot.as_ref().unwrap_unchecked() })
573 }
574
575 /// Gets the contents of the cell, initializing it with `f`
576 /// if the cell was empty.
577 ///
578 /// # Panics
579 ///
580 /// If `f` panics, the panic is propagated to the caller, and the cell
581 /// remains uninitialized.
582 ///
583 /// It is an error to reentrantly initialize the cell from `f`. Doing
584 /// so results in a panic.
585 ///
586 /// # Example
587 /// ```
588 /// use once_cell::unsync::OnceCell;
589 ///
590 /// let cell = OnceCell::new();
591 /// let value = cell.get_or_init(|| 92);
592 /// assert_eq!(value, &92);
593 /// let value = cell.get_or_init(|| unreachable!());
594 /// assert_eq!(value, &92);
595 /// ```
596 pub fn get_or_init<F>(&self, f: F) -> &T
597 where
598 F: FnOnce() -> T,
599 {
600 enum Void {}
601 match self.get_or_try_init(|| Ok::<T, Void>(f())) {
602 Ok(val) => val,
603 Err(void) => match void {},
604 }
605 }
606
607 /// Gets the contents of the cell, initializing it with `f` if
608 /// the cell was empty. If the cell was empty and `f` failed, an
609 /// error is returned.
610 ///
611 /// # Panics
612 ///
613 /// If `f` panics, the panic is propagated to the caller, and the cell
614 /// remains uninitialized.
615 ///
616 /// It is an error to reentrantly initialize the cell from `f`. Doing
617 /// so results in a panic.
618 ///
619 /// # Example
620 /// ```
621 /// use once_cell::unsync::OnceCell;
622 ///
623 /// let cell = OnceCell::new();
624 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
625 /// assert!(cell.get().is_none());
626 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
627 /// Ok(92)
628 /// });
629 /// assert_eq!(value, Ok(&92));
630 /// assert_eq!(cell.get(), Some(&92))
631 /// ```
632 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
633 where
634 F: FnOnce() -> Result<T, E>,
635 {
636 if let Some(val) = self.get() {
637 return Ok(val);
638 }
639 let val = f()?;
640 // Note that *some* forms of reentrant initialization might lead to
641 // UB (see `reentrant_init` test). I believe that just removing this
642 // `assert`, while keeping `set/get` would be sound, but it seems
643 // better to panic, rather than to silently use an old value.
644 assert!(self.set(val).is_ok(), "reentrant init");
645 Ok(unsafe { self.get().unwrap_unchecked() })
646 }
647
648 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
649 ///
650 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
651 ///
652 /// # Examples
653 ///
654 /// ```
655 /// use once_cell::unsync::OnceCell;
656 ///
657 /// let mut cell: OnceCell<String> = OnceCell::new();
658 /// assert_eq!(cell.take(), None);
659 ///
660 /// let mut cell = OnceCell::new();
661 /// cell.set("hello".to_string()).unwrap();
662 /// assert_eq!(cell.take(), Some("hello".to_string()));
663 /// assert_eq!(cell.get(), None);
664 /// ```
665 ///
666 /// This method is allowed to violate the invariant of writing to a `OnceCell`
667 /// at most once because it requires `&mut` access to `self`. As with all
668 /// interior mutability, `&mut` access permits arbitrary modification:
669 ///
670 /// ```
671 /// use once_cell::unsync::OnceCell;
672 ///
673 /// let mut cell: OnceCell<u32> = OnceCell::new();
674 /// cell.set(92).unwrap();
675 /// cell = OnceCell::new();
676 /// ```
677 pub fn take(&mut self) -> Option<T> {
678 mem::take(self).into_inner()
679 }
680
681 /// Consumes the `OnceCell`, returning the wrapped value.
682 ///
683 /// Returns `None` if the cell was empty.
684 ///
685 /// # Examples
686 ///
687 /// ```
688 /// use once_cell::unsync::OnceCell;
689 ///
690 /// let cell: OnceCell<String> = OnceCell::new();
691 /// assert_eq!(cell.into_inner(), None);
692 ///
693 /// let cell = OnceCell::new();
694 /// cell.set("hello".to_string()).unwrap();
695 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
696 /// ```
697 pub fn into_inner(self) -> Option<T> {
698 // Because `into_inner` takes `self` by value, the compiler statically verifies
699 // that it is not currently borrowed. So it is safe to move out `Option<T>`.
700 self.inner.into_inner()
701 }
702 }
703
704 /// A value which is initialized on the first access.
705 ///
706 /// # Example
707 /// ```
708 /// use once_cell::unsync::Lazy;
709 ///
710 /// let lazy: Lazy<i32> = Lazy::new(|| {
711 /// println!("initializing");
712 /// 92
713 /// });
714 /// println!("ready");
715 /// println!("{}", *lazy);
716 /// println!("{}", *lazy);
717 ///
718 /// // Prints:
719 /// // ready
720 /// // initializing
721 /// // 92
722 /// // 92
723 /// ```
724 pub struct Lazy<T, F = fn() -> T> {
725 cell: OnceCell<T>,
726 init: Cell<Option<F>>,
727 }
728
729 impl<T, F: RefUnwindSafe> RefUnwindSafe for Lazy<T, F> where OnceCell<T>: RefUnwindSafe {}
730
731 impl<T: fmt::Debug, F> fmt::Debug for Lazy<T, F> {
732 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
733 f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
734 }
735 }
736
737 impl<T, F> Lazy<T, F> {
738 /// Creates a new lazy value with the given initializing function.
739 ///
740 /// # Example
741 /// ```
742 /// # fn main() {
743 /// use once_cell::unsync::Lazy;
744 ///
745 /// let hello = "Hello, World!".to_string();
746 ///
747 /// let lazy = Lazy::new(|| hello.to_uppercase());
748 ///
749 /// assert_eq!(&*lazy, "HELLO, WORLD!");
750 /// # }
751 /// ```
752 pub const fn new(init: F) -> Lazy<T, F> {
753 Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
754 }
755
756 /// Consumes this `Lazy` returning the stored value.
757 ///
758 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
759 pub fn into_value(this: Lazy<T, F>) -> Result<T, F> {
760 let cell = this.cell;
761 let init = this.init;
762 cell.into_inner().ok_or_else(|| {
763 init.take().unwrap_or_else(|| panic!("Lazy instance has previously been poisoned"))
764 })
765 }
766 }
767
768 impl<T, F: FnOnce() -> T> Lazy<T, F> {
769 /// Forces the evaluation of this lazy value and returns a reference to
770 /// the result.
771 ///
772 /// This is equivalent to the `Deref` impl, but is explicit.
773 ///
774 /// # Example
775 /// ```
776 /// use once_cell::unsync::Lazy;
777 ///
778 /// let lazy = Lazy::new(|| 92);
779 ///
780 /// assert_eq!(Lazy::force(&lazy), &92);
781 /// assert_eq!(&*lazy, &92);
782 /// ```
783 pub fn force(this: &Lazy<T, F>) -> &T {
784 this.cell.get_or_init(|| match this.init.take() {
785 Some(f) => f(),
786 None => panic!("Lazy instance has previously been poisoned"),
787 })
788 }
789
790 /// Forces the evaluation of this lazy value and returns a mutable reference to
791 /// the result.
792 ///
793 /// This is equivalent to the `DerefMut` impl, but is explicit.
794 ///
795 /// # Example
796 /// ```
797 /// use once_cell::unsync::Lazy;
798 ///
799 /// let mut lazy = Lazy::new(|| 92);
800 ///
801 /// assert_eq!(Lazy::force_mut(&mut lazy), &92);
802 /// assert_eq!(*lazy, 92);
803 /// ```
804 pub fn force_mut(this: &mut Lazy<T, F>) -> &mut T {
805 if this.cell.get_mut().is_none() {
806 let value = match this.init.get_mut().take() {
807 Some(f) => f(),
808 None => panic!("Lazy instance has previously been poisoned"),
809 };
810 this.cell = OnceCell::with_value(value);
811 }
812 this.cell.get_mut().unwrap_or_else(|| unreachable!())
813 }
814
815 /// Gets the reference to the result of this lazy value if
816 /// it was initialized, otherwise returns `None`.
817 ///
818 /// # Example
819 /// ```
820 /// use once_cell::unsync::Lazy;
821 ///
822 /// let lazy = Lazy::new(|| 92);
823 ///
824 /// assert_eq!(Lazy::get(&lazy), None);
825 /// assert_eq!(&*lazy, &92);
826 /// assert_eq!(Lazy::get(&lazy), Some(&92));
827 /// ```
828 pub fn get(this: &Lazy<T, F>) -> Option<&T> {
829 this.cell.get()
830 }
831
832 /// Gets the mutable reference to the result of this lazy value if
833 /// it was initialized, otherwise returns `None`.
834 ///
835 /// # Example
836 /// ```
837 /// use once_cell::unsync::Lazy;
838 ///
839 /// let mut lazy = Lazy::new(|| 92);
840 ///
841 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
842 /// assert_eq!(*lazy, 92);
843 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
844 /// ```
845 pub fn get_mut(this: &mut Lazy<T, F>) -> Option<&mut T> {
846 this.cell.get_mut()
847 }
848 }
849
850 impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
851 type Target = T;
852 fn deref(&self) -> &T {
853 Lazy::force(self)
854 }
855 }
856
857 impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
858 fn deref_mut(&mut self) -> &mut T {
859 Lazy::force_mut(self)
860 }
861 }
862
863 impl<T: Default> Default for Lazy<T> {
864 /// Creates a new lazy value using `Default` as the initializing function.
865 fn default() -> Lazy<T> {
866 Lazy::new(T::default)
867 }
868 }
869}
870
871/// Thread-safe, blocking version of `OnceCell`.
872#[cfg(any(feature = "std", feature = "critical-section"))]
873pub mod sync {
874 use core::{
875 cell::Cell,
876 fmt, mem,
877 ops::{Deref, DerefMut},
878 panic::RefUnwindSafe,
879 };
880
881 use super::imp::OnceCell as Imp;
882
883 /// A thread-safe cell which can be written to only once.
884 ///
885 /// `OnceCell` provides `&` references to the contents without RAII guards.
886 ///
887 /// Reading a non-`None` value out of `OnceCell` establishes a
888 /// happens-before relationship with a corresponding write. For example, if
889 /// thread A initializes the cell with `get_or_init(f)`, and thread B
890 /// subsequently reads the result of this call, B also observes all the side
891 /// effects of `f`.
892 ///
893 /// # Example
894 /// ```
895 /// use once_cell::sync::OnceCell;
896 ///
897 /// static CELL: OnceCell<String> = OnceCell::new();
898 /// assert!(CELL.get().is_none());
899 ///
900 /// std::thread::spawn(|| {
901 /// let value: &String = CELL.get_or_init(|| {
902 /// "Hello, World!".to_string()
903 /// });
904 /// assert_eq!(value, "Hello, World!");
905 /// }).join().unwrap();
906 ///
907 /// let value: Option<&String> = CELL.get();
908 /// assert!(value.is_some());
909 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
910 /// ```
911 pub struct OnceCell<T>(Imp<T>);
912
913 impl<T> Default for OnceCell<T> {
914 fn default() -> OnceCell<T> {
915 OnceCell::new()
916 }
917 }
918
919 impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
921 match self.get() {
922 Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
923 None => f.write_str("OnceCell(Uninit)"),
924 }
925 }
926 }
927
928 impl<T: Clone> Clone for OnceCell<T> {
929 fn clone(&self) -> OnceCell<T> {
930 match self.get() {
931 Some(value) => Self::with_value(value.clone()),
932 None => Self::new(),
933 }
934 }
935
936 fn clone_from(&mut self, source: &Self) {
937 match (self.get_mut(), source.get()) {
938 (Some(this), Some(source)) => this.clone_from(source),
939 _ => *self = source.clone(),
940 }
941 }
942 }
943
944 impl<T> From<T> for OnceCell<T> {
945 fn from(value: T) -> Self {
946 Self::with_value(value)
947 }
948 }
949
950 impl<T: PartialEq> PartialEq for OnceCell<T> {
951 fn eq(&self, other: &OnceCell<T>) -> bool {
952 self.get() == other.get()
953 }
954 }
955
956 impl<T: Eq> Eq for OnceCell<T> {}
957
958 impl<T> OnceCell<T> {
959 /// Creates a new empty cell.
960 pub const fn new() -> OnceCell<T> {
961 OnceCell(Imp::new())
962 }
963
964 /// Creates a new initialized cell.
965 pub const fn with_value(value: T) -> OnceCell<T> {
966 OnceCell(Imp::with_value(value))
967 }
968
969 /// Gets the reference to the underlying value.
970 ///
971 /// Returns `None` if the cell is empty, or being initialized. This
972 /// method never blocks.
973 pub fn get(&self) -> Option<&T> {
974 if self.0.is_initialized() {
975 // Safe b/c value is initialized.
976 Some(unsafe { self.get_unchecked() })
977 } else {
978 None
979 }
980 }
981
982 /// Gets the reference to the underlying value, blocking the current
983 /// thread until it is set.
984 ///
985 /// ```
986 /// use once_cell::sync::OnceCell;
987 ///
988 /// let mut cell = std::sync::Arc::new(OnceCell::new());
989 /// let t = std::thread::spawn({
990 /// let cell = std::sync::Arc::clone(&cell);
991 /// move || cell.set(92).unwrap()
992 /// });
993 ///
994 /// // Returns immediately, but might return None.
995 /// let _value_or_none = cell.get();
996 ///
997 /// // Will return 92, but might block until the other thread does `.set`.
998 /// let value: &u32 = cell.wait();
999 /// assert_eq!(*value, 92);
1000 /// t.join().unwrap();
1001 /// ```
1002 #[cfg(feature = "std")]
1003 pub fn wait(&self) -> &T {
1004 if !self.0.is_initialized() {
1005 self.0.wait()
1006 }
1007 debug_assert!(self.0.is_initialized());
1008 // Safe b/c of the wait call above and the fact that we didn't
1009 // relinquish our borrow.
1010 unsafe { self.get_unchecked() }
1011 }
1012
1013 /// Gets the mutable reference to the underlying value.
1014 ///
1015 /// Returns `None` if the cell is empty.
1016 ///
1017 /// This method is allowed to violate the invariant of writing to a `OnceCell`
1018 /// at most once because it requires `&mut` access to `self`. As with all
1019 /// interior mutability, `&mut` access permits arbitrary modification:
1020 ///
1021 /// ```
1022 /// use once_cell::sync::OnceCell;
1023 ///
1024 /// let mut cell: OnceCell<u32> = OnceCell::new();
1025 /// cell.set(92).unwrap();
1026 /// cell = OnceCell::new();
1027 /// ```
1028 #[inline]
1029 pub fn get_mut(&mut self) -> Option<&mut T> {
1030 self.0.get_mut()
1031 }
1032
1033 /// Get the reference to the underlying value, without checking if the
1034 /// cell is initialized.
1035 ///
1036 /// # Safety
1037 ///
1038 /// Caller must ensure that the cell is in initialized state, and that
1039 /// the contents are acquired by (synchronized to) this thread.
1040 #[inline]
1041 pub unsafe fn get_unchecked(&self) -> &T {
1042 self.0.get_unchecked()
1043 }
1044
1045 /// Sets the contents of this cell to `value`.
1046 ///
1047 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
1048 /// full.
1049 ///
1050 /// # Example
1051 ///
1052 /// ```
1053 /// use once_cell::sync::OnceCell;
1054 ///
1055 /// static CELL: OnceCell<i32> = OnceCell::new();
1056 ///
1057 /// fn main() {
1058 /// assert!(CELL.get().is_none());
1059 ///
1060 /// std::thread::spawn(|| {
1061 /// assert_eq!(CELL.set(92), Ok(()));
1062 /// }).join().unwrap();
1063 ///
1064 /// assert_eq!(CELL.set(62), Err(62));
1065 /// assert_eq!(CELL.get(), Some(&92));
1066 /// }
1067 /// ```
1068 pub fn set(&self, value: T) -> Result<(), T> {
1069 match self.try_insert(value) {
1070 Ok(_) => Ok(()),
1071 Err((_, value)) => Err(value),
1072 }
1073 }
1074
1075 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
1076 ///
1077 /// # Example
1078 ///
1079 /// ```
1080 /// use once_cell::sync::OnceCell;
1081 ///
1082 /// let cell = OnceCell::new();
1083 /// assert!(cell.get().is_none());
1084 ///
1085 /// assert_eq!(cell.try_insert(92), Ok(&92));
1086 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
1087 ///
1088 /// assert!(cell.get().is_some());
1089 /// ```
1090 pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
1091 let mut value = Some(value);
1092 let res = self.get_or_init(|| unsafe { value.take().unwrap_unchecked() });
1093 match value {
1094 None => Ok(res),
1095 Some(value) => Err((res, value)),
1096 }
1097 }
1098
1099 /// Gets the contents of the cell, initializing it with `f` if the cell
1100 /// was empty.
1101 ///
1102 /// Many threads may call `get_or_init` concurrently with different
1103 /// initializing functions, but it is guaranteed that only one function
1104 /// will be executed.
1105 ///
1106 /// # Panics
1107 ///
1108 /// If `f` panics, the panic is propagated to the caller, and the cell
1109 /// remains uninitialized.
1110 ///
1111 /// It is an error to reentrantly initialize the cell from `f`. The
1112 /// exact outcome is unspecified. Current implementation deadlocks, but
1113 /// this may be changed to a panic in the future.
1114 ///
1115 /// # Example
1116 /// ```
1117 /// use once_cell::sync::OnceCell;
1118 ///
1119 /// let cell = OnceCell::new();
1120 /// let value = cell.get_or_init(|| 92);
1121 /// assert_eq!(value, &92);
1122 /// let value = cell.get_or_init(|| unreachable!());
1123 /// assert_eq!(value, &92);
1124 /// ```
1125 pub fn get_or_init<F>(&self, f: F) -> &T
1126 where
1127 F: FnOnce() -> T,
1128 {
1129 enum Void {}
1130 match self.get_or_try_init(|| Ok::<T, Void>(f())) {
1131 Ok(val) => val,
1132 Err(void) => match void {},
1133 }
1134 }
1135
1136 /// Gets the contents of the cell, initializing it with `f` if
1137 /// the cell was empty. If the cell was empty and `f` failed, an
1138 /// error is returned.
1139 ///
1140 /// # Panics
1141 ///
1142 /// If `f` panics, the panic is propagated to the caller, and
1143 /// the cell remains uninitialized.
1144 ///
1145 /// It is an error to reentrantly initialize the cell from `f`.
1146 /// The exact outcome is unspecified. Current implementation
1147 /// deadlocks, but this may be changed to a panic in the future.
1148 ///
1149 /// # Example
1150 /// ```
1151 /// use once_cell::sync::OnceCell;
1152 ///
1153 /// let cell = OnceCell::new();
1154 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
1155 /// assert!(cell.get().is_none());
1156 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
1157 /// Ok(92)
1158 /// });
1159 /// assert_eq!(value, Ok(&92));
1160 /// assert_eq!(cell.get(), Some(&92))
1161 /// ```
1162 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
1163 where
1164 F: FnOnce() -> Result<T, E>,
1165 {
1166 // Fast path check
1167 if let Some(value) = self.get() {
1168 return Ok(value);
1169 }
1170
1171 self.0.initialize(f)?;
1172
1173 // Safe b/c value is initialized.
1174 debug_assert!(self.0.is_initialized());
1175 Ok(unsafe { self.get_unchecked() })
1176 }
1177
1178 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
1179 ///
1180 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
1181 ///
1182 /// # Examples
1183 ///
1184 /// ```
1185 /// use once_cell::sync::OnceCell;
1186 ///
1187 /// let mut cell: OnceCell<String> = OnceCell::new();
1188 /// assert_eq!(cell.take(), None);
1189 ///
1190 /// let mut cell = OnceCell::new();
1191 /// cell.set("hello".to_string()).unwrap();
1192 /// assert_eq!(cell.take(), Some("hello".to_string()));
1193 /// assert_eq!(cell.get(), None);
1194 /// ```
1195 ///
1196 /// This method is allowed to violate the invariant of writing to a `OnceCell`
1197 /// at most once because it requires `&mut` access to `self`. As with all
1198 /// interior mutability, `&mut` access permits arbitrary modification:
1199 ///
1200 /// ```
1201 /// use once_cell::sync::OnceCell;
1202 ///
1203 /// let mut cell: OnceCell<u32> = OnceCell::new();
1204 /// cell.set(92).unwrap();
1205 /// cell = OnceCell::new();
1206 /// ```
1207 pub fn take(&mut self) -> Option<T> {
1208 mem::take(self).into_inner()
1209 }
1210
1211 /// Consumes the `OnceCell`, returning the wrapped value. Returns
1212 /// `None` if the cell was empty.
1213 ///
1214 /// # Examples
1215 ///
1216 /// ```
1217 /// use once_cell::sync::OnceCell;
1218 ///
1219 /// let cell: OnceCell<String> = OnceCell::new();
1220 /// assert_eq!(cell.into_inner(), None);
1221 ///
1222 /// let cell = OnceCell::new();
1223 /// cell.set("hello".to_string()).unwrap();
1224 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
1225 /// ```
1226 #[inline]
1227 pub fn into_inner(self) -> Option<T> {
1228 self.0.into_inner()
1229 }
1230 }
1231
1232 /// A value which is initialized on the first access.
1233 ///
1234 /// This type is thread-safe and can be used in statics.
1235 ///
1236 /// # Example
1237 ///
1238 /// ```
1239 /// use std::collections::HashMap;
1240 ///
1241 /// use once_cell::sync::Lazy;
1242 ///
1243 /// static HASHMAP: Lazy<HashMap<i32, String>> = Lazy::new(|| {
1244 /// println!("initializing");
1245 /// let mut m = HashMap::new();
1246 /// m.insert(13, "Spica".to_string());
1247 /// m.insert(74, "Hoyten".to_string());
1248 /// m
1249 /// });
1250 ///
1251 /// fn main() {
1252 /// println!("ready");
1253 /// std::thread::spawn(|| {
1254 /// println!("{:?}", HASHMAP.get(&13));
1255 /// }).join().unwrap();
1256 /// println!("{:?}", HASHMAP.get(&74));
1257 ///
1258 /// // Prints:
1259 /// // ready
1260 /// // initializing
1261 /// // Some("Spica")
1262 /// // Some("Hoyten")
1263 /// }
1264 /// ```
1265 pub struct Lazy<T, F = fn() -> T> {
1266 cell: OnceCell<T>,
1267 init: Cell<Option<F>>,
1268 }
1269
1270 impl<T: fmt::Debug, F> fmt::Debug for Lazy<T, F> {
1271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1272 f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
1273 }
1274 }
1275
1276 // We never create a `&F` from a `&Lazy<T, F>` so it is fine to not impl
1277 // `Sync` for `F`. We do create a `&mut Option<F>` in `force`, but this is
1278 // properly synchronized, so it only happens once so it also does not
1279 // contribute to this impl.
1280 unsafe impl<T, F: Send> Sync for Lazy<T, F> where OnceCell<T>: Sync {}
1281 // auto-derived `Send` impl is OK.
1282
1283 impl<T, F: RefUnwindSafe> RefUnwindSafe for Lazy<T, F> where OnceCell<T>: RefUnwindSafe {}
1284
1285 impl<T, F> Lazy<T, F> {
1286 /// Creates a new lazy value with the given initializing
1287 /// function.
1288 pub const fn new(f: F) -> Lazy<T, F> {
1289 Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1290 }
1291
1292 /// Consumes this `Lazy` returning the stored value.
1293 ///
1294 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
1295 pub fn into_value(this: Lazy<T, F>) -> Result<T, F> {
1296 let cell = this.cell;
1297 let init = this.init;
1298 cell.into_inner().ok_or_else(|| {
1299 init.take().unwrap_or_else(|| panic!("Lazy instance has previously been poisoned"))
1300 })
1301 }
1302 }
1303
1304 impl<T, F: FnOnce() -> T> Lazy<T, F> {
1305 /// Forces the evaluation of this lazy value and
1306 /// returns a reference to the result. This is equivalent
1307 /// to the `Deref` impl, but is explicit.
1308 ///
1309 /// # Example
1310 /// ```
1311 /// use once_cell::sync::Lazy;
1312 ///
1313 /// let lazy = Lazy::new(|| 92);
1314 ///
1315 /// assert_eq!(Lazy::force(&lazy), &92);
1316 /// assert_eq!(&*lazy, &92);
1317 /// ```
1318 pub fn force(this: &Lazy<T, F>) -> &T {
1319 this.cell.get_or_init(|| match this.init.take() {
1320 Some(f) => f(),
1321 None => panic!("Lazy instance has previously been poisoned"),
1322 })
1323 }
1324
1325 /// Forces the evaluation of this lazy value and
1326 /// returns a mutable reference to the result. This is equivalent
1327 /// to the `Deref` impl, but is explicit.
1328 ///
1329 /// # Example
1330 /// ```
1331 /// use once_cell::sync::Lazy;
1332 ///
1333 /// let mut lazy = Lazy::new(|| 92);
1334 ///
1335 /// assert_eq!(Lazy::force_mut(&mut lazy), &mut 92);
1336 /// ```
1337 pub fn force_mut(this: &mut Lazy<T, F>) -> &mut T {
1338 if this.cell.get_mut().is_none() {
1339 let value = match this.init.get_mut().take() {
1340 Some(f) => f(),
1341 None => panic!("Lazy instance has previously been poisoned"),
1342 };
1343 this.cell = OnceCell::with_value(value);
1344 }
1345 this.cell.get_mut().unwrap_or_else(|| unreachable!())
1346 }
1347
1348 /// Gets the reference to the result of this lazy value if
1349 /// it was initialized, otherwise returns `None`.
1350 ///
1351 /// # Example
1352 /// ```
1353 /// use once_cell::sync::Lazy;
1354 ///
1355 /// let lazy = Lazy::new(|| 92);
1356 ///
1357 /// assert_eq!(Lazy::get(&lazy), None);
1358 /// assert_eq!(&*lazy, &92);
1359 /// assert_eq!(Lazy::get(&lazy), Some(&92));
1360 /// ```
1361 pub fn get(this: &Lazy<T, F>) -> Option<&T> {
1362 this.cell.get()
1363 }
1364
1365 /// Gets the reference to the result of this lazy value if
1366 /// it was initialized, otherwise returns `None`.
1367 ///
1368 /// # Example
1369 /// ```
1370 /// use once_cell::sync::Lazy;
1371 ///
1372 /// let mut lazy = Lazy::new(|| 92);
1373 ///
1374 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
1375 /// assert_eq!(&*lazy, &92);
1376 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
1377 /// ```
1378 pub fn get_mut(this: &mut Lazy<T, F>) -> Option<&mut T> {
1379 this.cell.get_mut()
1380 }
1381 }
1382
1383 impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
1384 type Target = T;
1385 fn deref(&self) -> &T {
1386 Lazy::force(self)
1387 }
1388 }
1389
1390 impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
1391 fn deref_mut(&mut self) -> &mut T {
1392 Lazy::force_mut(self)
1393 }
1394 }
1395
1396 impl<T: Default> Default for Lazy<T> {
1397 /// Creates a new lazy value using `Default` as the initializing function.
1398 fn default() -> Lazy<T> {
1399 Lazy::new(T::default)
1400 }
1401 }
1402
1403 /// ```compile_fail
1404 /// struct S(*mut ());
1405 /// unsafe impl Sync for S {}
1406 ///
1407 /// fn share<T: Sync>(_: &T) {}
1408 /// share(&once_cell::sync::OnceCell::<S>::new());
1409 /// ```
1410 ///
1411 /// ```compile_fail
1412 /// struct S(*mut ());
1413 /// unsafe impl Sync for S {}
1414 ///
1415 /// fn share<T: Sync>(_: &T) {}
1416 /// share(&once_cell::sync::Lazy::<S>::new(|| unimplemented!()));
1417 /// ```
1418 fn _dummy() {}
1419}
1420
1421#[cfg(feature = "race")]
1422pub mod race;