3 //! `once_cell` provides two new cell-like types, [`unsync::OnceCell`] and [`sync::OnceCell`]. A `OnceCell`
4 //! might store arbitrary non-`Copy` types, can be assigned to at most once and provides direct access
5 //! to the stored contents. The core API looks *roughly* like this (and there's much more inside, read on!):
8 //! impl<T> OnceCell<T> {
9 //! const fn new() -> OnceCell<T> { ... }
10 //! fn set(&self, value: T) -> Result<(), T> { ... }
11 //! fn get(&self) -> Option<&T> { ... }
15 //! Note that, like with [`RefCell`] and [`Mutex`], the `set` method requires only a shared reference.
16 //! Because of the single assignment restriction `get` can return a `&T` instead of `Ref<T>`
17 //! or `MutexGuard<T>`.
19 //! The `sync` flavor is thread-safe (that is, implements the [`Sync`] trait), while the `unsync` one is not.
21 //! [`unsync::OnceCell`]: unsync/struct.OnceCell.html
22 //! [`sync::OnceCell`]: sync/struct.OnceCell.html
23 //! [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
24 //! [`Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
25 //! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
29 //! `OnceCell` might be useful for a variety of patterns.
31 //! ## Safe Initialization of Global Data
34 //! use std::{env, io};
36 //! use once_cell::sync::OnceCell;
39 //! pub struct Logger {
42 //! static INSTANCE: OnceCell<Logger> = OnceCell::new();
45 //! pub fn global() -> &'static Logger {
46 //! INSTANCE.get().expect("logger is not initialized")
49 //! fn from_cli(args: env::Args) -> Result<Logger, std::io::Error> {
56 //! let logger = Logger::from_cli(env::args()).unwrap();
57 //! INSTANCE.set(logger).unwrap();
58 //! // use `Logger::global()` from now on
62 //! ## Lazy Initialized Global Data
64 //! This is essentially the `lazy_static!` macro, but without a macro.
67 //! use std::{sync::Mutex, collections::HashMap};
69 //! use once_cell::sync::OnceCell;
71 //! fn global_data() -> &'static Mutex<HashMap<i32, String>> {
72 //! static INSTANCE: OnceCell<Mutex<HashMap<i32, String>>> = OnceCell::new();
73 //! INSTANCE.get_or_init(|| {
74 //! let mut m = HashMap::new();
75 //! m.insert(13, "Spica".to_string());
76 //! m.insert(74, "Hoyten".to_string());
82 //! There are also the [`sync::Lazy`] and [`unsync::Lazy`] convenience types to streamline this pattern:
85 //! use std::{sync::Mutex, collections::HashMap};
86 //! use once_cell::sync::Lazy;
88 //! static GLOBAL_DATA: Lazy<Mutex<HashMap<i32, String>>> = Lazy::new(|| {
89 //! let mut m = HashMap::new();
90 //! m.insert(13, "Spica".to_string());
91 //! m.insert(74, "Hoyten".to_string());
96 //! println!("{:?}", GLOBAL_DATA.lock().unwrap());
100 //! Note that the variable that holds `Lazy` is declared as `static`, *not*
101 //! `const`. This is important: using `const` instead compiles, but works wrong.
103 //! [`sync::Lazy`]: sync/struct.Lazy.html
104 //! [`unsync::Lazy`]: unsync/struct.Lazy.html
106 //! ## General purpose lazy evaluation
108 //! Unlike `lazy_static!`, `Lazy` works with local variables.
111 //! use once_cell::unsync::Lazy;
114 //! let ctx = vec![1, 2, 3];
115 //! let thunk = Lazy::new(|| {
116 //! ctx.iter().sum::<i32>()
118 //! assert_eq!(*thunk, 6);
122 //! If you need a lazy field in a struct, you probably should use `OnceCell`
123 //! directly, because that will allow you to access `self` during initialization.
126 //! use std::{fs, path::PathBuf};
128 //! use once_cell::unsync::OnceCell;
131 //! config_path: PathBuf,
132 //! config: OnceCell<String>,
136 //! pub fn get_config(&self) -> Result<&str, std::io::Error> {
137 //! let cfg = self.config.get_or_try_init(|| {
138 //! fs::read_to_string(&self.config_path)
145 //! ## Lazily Compiled Regex
147 //! This is a `regex!` macro which takes a string literal and returns an
148 //! *expression* that evaluates to a `&'static Regex`:
151 //! macro_rules! regex {
152 //! ($re:literal $(,)?) => {{
153 //! static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
154 //! RE.get_or_init(|| regex::Regex::new($re).unwrap())
159 //! This macro can be useful to avoid the "compile regex on every loop iteration" problem.
161 //! ## Runtime `include_bytes!`
163 //! The `include_bytes` macro is useful to include test resources, but it slows
164 //! down test compilation a lot. An alternative is to load the resources at
168 //! use std::path::Path;
170 //! use once_cell::sync::OnceCell;
172 //! pub struct TestResource {
173 //! path: &'static str,
174 //! cell: OnceCell<Vec<u8>>,
177 //! impl TestResource {
178 //! pub const fn new(path: &'static str) -> TestResource {
179 //! TestResource { path, cell: OnceCell::new() }
181 //! pub fn bytes(&self) -> &[u8] {
182 //! self.cell.get_or_init(|| {
183 //! let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
184 //! let path = Path::new(dir.as_str()).join(self.path);
185 //! std::fs::read(&path).unwrap_or_else(|_err| {
186 //! panic!("failed to load test resource: {}", path.display())
192 //! static TEST_IMAGE: TestResource = TestResource::new("test_data/lena.png");
195 //! fn test_sobel_filter() {
196 //! let rgb: &[u8] = TEST_IMAGE.bytes();
204 //! `LateInit` type for delayed initialization. It is reminiscent of Kotlin's
205 //! `lateinit` keyword and allows construction of cyclic data structures:
209 //! use once_cell::sync::OnceCell;
211 //! pub struct LateInit<T> { cell: OnceCell<T> }
213 //! impl<T> LateInit<T> {
214 //! pub fn init(&self, value: T) {
215 //! assert!(self.cell.set(value).is_ok())
219 //! impl<T> Default for LateInit<T> {
220 //! fn default() -> Self { LateInit { cell: OnceCell::default() } }
223 //! impl<T> std::ops::Deref for LateInit<T> {
225 //! fn deref(&self) -> &T {
226 //! self.cell.get().unwrap()
230 //! #[derive(Default)]
232 //! b: LateInit<&'a B<'a>>,
235 //! #[derive(Default)]
237 //! a: LateInit<&'a A<'a>>
241 //! fn build_cycle() {
242 //! let a = A::default();
243 //! let b = B::default();
247 //! let _a = &a.b.a.b.a;
251 //! # Comparison with std
253 //! |`!Sync` types | Access Mode | Drawbacks |
254 //! |----------------------|------------------------|-----------------------------------------------|
255 //! |`Cell<T>` | `T` | requires `T: Copy` for `get` |
256 //! |`RefCell<T>` | `RefMut<T>` / `Ref<T>` | may panic at runtime |
257 //! |`unsync::OnceCell<T>` | `&T` | assignable only once |
259 //! |`Sync` types | Access Mode | Drawbacks |
260 //! |----------------------|------------------------|-----------------------------------------------|
261 //! |`AtomicT` | `T` | works only with certain `Copy` types |
262 //! |`Mutex<T>` | `MutexGuard<T>` | may deadlock at runtime, may block the thread |
263 //! |`sync::OnceCell<T>` | `&T` | assignable only once, may block the thread |
265 //! Technically, calling `get_or_init` will also cause a panic or a deadlock if it recursively calls
266 //! itself. However, because the assignment can happen only once, such cases should be more rare than
267 //! equivalents with `RefCell` and `Mutex`.
269 //! # Minimum Supported `rustc` Version
271 //! This crate's minimum supported `rustc` version is `1.56.0`.
273 //! If only the `std` feature is enabled, MSRV will be updated conservatively, supporting at least latest 8 versions of the compiler.
274 //! When using other features, like `parking_lot`, MSRV might be updated more frequently, up to the latest stable.
275 //! In both cases, increasing MSRV is *not* considered a semver-breaking change.
277 //! # Implementation details
279 //! The implementation is based on the [`lazy_static`](https://github.com/rust-lang-nursery/lazy-static.rs/)
280 //! and [`lazy_cell`](https://github.com/indiv0/lazycell/) crates and [`std::sync::Once`]. In some sense,
281 //! `once_cell` just streamlines and unifies those APIs.
283 //! To implement a sync flavor of `OnceCell`, this crates uses either a custom
284 //! re-implementation of `std::sync::Once` or `parking_lot::Mutex`. This is
285 //! controlled by the `parking_lot` feature (disabled by default). Performance
286 //! is the same for both cases, but the `parking_lot` based `OnceCell<T>` is
287 //! smaller by up to 16 bytes.
289 //! This crate uses `unsafe`.
291 //! [`std::sync::Once`]: https://doc.rust-lang.org/std/sync/struct.Once.html
295 //! **Should I use lazy_static or once_cell?**
297 //! To the first approximation, `once_cell` is both more flexible and more convenient than `lazy_static`
298 //! and should be preferred.
300 //! Unlike `once_cell`, `lazy_static` supports spinlock-based implementation of blocking which works with
303 //! `lazy_static` has received significantly more real world testing, but `once_cell` is also a widely
306 //! **Should I use the sync or unsync flavor?**
308 //! Because Rust compiler checks thread safety for you, it's impossible to accidentally use `unsync` where
309 //! `sync` is required. So, use `unsync` in single-threaded code and `sync` in multi-threaded. It's easy
310 //! to switch between the two if code becomes multi-threaded later.
312 //! At the moment, `unsync` has an additional benefit that reentrant initialization causes a panic, which
313 //! might be easier to debug than a deadlock.
315 //! **Does this crate support async?**
317 //! No, but you can use [`async_once_cell`](https://crates.io/crates/async_once_cell) instead.
319 //! **Can I bring my own mutex?**
321 //! There is [generic_once_cell](https://crates.io/crates/generic_once_cell) to allow just that.
325 //! * [double-checked-cell](https://github.com/niklasf/double-checked-cell)
326 //! * [lazy-init](https://crates.io/crates/lazy-init)
327 //! * [lazycell](https://crates.io/crates/lazycell)
328 //! * [mitochondria](https://crates.io/crates/mitochondria)
329 //! * [lazy_static](https://crates.io/crates/lazy_static)
330 //! * [async_once_cell](https://crates.io/crates/async_once_cell)
331 //! * [generic_once_cell](https://crates.io/crates/generic_once_cell) (bring your own mutex)
333 //! Most of this crate's functionality is available in `std` in nightly Rust.
334 //! See the [tracking issue](https://github.com/rust-lang/rust/issues/74465).
336 #![cfg_attr(not(feature = "std"), no_std)]
338 #[cfg(feature = "alloc")]
341 #[cfg(all(feature = "critical-section", not(feature = "std")))]
342 #[path = "imp_cs.rs"]
345 #[cfg(all(feature = "std", feature = "parking_lot"))]
346 #[path = "imp_pl.rs"]
349 #[cfg(all(feature = "std", not(feature = "parking_lot")))]
350 #[path = "imp_std.rs"]
353 /// Single-threaded version of `OnceCell`.
356 cell
::{Cell, UnsafeCell}
,
358 ops
::{Deref, DerefMut}
,
359 panic
::{RefUnwindSafe, UnwindSafe}
,
362 use super::unwrap_unchecked
;
364 /// A cell which can be written to only once. It is not thread safe.
366 /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&`
367 /// references to the contents.
369 /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
373 /// use once_cell::unsync::OnceCell;
375 /// let cell = OnceCell::new();
376 /// assert!(cell.get().is_none());
378 /// let value: &String = cell.get_or_init(|| {
379 /// "Hello, World!".to_string()
381 /// assert_eq!(value, "Hello, World!");
382 /// assert!(cell.get().is_some());
384 pub struct OnceCell
<T
> {
385 // Invariant: written to at most once.
386 inner
: UnsafeCell
<Option
<T
>>,
389 // Similarly to a `Sync` bound on `sync::OnceCell`, we can use
390 // `&unsync::OnceCell` to sneak a `T` through `catch_unwind`,
391 // by initializing the cell in closure and extracting the value in the
393 impl<T
: RefUnwindSafe
+ UnwindSafe
> RefUnwindSafe
for OnceCell
<T
> {}
394 impl<T
: UnwindSafe
> UnwindSafe
for OnceCell
<T
> {}
396 impl<T
> Default
for OnceCell
<T
> {
397 fn default() -> Self {
402 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
403 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
405 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
406 None
=> f
.write_str("OnceCell(Uninit)"),
411 impl<T
: Clone
> Clone
for OnceCell
<T
> {
412 fn clone(&self) -> OnceCell
<T
> {
414 Some(value
) => OnceCell
::with_value(value
.clone()),
415 None
=> OnceCell
::new(),
419 fn clone_from(&mut self, source
: &Self) {
420 match (self.get_mut(), source
.get()) {
421 (Some(this
), Some(source
)) => this
.clone_from(source
),
422 _
=> *self = source
.clone(),
427 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
428 fn eq(&self, other
: &Self) -> bool
{
429 self.get() == other
.get()
433 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
435 impl<T
> From
<T
> for OnceCell
<T
> {
436 fn from(value
: T
) -> Self {
437 OnceCell
::with_value(value
)
441 impl<T
> OnceCell
<T
> {
442 /// Creates a new empty cell.
443 pub const fn new() -> OnceCell
<T
> {
444 OnceCell { inner: UnsafeCell::new(None) }
447 /// Creates a new initialized cell.
448 pub const fn with_value(value
: T
) -> OnceCell
<T
> {
449 OnceCell { inner: UnsafeCell::new(Some(value)) }
452 /// Gets a reference to the underlying value.
454 /// Returns `None` if the cell is empty.
456 pub fn get(&self) -> Option
<&T
> {
457 // Safe due to `inner`'s invariant of being written to at most once.
458 // Had multiple writes to `inner` been allowed, a reference to the
459 // value we return now would become dangling by a write of a
460 // different value later.
461 unsafe { &*self.inner.get() }
.as_ref()
464 /// Gets a mutable reference to the underlying value.
466 /// Returns `None` if the cell is empty.
468 /// This method is allowed to violate the invariant of writing to a `OnceCell`
469 /// at most once because it requires `&mut` access to `self`. As with all
470 /// interior mutability, `&mut` access permits arbitrary modification:
473 /// use once_cell::unsync::OnceCell;
475 /// let mut cell: OnceCell<u32> = OnceCell::new();
476 /// cell.set(92).unwrap();
477 /// *cell.get_mut().unwrap() = 93;
478 /// assert_eq!(cell.get(), Some(&93));
481 pub fn get_mut(&mut self) -> Option
<&mut T
> {
482 // Safe because we have unique access
483 unsafe { &mut *self.inner.get() }
.as_mut()
486 /// Sets the contents of this cell to `value`.
488 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
493 /// use once_cell::unsync::OnceCell;
495 /// let cell = OnceCell::new();
496 /// assert!(cell.get().is_none());
498 /// assert_eq!(cell.set(92), Ok(()));
499 /// assert_eq!(cell.set(62), Err(62));
501 /// assert!(cell.get().is_some());
503 pub fn set(&self, value
: T
) -> Result
<(), T
> {
504 match self.try_insert(value
) {
506 Err((_
, value
)) => Err(value
),
510 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
514 /// use once_cell::unsync::OnceCell;
516 /// let cell = OnceCell::new();
517 /// assert!(cell.get().is_none());
519 /// assert_eq!(cell.try_insert(92), Ok(&92));
520 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
522 /// assert!(cell.get().is_some());
524 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
525 if let Some(old
) = self.get() {
526 return Err((old
, value
));
529 let slot
= unsafe { &mut *self.inner.get() }
;
530 // This is the only place where we set the slot, no races
531 // due to reentrancy/concurrency are possible, and we've
532 // checked that slot is currently `None`, so this write
533 // maintains the `inner`'s invariant.
535 Ok(unsafe { unwrap_unchecked(slot.as_ref()) }
)
538 /// Gets the contents of the cell, initializing it with `f`
539 /// if the cell was empty.
543 /// If `f` panics, the panic is propagated to the caller, and the cell
544 /// remains uninitialized.
546 /// It is an error to reentrantly initialize the cell from `f`. Doing
547 /// so results in a panic.
551 /// use once_cell::unsync::OnceCell;
553 /// let cell = OnceCell::new();
554 /// let value = cell.get_or_init(|| 92);
555 /// assert_eq!(value, &92);
556 /// let value = cell.get_or_init(|| unreachable!());
557 /// assert_eq!(value, &92);
559 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
564 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
566 Err(void
) => match void {}
,
570 /// Gets the contents of the cell, initializing it with `f` if
571 /// the cell was empty. If the cell was empty and `f` failed, an
572 /// error is returned.
576 /// If `f` panics, the panic is propagated to the caller, and the cell
577 /// remains uninitialized.
579 /// It is an error to reentrantly initialize the cell from `f`. Doing
580 /// so results in a panic.
584 /// use once_cell::unsync::OnceCell;
586 /// let cell = OnceCell::new();
587 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
588 /// assert!(cell.get().is_none());
589 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
592 /// assert_eq!(value, Ok(&92));
593 /// assert_eq!(cell.get(), Some(&92))
595 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
597 F
: FnOnce() -> Result
<T
, E
>,
599 if let Some(val
) = self.get() {
603 // Note that *some* forms of reentrant initialization might lead to
604 // UB (see `reentrant_init` test). I believe that just removing this
605 // `assert`, while keeping `set/get` would be sound, but it seems
606 // better to panic, rather than to silently use an old value.
607 assert
!(self.set(val
).is_ok(), "reentrant init");
608 Ok(unsafe { unwrap_unchecked(self.get()) }
)
611 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
613 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
618 /// use once_cell::unsync::OnceCell;
620 /// let mut cell: OnceCell<String> = OnceCell::new();
621 /// assert_eq!(cell.take(), None);
623 /// let mut cell = OnceCell::new();
624 /// cell.set("hello".to_string()).unwrap();
625 /// assert_eq!(cell.take(), Some("hello".to_string()));
626 /// assert_eq!(cell.get(), None);
629 /// This method is allowed to violate the invariant of writing to a `OnceCell`
630 /// at most once because it requires `&mut` access to `self`. As with all
631 /// interior mutability, `&mut` access permits arbitrary modification:
634 /// use once_cell::unsync::OnceCell;
636 /// let mut cell: OnceCell<u32> = OnceCell::new();
637 /// cell.set(92).unwrap();
638 /// cell = OnceCell::new();
640 pub fn take(&mut self) -> Option
<T
> {
641 mem
::replace(self, Self::default()).into_inner()
644 /// Consumes the `OnceCell`, returning the wrapped value.
646 /// Returns `None` if the cell was empty.
651 /// use once_cell::unsync::OnceCell;
653 /// let cell: OnceCell<String> = OnceCell::new();
654 /// assert_eq!(cell.into_inner(), None);
656 /// let cell = OnceCell::new();
657 /// cell.set("hello".to_string()).unwrap();
658 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
660 pub fn into_inner(self) -> Option
<T
> {
661 // Because `into_inner` takes `self` by value, the compiler statically verifies
662 // that it is not currently borrowed. So it is safe to move out `Option<T>`.
663 self.inner
.into_inner()
667 /// A value which is initialized on the first access.
671 /// use once_cell::unsync::Lazy;
673 /// let lazy: Lazy<i32> = Lazy::new(|| {
674 /// println!("initializing");
677 /// println!("ready");
678 /// println!("{}", *lazy);
679 /// println!("{}", *lazy);
687 pub struct Lazy
<T
, F
= fn() -> T
> {
689 init
: Cell
<Option
<F
>>,
692 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
694 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
695 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
696 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
700 impl<T
, F
> Lazy
<T
, F
> {
701 /// Creates a new lazy value with the given initializing function.
706 /// use once_cell::unsync::Lazy;
708 /// let hello = "Hello, World!".to_string();
710 /// let lazy = Lazy::new(|| hello.to_uppercase());
712 /// assert_eq!(&*lazy, "HELLO, WORLD!");
715 pub const fn new(init
: F
) -> Lazy
<T
, F
> {
716 Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
719 /// Consumes this `Lazy` returning the stored value.
721 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
722 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
723 let cell
= this
.cell
;
724 let init
= this
.init
;
725 cell
.into_inner().ok_or_else(|| {
726 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
731 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
732 /// Forces the evaluation of this lazy value and returns a reference to
735 /// This is equivalent to the `Deref` impl, but is explicit.
739 /// use once_cell::unsync::Lazy;
741 /// let lazy = Lazy::new(|| 92);
743 /// assert_eq!(Lazy::force(&lazy), &92);
744 /// assert_eq!(&*lazy, &92);
746 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
747 this
.cell
.get_or_init(|| match this
.init
.take() {
749 None
=> panic
!("Lazy instance has previously been poisoned"),
753 /// Forces the evaluation of this lazy value and returns a mutable reference to
756 /// This is equivalent to the `DerefMut` impl, but is explicit.
760 /// use once_cell::unsync::Lazy;
762 /// let mut lazy = Lazy::new(|| 92);
764 /// assert_eq!(Lazy::force_mut(&mut lazy), &92);
765 /// assert_eq!(*lazy, 92);
767 pub fn force_mut(this
: &mut Lazy
<T
, F
>) -> &mut T
{
769 Self::get_mut(this
).unwrap_or_else(|| unreachable
!())
772 /// Gets the reference to the result of this lazy value if
773 /// it was initialized, otherwise returns `None`.
777 /// use once_cell::unsync::Lazy;
779 /// let lazy = Lazy::new(|| 92);
781 /// assert_eq!(Lazy::get(&lazy), None);
782 /// assert_eq!(&*lazy, &92);
783 /// assert_eq!(Lazy::get(&lazy), Some(&92));
785 pub fn get(this
: &Lazy
<T
, F
>) -> Option
<&T
> {
789 /// Gets the mutable reference to the result of this lazy value if
790 /// it was initialized, otherwise returns `None`.
794 /// use once_cell::unsync::Lazy;
796 /// let mut lazy = Lazy::new(|| 92);
798 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
799 /// assert_eq!(*lazy, 92);
800 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
802 pub fn get_mut(this
: &mut Lazy
<T
, F
>) -> Option
<&mut T
> {
807 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
809 fn deref(&self) -> &T
{
814 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
815 fn deref_mut(&mut self) -> &mut T
{
817 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
821 impl<T
: Default
> Default
for Lazy
<T
> {
822 /// Creates a new lazy value using `Default` as the initializing function.
823 fn default() -> Lazy
<T
> {
824 Lazy
::new(T
::default)
829 /// Thread-safe, blocking version of `OnceCell`.
830 #[cfg(any(feature = "std", feature = "critical-section"))]
835 ops
::{Deref, DerefMut}
,
836 panic
::RefUnwindSafe
,
839 use super::{imp::OnceCell as Imp, unwrap_unchecked}
;
841 /// A thread-safe cell which can be written to only once.
843 /// `OnceCell` provides `&` references to the contents without RAII guards.
845 /// Reading a non-`None` value out of `OnceCell` establishes a
846 /// happens-before relationship with a corresponding write. For example, if
847 /// thread A initializes the cell with `get_or_init(f)`, and thread B
848 /// subsequently reads the result of this call, B also observes all the side
853 /// use once_cell::sync::OnceCell;
855 /// static CELL: OnceCell<String> = OnceCell::new();
856 /// assert!(CELL.get().is_none());
858 /// std::thread::spawn(|| {
859 /// let value: &String = CELL.get_or_init(|| {
860 /// "Hello, World!".to_string()
862 /// assert_eq!(value, "Hello, World!");
863 /// }).join().unwrap();
865 /// let value: Option<&String> = CELL.get();
866 /// assert!(value.is_some());
867 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
869 pub struct OnceCell
<T
>(Imp
<T
>);
871 impl<T
> Default
for OnceCell
<T
> {
872 fn default() -> OnceCell
<T
> {
877 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
878 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
880 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
881 None
=> f
.write_str("OnceCell(Uninit)"),
886 impl<T
: Clone
> Clone
for OnceCell
<T
> {
887 fn clone(&self) -> OnceCell
<T
> {
889 Some(value
) => Self::with_value(value
.clone()),
894 fn clone_from(&mut self, source
: &Self) {
895 match (self.get_mut(), source
.get()) {
896 (Some(this
), Some(source
)) => this
.clone_from(source
),
897 _
=> *self = source
.clone(),
902 impl<T
> From
<T
> for OnceCell
<T
> {
903 fn from(value
: T
) -> Self {
904 Self::with_value(value
)
908 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
909 fn eq(&self, other
: &OnceCell
<T
>) -> bool
{
910 self.get() == other
.get()
914 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
916 impl<T
> OnceCell
<T
> {
917 /// Creates a new empty cell.
918 pub const fn new() -> OnceCell
<T
> {
922 /// Creates a new initialized cell.
923 pub const fn with_value(value
: T
) -> OnceCell
<T
> {
924 OnceCell(Imp
::with_value(value
))
927 /// Gets the reference to the underlying value.
929 /// Returns `None` if the cell is empty, or being initialized. This
930 /// method never blocks.
931 pub fn get(&self) -> Option
<&T
> {
932 if self.0.is_initialized
() {
933 // Safe b/c value is initialized.
934 Some(unsafe { self.get_unchecked() }
)
940 /// Gets the reference to the underlying value, blocking the current
941 /// thread until it is set.
944 /// use once_cell::sync::OnceCell;
946 /// let mut cell = std::sync::Arc::new(OnceCell::new());
947 /// let t = std::thread::spawn({
948 /// let cell = std::sync::Arc::clone(&cell);
949 /// move || cell.set(92).unwrap()
952 /// // Returns immediately, but might return None.
953 /// let _value_or_none = cell.get();
955 /// // Will return 92, but might block until the other thread does `.set`.
956 /// let value: &u32 = cell.wait();
957 /// assert_eq!(*value, 92);
958 /// t.join().unwrap();
960 #[cfg(feature = "std")]
961 pub fn wait(&self) -> &T
{
962 if !self.0.is_initialized
() {
965 debug_assert
!(self.0.is_initialized
());
966 // Safe b/c of the wait call above and the fact that we didn't
967 // relinquish our borrow.
968 unsafe { self.get_unchecked() }
971 /// Gets the mutable reference to the underlying value.
973 /// Returns `None` if the cell is empty.
975 /// This method is allowed to violate the invariant of writing to a `OnceCell`
976 /// at most once because it requires `&mut` access to `self`. As with all
977 /// interior mutability, `&mut` access permits arbitrary modification:
980 /// use once_cell::sync::OnceCell;
982 /// let mut cell: OnceCell<u32> = OnceCell::new();
983 /// cell.set(92).unwrap();
984 /// cell = OnceCell::new();
987 pub fn get_mut(&mut self) -> Option
<&mut T
> {
991 /// Get the reference to the underlying value, without checking if the
992 /// cell is initialized.
996 /// Caller must ensure that the cell is in initialized state, and that
997 /// the contents are acquired by (synchronized to) this thread.
999 pub unsafe fn get_unchecked(&self) -> &T
{
1000 self.0.get_unchecked()
1003 /// Sets the contents of this cell to `value`.
1005 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
1011 /// use once_cell::sync::OnceCell;
1013 /// static CELL: OnceCell<i32> = OnceCell::new();
1016 /// assert!(CELL.get().is_none());
1018 /// std::thread::spawn(|| {
1019 /// assert_eq!(CELL.set(92), Ok(()));
1020 /// }).join().unwrap();
1022 /// assert_eq!(CELL.set(62), Err(62));
1023 /// assert_eq!(CELL.get(), Some(&92));
1026 pub fn set(&self, value
: T
) -> Result
<(), T
> {
1027 match self.try_insert(value
) {
1029 Err((_
, value
)) => Err(value
),
1033 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
1038 /// use once_cell::unsync::OnceCell;
1040 /// let cell = OnceCell::new();
1041 /// assert!(cell.get().is_none());
1043 /// assert_eq!(cell.try_insert(92), Ok(&92));
1044 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
1046 /// assert!(cell.get().is_some());
1048 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
1049 let mut value
= Some(value
);
1050 let res
= self.get_or_init(|| unsafe { unwrap_unchecked(value.take()) }
);
1053 Some(value
) => Err((res
, value
)),
1057 /// Gets the contents of the cell, initializing it with `f` if the cell
1060 /// Many threads may call `get_or_init` concurrently with different
1061 /// initializing functions, but it is guaranteed that only one function
1062 /// will be executed.
1066 /// If `f` panics, the panic is propagated to the caller, and the cell
1067 /// remains uninitialized.
1069 /// It is an error to reentrantly initialize the cell from `f`. The
1070 /// exact outcome is unspecified. Current implementation deadlocks, but
1071 /// this may be changed to a panic in the future.
1075 /// use once_cell::sync::OnceCell;
1077 /// let cell = OnceCell::new();
1078 /// let value = cell.get_or_init(|| 92);
1079 /// assert_eq!(value, &92);
1080 /// let value = cell.get_or_init(|| unreachable!());
1081 /// assert_eq!(value, &92);
1083 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
1088 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
1090 Err(void
) => match void {}
,
1094 /// Gets the contents of the cell, initializing it with `f` if
1095 /// the cell was empty. If the cell was empty and `f` failed, an
1096 /// error is returned.
1100 /// If `f` panics, the panic is propagated to the caller, and
1101 /// the cell remains uninitialized.
1103 /// It is an error to reentrantly initialize the cell from `f`.
1104 /// The exact outcome is unspecified. Current implementation
1105 /// deadlocks, but this may be changed to a panic in the future.
1109 /// use once_cell::sync::OnceCell;
1111 /// let cell = OnceCell::new();
1112 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
1113 /// assert!(cell.get().is_none());
1114 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
1117 /// assert_eq!(value, Ok(&92));
1118 /// assert_eq!(cell.get(), Some(&92))
1120 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
1122 F
: FnOnce() -> Result
<T
, E
>,
1125 if let Some(value
) = self.get() {
1129 self.0.initialize
(f
)?
;
1131 // Safe b/c value is initialized.
1132 debug_assert
!(self.0.is_initialized
());
1133 Ok(unsafe { self.get_unchecked() }
)
1136 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
1138 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
1143 /// use once_cell::sync::OnceCell;
1145 /// let mut cell: OnceCell<String> = OnceCell::new();
1146 /// assert_eq!(cell.take(), None);
1148 /// let mut cell = OnceCell::new();
1149 /// cell.set("hello".to_string()).unwrap();
1150 /// assert_eq!(cell.take(), Some("hello".to_string()));
1151 /// assert_eq!(cell.get(), None);
1154 /// This method is allowed to violate the invariant of writing to a `OnceCell`
1155 /// at most once because it requires `&mut` access to `self`. As with all
1156 /// interior mutability, `&mut` access permits arbitrary modification:
1159 /// use once_cell::sync::OnceCell;
1161 /// let mut cell: OnceCell<u32> = OnceCell::new();
1162 /// cell.set(92).unwrap();
1163 /// cell = OnceCell::new();
1165 pub fn take(&mut self) -> Option
<T
> {
1166 mem
::replace(self, Self::default()).into_inner()
1169 /// Consumes the `OnceCell`, returning the wrapped value. Returns
1170 /// `None` if the cell was empty.
1175 /// use once_cell::sync::OnceCell;
1177 /// let cell: OnceCell<String> = OnceCell::new();
1178 /// assert_eq!(cell.into_inner(), None);
1180 /// let cell = OnceCell::new();
1181 /// cell.set("hello".to_string()).unwrap();
1182 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
1185 pub fn into_inner(self) -> Option
<T
> {
1190 /// A value which is initialized on the first access.
1192 /// This type is thread-safe and can be used in statics.
1197 /// use std::collections::HashMap;
1199 /// use once_cell::sync::Lazy;
1201 /// static HASHMAP: Lazy<HashMap<i32, String>> = Lazy::new(|| {
1202 /// println!("initializing");
1203 /// let mut m = HashMap::new();
1204 /// m.insert(13, "Spica".to_string());
1205 /// m.insert(74, "Hoyten".to_string());
1210 /// println!("ready");
1211 /// std::thread::spawn(|| {
1212 /// println!("{:?}", HASHMAP.get(&13));
1213 /// }).join().unwrap();
1214 /// println!("{:?}", HASHMAP.get(&74));
1219 /// // Some("Spica")
1220 /// // Some("Hoyten")
1223 pub struct Lazy
<T
, F
= fn() -> T
> {
1225 init
: Cell
<Option
<F
>>,
1228 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
1229 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1230 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
1234 // We never create a `&F` from a `&Lazy<T, F>` so it is fine to not impl
1235 // `Sync` for `F`. We do create a `&mut Option<F>` in `force`, but this is
1236 // properly synchronized, so it only happens once so it also does not
1237 // contribute to this impl.
1238 unsafe impl<T
, F
: Send
> Sync
for Lazy
<T
, F
> where OnceCell
<T
>: Sync {}
1239 // auto-derived `Send` impl is OK.
1241 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
1243 impl<T
, F
> Lazy
<T
, F
> {
1244 /// Creates a new lazy value with the given initializing
1246 pub const fn new(f
: F
) -> Lazy
<T
, F
> {
1247 Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1250 /// Consumes this `Lazy` returning the stored value.
1252 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
1253 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
1254 let cell
= this
.cell
;
1255 let init
= this
.init
;
1256 cell
.into_inner().ok_or_else(|| {
1257 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
1262 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
1263 /// Forces the evaluation of this lazy value and
1264 /// returns a reference to the result. This is equivalent
1265 /// to the `Deref` impl, but is explicit.
1269 /// use once_cell::sync::Lazy;
1271 /// let lazy = Lazy::new(|| 92);
1273 /// assert_eq!(Lazy::force(&lazy), &92);
1274 /// assert_eq!(&*lazy, &92);
1276 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
1277 this
.cell
.get_or_init(|| match this
.init
.take() {
1279 None
=> panic
!("Lazy instance has previously been poisoned"),
1283 /// Forces the evaluation of this lazy value and
1284 /// returns a mutable reference to the result. This is equivalent
1285 /// to the `Deref` impl, but is explicit.
1289 /// use once_cell::sync::Lazy;
1291 /// let mut lazy = Lazy::new(|| 92);
1293 /// assert_eq!(Lazy::force_mut(&mut lazy), &mut 92);
1295 pub fn force_mut(this
: &mut Lazy
<T
, F
>) -> &mut T
{
1297 Self::get_mut(this
).unwrap_or_else(|| unreachable
!())
1300 /// Gets the reference to the result of this lazy value if
1301 /// it was initialized, otherwise returns `None`.
1305 /// use once_cell::sync::Lazy;
1307 /// let lazy = Lazy::new(|| 92);
1309 /// assert_eq!(Lazy::get(&lazy), None);
1310 /// assert_eq!(&*lazy, &92);
1311 /// assert_eq!(Lazy::get(&lazy), Some(&92));
1313 pub fn get(this
: &Lazy
<T
, F
>) -> Option
<&T
> {
1317 /// Gets the reference to the result of this lazy value if
1318 /// it was initialized, otherwise returns `None`.
1322 /// use once_cell::sync::Lazy;
1324 /// let mut lazy = Lazy::new(|| 92);
1326 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
1327 /// assert_eq!(&*lazy, &92);
1328 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
1330 pub fn get_mut(this
: &mut Lazy
<T
, F
>) -> Option
<&mut T
> {
1335 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
1337 fn deref(&self) -> &T
{
1342 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
1343 fn deref_mut(&mut self) -> &mut T
{
1345 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
1349 impl<T
: Default
> Default
for Lazy
<T
> {
1350 /// Creates a new lazy value using `Default` as the initializing function.
1351 fn default() -> Lazy
<T
> {
1352 Lazy
::new(T
::default)
1357 /// struct S(*mut ());
1358 /// unsafe impl Sync for S {}
1360 /// fn share<T: Sync>(_: &T) {}
1361 /// share(&once_cell::sync::OnceCell::<S>::new());
1365 /// struct S(*mut ());
1366 /// unsafe impl Sync for S {}
1368 /// fn share<T: Sync>(_: &T) {}
1369 /// share(&once_cell::sync::Lazy::<S>::new(|| unimplemented!()));
1374 #[cfg(feature = "race")]
1377 // Remove once MSRV is at least 1.58.
1379 unsafe fn unwrap_unchecked
<T
>(val
: Option
<T
>) -> T
{
1381 Some(value
) => value
,
1383 debug_assert
!(false);
1384 core
::hint
::unreachable_unchecked()