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;
212 //! pub struct LateInit<T> { cell: OnceCell<T> }
214 //! impl<T> LateInit<T> {
215 //! pub fn init(&self, value: T) {
216 //! assert!(self.cell.set(value).is_ok())
220 //! impl<T> Default for LateInit<T> {
221 //! fn default() -> Self { LateInit { cell: OnceCell::default() } }
224 //! impl<T> std::ops::Deref for LateInit<T> {
226 //! fn deref(&self) -> &T {
227 //! self.cell.get().unwrap()
231 //! #[derive(Default, Debug)]
233 //! b: LateInit<&'a B<'a>>,
236 //! #[derive(Default, Debug)]
238 //! a: LateInit<&'a A<'a>>
241 //! fn build_cycle() {
242 //! let a = A::default();
243 //! let b = B::default();
246 //! println!("{:?}", a.b.a.b.a);
250 //! # Comparison with std
252 //! |`!Sync` types | Access Mode | Drawbacks |
253 //! |----------------------|------------------------|-----------------------------------------------|
254 //! |`Cell<T>` | `T` | requires `T: Copy` for `get` |
255 //! |`RefCell<T>` | `RefMut<T>` / `Ref<T>` | may panic at runtime |
256 //! |`unsync::OnceCell<T>` | `&T` | assignable only once |
258 //! |`Sync` types | Access Mode | Drawbacks |
259 //! |----------------------|------------------------|-----------------------------------------------|
260 //! |`AtomicT` | `T` | works only with certain `Copy` types |
261 //! |`Mutex<T>` | `MutexGuard<T>` | may deadlock at runtime, may block the thread |
262 //! |`sync::OnceCell<T>` | `&T` | assignable only once, may block the thread |
264 //! Technically, calling `get_or_init` will also cause a panic or a deadlock if it recursively calls
265 //! itself. However, because the assignment can happen only once, such cases should be more rare than
266 //! equivalents with `RefCell` and `Mutex`.
268 //! # Minimum Supported `rustc` Version
270 //! This crate's minimum supported `rustc` version is `1.56.0`.
272 //! If only the `std` feature is enabled, MSRV will be updated conservatively.
273 //! When using other features, like `parking_lot`, MSRV might be updated more frequently, up to the latest stable.
274 //! In both cases, increasing MSRV is *not* considered a semver-breaking change.
276 //! # Implementation details
278 //! The implementation is based on the [`lazy_static`](https://github.com/rust-lang-nursery/lazy-static.rs/)
279 //! and [`lazy_cell`](https://github.com/indiv0/lazycell/) crates and [`std::sync::Once`]. In some sense,
280 //! `once_cell` just streamlines and unifies those APIs.
282 //! To implement a sync flavor of `OnceCell`, this crates uses either a custom
283 //! re-implementation of `std::sync::Once` or `parking_lot::Mutex`. This is
284 //! controlled by the `parking_lot` feature (disabled by default). Performance
285 //! is the same for both cases, but the `parking_lot` based `OnceCell<T>` is
286 //! smaller by up to 16 bytes.
288 //! This crate uses `unsafe`.
290 //! [`std::sync::Once`]: https://doc.rust-lang.org/std/sync/struct.Once.html
294 //! **Should I use lazy_static or once_cell?**
296 //! To the first approximation, `once_cell` is both more flexible and more convenient than `lazy_static`
297 //! and should be preferred.
299 //! Unlike `once_cell`, `lazy_static` supports spinlock-based implementation of blocking which works with
302 //! `lazy_static` has received significantly more real world testing, but `once_cell` is also a widely
305 //! **Should I use the sync or unsync flavor?**
307 //! Because Rust compiler checks thread safety for you, it's impossible to accidentally use `unsync` where
308 //! `sync` is required. So, use `unsync` in single-threaded code and `sync` in multi-threaded. It's easy
309 //! to switch between the two if code becomes multi-threaded later.
311 //! At the moment, `unsync` has an additional benefit that reentrant initialization causes a panic, which
312 //! might be easier to debug than a deadlock.
314 //! **Does this crate support async?**
316 //! No, but you can use [`async_once_cell`](https://crates.io/crates/async_once_cell) instead.
320 //! * [double-checked-cell](https://github.com/niklasf/double-checked-cell)
321 //! * [lazy-init](https://crates.io/crates/lazy-init)
322 //! * [lazycell](https://crates.io/crates/lazycell)
323 //! * [mitochondria](https://crates.io/crates/mitochondria)
324 //! * [lazy_static](https://crates.io/crates/lazy_static)
325 //! * [async_once_cell](https://crates.io/crates/async_once_cell)
327 //! Most of this crate's functionality is available in `std` in nightly Rust.
328 //! See the [tracking issue](https://github.com/rust-lang/rust/issues/74465).
330 #![cfg_attr(not(feature = "std"), no_std)]
332 #[cfg(feature = "alloc")]
335 #[cfg(feature = "std")]
336 #[cfg(feature = "parking_lot")]
337 #[path = "imp_pl.rs"]
340 #[cfg(feature = "std")]
341 #[cfg(not(feature = "parking_lot"))]
342 #[path = "imp_std.rs"]
345 /// Single-threaded version of `OnceCell`.
348 cell
::{Cell, UnsafeCell}
,
350 ops
::{Deref, DerefMut}
,
351 panic
::{RefUnwindSafe, UnwindSafe}
,
354 /// A cell which can be written to only once. It is not thread safe.
356 /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&`
357 /// references to the contents.
359 /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
363 /// use once_cell::unsync::OnceCell;
365 /// let cell = OnceCell::new();
366 /// assert!(cell.get().is_none());
368 /// let value: &String = cell.get_or_init(|| {
369 /// "Hello, World!".to_string()
371 /// assert_eq!(value, "Hello, World!");
372 /// assert!(cell.get().is_some());
374 pub struct OnceCell
<T
> {
375 // Invariant: written to at most once.
376 inner
: UnsafeCell
<Option
<T
>>,
379 // Similarly to a `Sync` bound on `sync::OnceCell`, we can use
380 // `&unsync::OnceCell` to sneak a `T` through `catch_unwind`,
381 // by initializing the cell in closure and extracting the value in the
383 impl<T
: RefUnwindSafe
+ UnwindSafe
> RefUnwindSafe
for OnceCell
<T
> {}
384 impl<T
: UnwindSafe
> UnwindSafe
for OnceCell
<T
> {}
386 impl<T
> Default
for OnceCell
<T
> {
387 fn default() -> Self {
392 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
393 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
395 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
396 None
=> f
.write_str("OnceCell(Uninit)"),
401 impl<T
: Clone
> Clone
for OnceCell
<T
> {
402 fn clone(&self) -> OnceCell
<T
> {
404 Some(value
) => OnceCell
::with_value(value
.clone()),
405 None
=> OnceCell
::new(),
409 fn clone_from(&mut self, source
: &Self) {
410 match (self.get_mut(), source
.get()) {
411 (Some(this
), Some(source
)) => this
.clone_from(source
),
412 _
=> *self = source
.clone(),
417 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
418 fn eq(&self, other
: &Self) -> bool
{
419 self.get() == other
.get()
423 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
425 impl<T
> From
<T
> for OnceCell
<T
> {
426 fn from(value
: T
) -> Self {
427 OnceCell
::with_value(value
)
431 impl<T
> OnceCell
<T
> {
432 /// Creates a new empty cell.
433 pub const fn new() -> OnceCell
<T
> {
434 OnceCell { inner: UnsafeCell::new(None) }
437 /// Creates a new initialized cell.
438 pub const fn with_value(value
: T
) -> OnceCell
<T
> {
439 OnceCell { inner: UnsafeCell::new(Some(value)) }
442 /// Gets a reference to the underlying value.
444 /// Returns `None` if the cell is empty.
445 pub fn get(&self) -> Option
<&T
> {
446 // Safe due to `inner`'s invariant
447 unsafe { &*self.inner.get() }
.as_ref()
450 /// Gets a mutable reference to the underlying value.
452 /// Returns `None` if the cell is empty.
454 /// This method is allowed to violate the invariant of writing to a `OnceCell`
455 /// at most once because it requires `&mut` access to `self`. As with all
456 /// interior mutability, `&mut` access permits arbitrary modification:
459 /// use once_cell::unsync::OnceCell;
461 /// let mut cell: OnceCell<u32> = OnceCell::new();
462 /// cell.set(92).unwrap();
463 /// *cell.get_mut().unwrap() = 93;
464 /// assert_eq!(cell.get(), Some(&93));
466 pub fn get_mut(&mut self) -> Option
<&mut T
> {
467 // Safe because we have unique access
468 unsafe { &mut *self.inner.get() }
.as_mut()
471 /// Sets the contents of this cell to `value`.
473 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
478 /// use once_cell::unsync::OnceCell;
480 /// let cell = OnceCell::new();
481 /// assert!(cell.get().is_none());
483 /// assert_eq!(cell.set(92), Ok(()));
484 /// assert_eq!(cell.set(62), Err(62));
486 /// assert!(cell.get().is_some());
488 pub fn set(&self, value
: T
) -> Result
<(), T
> {
489 match self.try_insert(value
) {
491 Err((_
, value
)) => Err(value
),
495 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
499 /// use once_cell::unsync::OnceCell;
501 /// let cell = OnceCell::new();
502 /// assert!(cell.get().is_none());
504 /// assert_eq!(cell.try_insert(92), Ok(&92));
505 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
507 /// assert!(cell.get().is_some());
509 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
510 if let Some(old
) = self.get() {
511 return Err((old
, value
));
513 let slot
= unsafe { &mut *self.inner.get() }
;
514 // This is the only place where we set the slot, no races
515 // due to reentrancy/concurrency are possible, and we've
516 // checked that slot is currently `None`, so this write
517 // maintains the `inner`'s invariant.
520 Some(value
) => value
,
521 None
=> unsafe { hint::unreachable_unchecked() }
,
525 /// Gets the contents of the cell, initializing it with `f`
526 /// if the cell was empty.
530 /// If `f` panics, the panic is propagated to the caller, and the cell
531 /// remains uninitialized.
533 /// It is an error to reentrantly initialize the cell from `f`. Doing
534 /// so results in a panic.
538 /// use once_cell::unsync::OnceCell;
540 /// let cell = OnceCell::new();
541 /// let value = cell.get_or_init(|| 92);
542 /// assert_eq!(value, &92);
543 /// let value = cell.get_or_init(|| unreachable!());
544 /// assert_eq!(value, &92);
546 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
551 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
553 Err(void
) => match void {}
,
557 /// Gets the contents of the cell, initializing it with `f` if
558 /// the cell was empty. If the cell was empty and `f` failed, an
559 /// error is returned.
563 /// If `f` panics, the panic is propagated to the caller, and the cell
564 /// remains uninitialized.
566 /// It is an error to reentrantly initialize the cell from `f`. Doing
567 /// so results in a panic.
571 /// use once_cell::unsync::OnceCell;
573 /// let cell = OnceCell::new();
574 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
575 /// assert!(cell.get().is_none());
576 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
579 /// assert_eq!(value, Ok(&92));
580 /// assert_eq!(cell.get(), Some(&92))
582 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
584 F
: FnOnce() -> Result
<T
, E
>,
586 if let Some(val
) = self.get() {
590 // Note that *some* forms of reentrant initialization might lead to
591 // UB (see `reentrant_init` test). I believe that just removing this
592 // `assert`, while keeping `set/get` would be sound, but it seems
593 // better to panic, rather than to silently use an old value.
594 assert
!(self.set(val
).is_ok(), "reentrant init");
595 Ok(self.get().unwrap())
598 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
600 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
605 /// use once_cell::unsync::OnceCell;
607 /// let mut cell: OnceCell<String> = OnceCell::new();
608 /// assert_eq!(cell.take(), None);
610 /// let mut cell = OnceCell::new();
611 /// cell.set("hello".to_string()).unwrap();
612 /// assert_eq!(cell.take(), Some("hello".to_string()));
613 /// assert_eq!(cell.get(), None);
616 /// This method is allowed to violate the invariant of writing to a `OnceCell`
617 /// at most once because it requires `&mut` access to `self`. As with all
618 /// interior mutability, `&mut` access permits arbitrary modification:
621 /// use once_cell::unsync::OnceCell;
623 /// let mut cell: OnceCell<u32> = OnceCell::new();
624 /// cell.set(92).unwrap();
625 /// cell = OnceCell::new();
627 pub fn take(&mut self) -> Option
<T
> {
628 mem
::replace(self, Self::default()).into_inner()
631 /// Consumes the `OnceCell`, returning the wrapped value.
633 /// Returns `None` if the cell was empty.
638 /// use once_cell::unsync::OnceCell;
640 /// let cell: OnceCell<String> = OnceCell::new();
641 /// assert_eq!(cell.into_inner(), None);
643 /// let cell = OnceCell::new();
644 /// cell.set("hello".to_string()).unwrap();
645 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
647 pub fn into_inner(self) -> Option
<T
> {
648 // Because `into_inner` takes `self` by value, the compiler statically verifies
649 // that it is not currently borrowed. So it is safe to move out `Option<T>`.
650 self.inner
.into_inner()
654 /// A value which is initialized on the first access.
658 /// use once_cell::unsync::Lazy;
660 /// let lazy: Lazy<i32> = Lazy::new(|| {
661 /// println!("initializing");
664 /// println!("ready");
665 /// println!("{}", *lazy);
666 /// println!("{}", *lazy);
674 pub struct Lazy
<T
, F
= fn() -> T
> {
676 init
: Cell
<Option
<F
>>,
679 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
681 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
682 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
683 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
687 impl<T
, F
> Lazy
<T
, F
> {
688 /// Creates a new lazy value with the given initializing function.
693 /// use once_cell::unsync::Lazy;
695 /// let hello = "Hello, World!".to_string();
697 /// let lazy = Lazy::new(|| hello.to_uppercase());
699 /// assert_eq!(&*lazy, "HELLO, WORLD!");
702 pub const fn new(init
: F
) -> Lazy
<T
, F
> {
703 Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
706 /// Consumes this `Lazy` returning the stored value.
708 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
709 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
710 let cell
= this
.cell
;
711 let init
= this
.init
;
712 cell
.into_inner().ok_or_else(|| {
713 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
718 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
719 /// Forces the evaluation of this lazy value and returns a reference to
722 /// This is equivalent to the `Deref` impl, but is explicit.
726 /// use once_cell::unsync::Lazy;
728 /// let lazy = Lazy::new(|| 92);
730 /// assert_eq!(Lazy::force(&lazy), &92);
731 /// assert_eq!(&*lazy, &92);
733 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
734 this
.cell
.get_or_init(|| match this
.init
.take() {
736 None
=> panic
!("Lazy instance has previously been poisoned"),
740 /// Forces the evaluation of this lazy value and returns a mutable reference to
743 /// This is equivalent to the `DerefMut` impl, but is explicit.
747 /// use once_cell::unsync::Lazy;
749 /// let mut lazy = Lazy::new(|| 92);
751 /// assert_eq!(Lazy::force_mut(&mut lazy), &92);
752 /// assert_eq!(*lazy, 92);
754 pub fn force_mut(this
: &mut Lazy
<T
, F
>) -> &mut T
{
756 Self::get_mut(this
).unwrap_or_else(|| unreachable
!())
759 /// Gets the reference to the result of this lazy value if
760 /// it was initialized, otherwise returns `None`.
764 /// use once_cell::unsync::Lazy;
766 /// let lazy = Lazy::new(|| 92);
768 /// assert_eq!(Lazy::get(&lazy), None);
769 /// assert_eq!(&*lazy, &92);
770 /// assert_eq!(Lazy::get(&lazy), Some(&92));
772 pub fn get(this
: &Lazy
<T
, F
>) -> Option
<&T
> {
776 /// Gets the mutable reference to the result of this lazy value if
777 /// it was initialized, otherwise returns `None`.
781 /// use once_cell::unsync::Lazy;
783 /// let mut lazy = Lazy::new(|| 92);
785 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
786 /// assert_eq!(*lazy, 92);
787 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
789 pub fn get_mut(this
: &mut Lazy
<T
, F
>) -> Option
<&mut T
> {
794 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
796 fn deref(&self) -> &T
{
801 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
802 fn deref_mut(&mut self) -> &mut T
{
804 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
808 impl<T
: Default
> Default
for Lazy
<T
> {
809 /// Creates a new lazy value using `Default` as the initializing function.
810 fn default() -> Lazy
<T
> {
811 Lazy
::new(T
::default)
816 /// Thread-safe, blocking version of `OnceCell`.
817 #[cfg(feature = "std")]
822 ops
::{Deref, DerefMut}
,
823 panic
::RefUnwindSafe
,
826 use crate::{imp::OnceCell as Imp, take_unchecked}
;
828 /// A thread-safe cell which can be written to only once.
830 /// `OnceCell` provides `&` references to the contents without RAII guards.
832 /// Reading a non-`None` value out of `OnceCell` establishes a
833 /// happens-before relationship with a corresponding write. For example, if
834 /// thread A initializes the cell with `get_or_init(f)`, and thread B
835 /// subsequently reads the result of this call, B also observes all the side
840 /// use once_cell::sync::OnceCell;
842 /// static CELL: OnceCell<String> = OnceCell::new();
843 /// assert!(CELL.get().is_none());
845 /// std::thread::spawn(|| {
846 /// let value: &String = CELL.get_or_init(|| {
847 /// "Hello, World!".to_string()
849 /// assert_eq!(value, "Hello, World!");
850 /// }).join().unwrap();
852 /// let value: Option<&String> = CELL.get();
853 /// assert!(value.is_some());
854 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
856 pub struct OnceCell
<T
>(Imp
<T
>);
858 impl<T
> Default
for OnceCell
<T
> {
859 fn default() -> OnceCell
<T
> {
864 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
865 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
867 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
868 None
=> f
.write_str("OnceCell(Uninit)"),
873 impl<T
: Clone
> Clone
for OnceCell
<T
> {
874 fn clone(&self) -> OnceCell
<T
> {
876 Some(value
) => Self::with_value(value
.clone()),
881 fn clone_from(&mut self, source
: &Self) {
882 match (self.get_mut(), source
.get()) {
883 (Some(this
), Some(source
)) => this
.clone_from(source
),
884 _
=> *self = source
.clone(),
889 impl<T
> From
<T
> for OnceCell
<T
> {
890 fn from(value
: T
) -> Self {
891 Self::with_value(value
)
895 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
896 fn eq(&self, other
: &OnceCell
<T
>) -> bool
{
897 self.get() == other
.get()
901 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
903 impl<T
> OnceCell
<T
> {
904 /// Creates a new empty cell.
905 pub const fn new() -> OnceCell
<T
> {
909 /// Creates a new initialized cell.
910 pub const fn with_value(value
: T
) -> OnceCell
<T
> {
911 OnceCell(Imp
::with_value(value
))
914 /// Gets the reference to the underlying value.
916 /// Returns `None` if the cell is empty, or being initialized. This
917 /// method never blocks.
918 pub fn get(&self) -> Option
<&T
> {
919 if self.0.is_initialized
() {
920 // Safe b/c value is initialized.
921 Some(unsafe { self.get_unchecked() }
)
927 /// Gets the reference to the underlying value, blocking the current
928 /// thread until it is set.
931 /// use once_cell::sync::OnceCell;
933 /// let mut cell = std::sync::Arc::new(OnceCell::new());
934 /// let t = std::thread::spawn({
935 /// let cell = std::sync::Arc::clone(&cell);
936 /// move || cell.set(92).unwrap()
939 /// // Returns immediately, but might return None.
940 /// let _value_or_none = cell.get();
942 /// // Will return 92, but might block until the other thread does `.set`.
943 /// let value: &u32 = cell.wait();
944 /// assert_eq!(*value, 92);
945 /// t.join().unwrap();;
947 pub fn wait(&self) -> &T
{
948 if !self.0.is_initialized
() {
951 debug_assert
!(self.0.is_initialized
());
952 // Safe b/c of the wait call above and the fact that we didn't
953 // relinquish our borrow.
954 unsafe { self.get_unchecked() }
957 /// Gets the mutable reference to the underlying value.
959 /// Returns `None` if the cell is empty.
961 /// This method is allowed to violate the invariant of writing to a `OnceCell`
962 /// at most once because it requires `&mut` access to `self`. As with all
963 /// interior mutability, `&mut` access permits arbitrary modification:
966 /// use once_cell::sync::OnceCell;
968 /// let mut cell: OnceCell<u32> = OnceCell::new();
969 /// cell.set(92).unwrap();
970 /// cell = OnceCell::new();
972 pub fn get_mut(&mut self) -> Option
<&mut T
> {
976 /// Get the reference to the underlying value, without checking if the
977 /// cell is initialized.
981 /// Caller must ensure that the cell is in initialized state, and that
982 /// the contents are acquired by (synchronized to) this thread.
983 pub unsafe fn get_unchecked(&self) -> &T
{
984 self.0.get_unchecked()
987 /// Sets the contents of this cell to `value`.
989 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
995 /// use once_cell::sync::OnceCell;
997 /// static CELL: OnceCell<i32> = OnceCell::new();
1000 /// assert!(CELL.get().is_none());
1002 /// std::thread::spawn(|| {
1003 /// assert_eq!(CELL.set(92), Ok(()));
1004 /// }).join().unwrap();
1006 /// assert_eq!(CELL.set(62), Err(62));
1007 /// assert_eq!(CELL.get(), Some(&92));
1010 pub fn set(&self, value
: T
) -> Result
<(), T
> {
1011 match self.try_insert(value
) {
1013 Err((_
, value
)) => Err(value
),
1017 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
1022 /// use once_cell::unsync::OnceCell;
1024 /// let cell = OnceCell::new();
1025 /// assert!(cell.get().is_none());
1027 /// assert_eq!(cell.try_insert(92), Ok(&92));
1028 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
1030 /// assert!(cell.get().is_some());
1032 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
1033 let mut value
= Some(value
);
1034 let res
= self.get_or_init(|| unsafe { take_unchecked(&mut value) }
);
1037 Some(value
) => Err((res
, value
)),
1041 /// Gets the contents of the cell, initializing it with `f` if the cell
1044 /// Many threads may call `get_or_init` concurrently with different
1045 /// initializing functions, but it is guaranteed that only one function
1046 /// will be executed.
1050 /// If `f` panics, the panic is propagated to the caller, and the cell
1051 /// remains uninitialized.
1053 /// It is an error to reentrantly initialize the cell from `f`. The
1054 /// exact outcome is unspecified. Current implementation deadlocks, but
1055 /// this may be changed to a panic in the future.
1059 /// use once_cell::sync::OnceCell;
1061 /// let cell = OnceCell::new();
1062 /// let value = cell.get_or_init(|| 92);
1063 /// assert_eq!(value, &92);
1064 /// let value = cell.get_or_init(|| unreachable!());
1065 /// assert_eq!(value, &92);
1067 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
1072 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
1074 Err(void
) => match void {}
,
1078 /// Gets the contents of the cell, initializing it with `f` if
1079 /// the cell was empty. If the cell was empty and `f` failed, an
1080 /// error is returned.
1084 /// If `f` panics, the panic is propagated to the caller, and
1085 /// the cell remains uninitialized.
1087 /// It is an error to reentrantly initialize the cell from `f`.
1088 /// The exact outcome is unspecified. Current implementation
1089 /// deadlocks, but this may be changed to a panic in the future.
1093 /// use once_cell::sync::OnceCell;
1095 /// let cell = OnceCell::new();
1096 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
1097 /// assert!(cell.get().is_none());
1098 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
1101 /// assert_eq!(value, Ok(&92));
1102 /// assert_eq!(cell.get(), Some(&92))
1104 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
1106 F
: FnOnce() -> Result
<T
, E
>,
1109 if let Some(value
) = self.get() {
1112 self.0.initialize
(f
)?
;
1114 // Safe b/c value is initialized.
1115 debug_assert
!(self.0.is_initialized
());
1116 Ok(unsafe { self.get_unchecked() }
)
1119 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
1121 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
1126 /// use once_cell::sync::OnceCell;
1128 /// let mut cell: OnceCell<String> = OnceCell::new();
1129 /// assert_eq!(cell.take(), None);
1131 /// let mut cell = OnceCell::new();
1132 /// cell.set("hello".to_string()).unwrap();
1133 /// assert_eq!(cell.take(), Some("hello".to_string()));
1134 /// assert_eq!(cell.get(), None);
1137 /// This method is allowed to violate the invariant of writing to a `OnceCell`
1138 /// at most once because it requires `&mut` access to `self`. As with all
1139 /// interior mutability, `&mut` access permits arbitrary modification:
1142 /// use once_cell::sync::OnceCell;
1144 /// let mut cell: OnceCell<u32> = OnceCell::new();
1145 /// cell.set(92).unwrap();
1146 /// cell = OnceCell::new();
1148 pub fn take(&mut self) -> Option
<T
> {
1149 mem
::replace(self, Self::default()).into_inner()
1152 /// Consumes the `OnceCell`, returning the wrapped value. Returns
1153 /// `None` if the cell was empty.
1158 /// use once_cell::sync::OnceCell;
1160 /// let cell: OnceCell<String> = OnceCell::new();
1161 /// assert_eq!(cell.into_inner(), None);
1163 /// let cell = OnceCell::new();
1164 /// cell.set("hello".to_string()).unwrap();
1165 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
1167 pub fn into_inner(self) -> Option
<T
> {
1172 /// A value which is initialized on the first access.
1174 /// This type is thread-safe and can be used in statics.
1179 /// use std::collections::HashMap;
1181 /// use once_cell::sync::Lazy;
1183 /// static HASHMAP: Lazy<HashMap<i32, String>> = Lazy::new(|| {
1184 /// println!("initializing");
1185 /// let mut m = HashMap::new();
1186 /// m.insert(13, "Spica".to_string());
1187 /// m.insert(74, "Hoyten".to_string());
1192 /// println!("ready");
1193 /// std::thread::spawn(|| {
1194 /// println!("{:?}", HASHMAP.get(&13));
1195 /// }).join().unwrap();
1196 /// println!("{:?}", HASHMAP.get(&74));
1201 /// // Some("Spica")
1202 /// // Some("Hoyten")
1205 pub struct Lazy
<T
, F
= fn() -> T
> {
1207 init
: Cell
<Option
<F
>>,
1210 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
1211 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1212 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
1216 // We never create a `&F` from a `&Lazy<T, F>` so it is fine to not impl
1217 // `Sync` for `F`. We do create a `&mut Option<F>` in `force`, but this is
1218 // properly synchronized, so it only happens once so it also does not
1219 // contribute to this impl.
1220 unsafe impl<T
, F
: Send
> Sync
for Lazy
<T
, F
> where OnceCell
<T
>: Sync {}
1221 // auto-derived `Send` impl is OK.
1223 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
1225 impl<T
, F
> Lazy
<T
, F
> {
1226 /// Creates a new lazy value with the given initializing
1228 pub const fn new(f
: F
) -> Lazy
<T
, F
> {
1229 Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1232 /// Consumes this `Lazy` returning the stored value.
1234 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
1235 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
1236 let cell
= this
.cell
;
1237 let init
= this
.init
;
1238 cell
.into_inner().ok_or_else(|| {
1239 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
1244 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
1245 /// Forces the evaluation of this lazy value and
1246 /// returns a reference to the result. This is equivalent
1247 /// to the `Deref` impl, but is explicit.
1251 /// use once_cell::sync::Lazy;
1253 /// let lazy = Lazy::new(|| 92);
1255 /// assert_eq!(Lazy::force(&lazy), &92);
1256 /// assert_eq!(&*lazy, &92);
1258 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
1259 this
.cell
.get_or_init(|| match this
.init
.take() {
1261 None
=> panic
!("Lazy instance has previously been poisoned"),
1265 /// Forces the evaluation of this lazy value and
1266 /// returns a mutable reference to the result. This is equivalent
1267 /// to the `Deref` impl, but is explicit.
1271 /// use once_cell::sync::Lazy;
1273 /// let mut lazy = Lazy::new(|| 92);
1275 /// assert_eq!(Lazy::force_mut(&mut lazy), &mut 92);
1277 pub fn force_mut(this
: &mut Lazy
<T
, F
>) -> &mut T
{
1279 Self::get_mut(this
).unwrap_or_else(|| unreachable
!())
1282 /// Gets the reference to the result of this lazy value if
1283 /// it was initialized, otherwise returns `None`.
1287 /// use once_cell::sync::Lazy;
1289 /// let lazy = Lazy::new(|| 92);
1291 /// assert_eq!(Lazy::get(&lazy), None);
1292 /// assert_eq!(&*lazy, &92);
1293 /// assert_eq!(Lazy::get(&lazy), Some(&92));
1295 pub fn get(this
: &Lazy
<T
, F
>) -> Option
<&T
> {
1299 /// Gets the reference to the result of this lazy value if
1300 /// it was initialized, otherwise returns `None`.
1304 /// use once_cell::sync::Lazy;
1306 /// let mut lazy = Lazy::new(|| 92);
1308 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
1309 /// assert_eq!(&*lazy, &92);
1310 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
1312 pub fn get_mut(this
: &mut Lazy
<T
, F
>) -> Option
<&mut T
> {
1317 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
1319 fn deref(&self) -> &T
{
1324 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
1325 fn deref_mut(&mut self) -> &mut T
{
1327 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
1331 impl<T
: Default
> Default
for Lazy
<T
> {
1332 /// Creates a new lazy value using `Default` as the initializing function.
1333 fn default() -> Lazy
<T
> {
1334 Lazy
::new(T
::default)
1339 /// struct S(*mut ());
1340 /// unsafe impl Sync for S {}
1342 /// fn share<T: Sync>(_: &T) {}
1343 /// share(&once_cell::sync::OnceCell::<S>::new());
1347 /// struct S(*mut ());
1348 /// unsafe impl Sync for S {}
1350 /// fn share<T: Sync>(_: &T) {}
1351 /// share(&once_cell::sync::Lazy::<S>::new(|| unimplemented!()));
1356 #[cfg(feature = "race")]
1359 #[cfg(feature = "std")]
1360 unsafe fn take_unchecked
<T
>(val
: &mut Option
<T
>) -> T
{
1364 debug_assert
!(false);
1365 std
::hint
::unreachable_unchecked()