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.36.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}
,
353 #[cfg(feature = "std")]
354 use std
::panic
::{RefUnwindSafe, UnwindSafe}
;
356 /// A cell which can be written to only once. It is not thread safe.
358 /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&`
359 /// references to the contents.
361 /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
365 /// use once_cell::unsync::OnceCell;
367 /// let cell = OnceCell::new();
368 /// assert!(cell.get().is_none());
370 /// let value: &String = cell.get_or_init(|| {
371 /// "Hello, World!".to_string()
373 /// assert_eq!(value, "Hello, World!");
374 /// assert!(cell.get().is_some());
376 pub struct OnceCell
<T
> {
377 // Invariant: written to at most once.
378 inner
: UnsafeCell
<Option
<T
>>,
381 // Similarly to a `Sync` bound on `sync::OnceCell`, we can use
382 // `&unsync::OnceCell` to sneak a `T` through `catch_unwind`,
383 // by initializing the cell in closure and extracting the value in the
385 #[cfg(feature = "std")]
386 impl<T
: RefUnwindSafe
+ UnwindSafe
> RefUnwindSafe
for OnceCell
<T
> {}
387 #[cfg(feature = "std")]
388 impl<T
: UnwindSafe
> UnwindSafe
for OnceCell
<T
> {}
390 impl<T
> Default
for OnceCell
<T
> {
391 fn default() -> Self {
396 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
397 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
399 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
400 None
=> f
.write_str("OnceCell(Uninit)"),
405 impl<T
: Clone
> Clone
for OnceCell
<T
> {
406 fn clone(&self) -> OnceCell
<T
> {
408 Some(value
) => OnceCell
::with_value(value
.clone()),
409 None
=> OnceCell
::new(),
413 fn clone_from(&mut self, source
: &Self) {
414 match (self.get_mut(), source
.get()) {
415 (Some(this
), Some(source
)) => this
.clone_from(source
),
416 _
=> *self = source
.clone(),
421 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
422 fn eq(&self, other
: &Self) -> bool
{
423 self.get() == other
.get()
427 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
429 impl<T
> From
<T
> for OnceCell
<T
> {
430 fn from(value
: T
) -> Self {
431 OnceCell
::with_value(value
)
435 impl<T
> OnceCell
<T
> {
436 /// Creates a new empty cell.
437 pub const fn new() -> OnceCell
<T
> {
438 OnceCell { inner: UnsafeCell::new(None) }
441 /// Creates a new initialized cell.
442 pub const fn with_value(value
: T
) -> OnceCell
<T
> {
443 OnceCell { inner: UnsafeCell::new(Some(value)) }
446 /// Gets a reference to the underlying value.
448 /// Returns `None` if the cell is empty.
449 pub fn get(&self) -> Option
<&T
> {
450 // Safe due to `inner`'s invariant
451 unsafe { &*self.inner.get() }
.as_ref()
454 /// Gets a mutable reference to the underlying value.
456 /// Returns `None` if the cell is empty.
458 /// This method is allowed to violate the invariant of writing to a `OnceCell`
459 /// at most once because it requires `&mut` access to `self`. As with all
460 /// interior mutability, `&mut` access permits arbitrary modification:
463 /// use once_cell::unsync::OnceCell;
465 /// let mut cell: OnceCell<u32> = OnceCell::new();
466 /// cell.set(92).unwrap();
467 /// cell = OnceCell::new();
469 pub fn get_mut(&mut self) -> Option
<&mut T
> {
470 // Safe because we have unique access
471 unsafe { &mut *self.inner.get() }
.as_mut()
474 /// Sets the contents of this cell to `value`.
476 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
481 /// use once_cell::unsync::OnceCell;
483 /// let cell = OnceCell::new();
484 /// assert!(cell.get().is_none());
486 /// assert_eq!(cell.set(92), Ok(()));
487 /// assert_eq!(cell.set(62), Err(62));
489 /// assert!(cell.get().is_some());
491 pub fn set(&self, value
: T
) -> Result
<(), T
> {
492 match self.try_insert(value
) {
494 Err((_
, value
)) => Err(value
),
498 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
502 /// use once_cell::unsync::OnceCell;
504 /// let cell = OnceCell::new();
505 /// assert!(cell.get().is_none());
507 /// assert_eq!(cell.try_insert(92), Ok(&92));
508 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
510 /// assert!(cell.get().is_some());
512 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
513 if let Some(old
) = self.get() {
514 return Err((old
, value
));
516 let slot
= unsafe { &mut *self.inner.get() }
;
517 // This is the only place where we set the slot, no races
518 // due to reentrancy/concurrency are possible, and we've
519 // checked that slot is currently `None`, so this write
520 // maintains the `inner`'s invariant.
523 Some(value
) => value
,
524 None
=> unsafe { hint::unreachable_unchecked() }
,
528 /// Gets the contents of the cell, initializing it with `f`
529 /// if the cell was empty.
533 /// If `f` panics, the panic is propagated to the caller, and the cell
534 /// remains uninitialized.
536 /// It is an error to reentrantly initialize the cell from `f`. Doing
537 /// so results in a panic.
541 /// use once_cell::unsync::OnceCell;
543 /// let cell = OnceCell::new();
544 /// let value = cell.get_or_init(|| 92);
545 /// assert_eq!(value, &92);
546 /// let value = cell.get_or_init(|| unreachable!());
547 /// assert_eq!(value, &92);
549 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
554 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
556 Err(void
) => match void {}
,
560 /// Gets the contents of the cell, initializing it with `f` if
561 /// the cell was empty. If the cell was empty and `f` failed, an
562 /// error is returned.
566 /// If `f` panics, the panic is propagated to the caller, and the cell
567 /// remains uninitialized.
569 /// It is an error to reentrantly initialize the cell from `f`. Doing
570 /// so results in a panic.
574 /// use once_cell::unsync::OnceCell;
576 /// let cell = OnceCell::new();
577 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
578 /// assert!(cell.get().is_none());
579 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
582 /// assert_eq!(value, Ok(&92));
583 /// assert_eq!(cell.get(), Some(&92))
585 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
587 F
: FnOnce() -> Result
<T
, E
>,
589 if let Some(val
) = self.get() {
593 // Note that *some* forms of reentrant initialization might lead to
594 // UB (see `reentrant_init` test). I believe that just removing this
595 // `assert`, while keeping `set/get` would be sound, but it seems
596 // better to panic, rather than to silently use an old value.
597 assert
!(self.set(val
).is_ok(), "reentrant init");
598 Ok(self.get().unwrap())
601 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
603 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
608 /// use once_cell::unsync::OnceCell;
610 /// let mut cell: OnceCell<String> = OnceCell::new();
611 /// assert_eq!(cell.take(), None);
613 /// let mut cell = OnceCell::new();
614 /// cell.set("hello".to_string()).unwrap();
615 /// assert_eq!(cell.take(), Some("hello".to_string()));
616 /// assert_eq!(cell.get(), None);
619 /// This method is allowed to violate the invariant of writing to a `OnceCell`
620 /// at most once because it requires `&mut` access to `self`. As with all
621 /// interior mutability, `&mut` access permits arbitrary modification:
624 /// use once_cell::unsync::OnceCell;
626 /// let mut cell: OnceCell<u32> = OnceCell::new();
627 /// cell.set(92).unwrap();
628 /// cell = OnceCell::new();
630 pub fn take(&mut self) -> Option
<T
> {
631 mem
::replace(self, Self::default()).into_inner()
634 /// Consumes the `OnceCell`, returning the wrapped value.
636 /// Returns `None` if the cell was empty.
641 /// use once_cell::unsync::OnceCell;
643 /// let cell: OnceCell<String> = OnceCell::new();
644 /// assert_eq!(cell.into_inner(), None);
646 /// let cell = OnceCell::new();
647 /// cell.set("hello".to_string()).unwrap();
648 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
650 pub fn into_inner(self) -> Option
<T
> {
651 // Because `into_inner` takes `self` by value, the compiler statically verifies
652 // that it is not currently borrowed. So it is safe to move out `Option<T>`.
653 self.inner
.into_inner()
657 /// A value which is initialized on the first access.
661 /// use once_cell::unsync::Lazy;
663 /// let lazy: Lazy<i32> = Lazy::new(|| {
664 /// println!("initializing");
667 /// println!("ready");
668 /// println!("{}", *lazy);
669 /// println!("{}", *lazy);
677 pub struct Lazy
<T
, F
= fn() -> T
> {
679 init
: Cell
<Option
<F
>>,
682 #[cfg(feature = "std")]
683 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
685 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
686 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
687 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
691 impl<T
, F
> Lazy
<T
, F
> {
692 /// Creates a new lazy value with the given initializing function.
697 /// use once_cell::unsync::Lazy;
699 /// let hello = "Hello, World!".to_string();
701 /// let lazy = Lazy::new(|| hello.to_uppercase());
703 /// assert_eq!(&*lazy, "HELLO, WORLD!");
706 pub const fn new(init
: F
) -> Lazy
<T
, F
> {
707 Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
710 /// Consumes this `Lazy` returning the stored value.
712 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
713 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
714 let cell
= this
.cell
;
715 let init
= this
.init
;
716 cell
.into_inner().ok_or_else(|| {
717 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
722 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
723 /// Forces the evaluation of this lazy value and returns a reference to
726 /// This is equivalent to the `Deref` impl, but is explicit.
730 /// use once_cell::unsync::Lazy;
732 /// let lazy = Lazy::new(|| 92);
734 /// assert_eq!(Lazy::force(&lazy), &92);
735 /// assert_eq!(&*lazy, &92);
737 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
738 this
.cell
.get_or_init(|| match this
.init
.take() {
740 None
=> panic
!("Lazy instance has previously been poisoned"),
745 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
747 fn deref(&self) -> &T
{
752 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
753 fn deref_mut(&mut self) -> &mut T
{
755 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
759 impl<T
: Default
> Default
for Lazy
<T
> {
760 /// Creates a new lazy value using `Default` as the initializing function.
761 fn default() -> Lazy
<T
> {
762 Lazy
::new(T
::default)
767 /// Thread-safe, blocking version of `OnceCell`.
768 #[cfg(feature = "std")]
773 ops
::{Deref, DerefMut}
,
774 panic
::RefUnwindSafe
,
777 use crate::{imp::OnceCell as Imp, take_unchecked}
;
779 /// A thread-safe cell which can be written to only once.
781 /// `OnceCell` provides `&` references to the contents without RAII guards.
783 /// Reading a non-`None` value out of `OnceCell` establishes a
784 /// happens-before relationship with a corresponding write. For example, if
785 /// thread A initializes the cell with `get_or_init(f)`, and thread B
786 /// subsequently reads the result of this call, B also observes all the side
791 /// use once_cell::sync::OnceCell;
793 /// static CELL: OnceCell<String> = OnceCell::new();
794 /// assert!(CELL.get().is_none());
796 /// std::thread::spawn(|| {
797 /// let value: &String = CELL.get_or_init(|| {
798 /// "Hello, World!".to_string()
800 /// assert_eq!(value, "Hello, World!");
801 /// }).join().unwrap();
803 /// let value: Option<&String> = CELL.get();
804 /// assert!(value.is_some());
805 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
807 pub struct OnceCell
<T
>(Imp
<T
>);
809 impl<T
> Default
for OnceCell
<T
> {
810 fn default() -> OnceCell
<T
> {
815 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
816 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
818 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
819 None
=> f
.write_str("OnceCell(Uninit)"),
824 impl<T
: Clone
> Clone
for OnceCell
<T
> {
825 fn clone(&self) -> OnceCell
<T
> {
827 Some(value
) => Self::with_value(value
.clone()),
832 fn clone_from(&mut self, source
: &Self) {
833 match (self.get_mut(), source
.get()) {
834 (Some(this
), Some(source
)) => this
.clone_from(source
),
835 _
=> *self = source
.clone(),
840 impl<T
> From
<T
> for OnceCell
<T
> {
841 fn from(value
: T
) -> Self {
842 Self::with_value(value
)
846 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
847 fn eq(&self, other
: &OnceCell
<T
>) -> bool
{
848 self.get() == other
.get()
852 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
854 impl<T
> OnceCell
<T
> {
855 /// Creates a new empty cell.
856 pub const fn new() -> OnceCell
<T
> {
860 /// Creates a new initialized cell.
861 pub const fn with_value(value
: T
) -> OnceCell
<T
> {
862 OnceCell(Imp
::with_value(value
))
865 /// Gets the reference to the underlying value.
867 /// Returns `None` if the cell is empty, or being initialized. This
868 /// method never blocks.
869 pub fn get(&self) -> Option
<&T
> {
870 if self.0.is_initialized
() {
871 // Safe b/c value is initialized.
872 Some(unsafe { self.get_unchecked() }
)
878 /// Gets the reference to the underlying value, blocking the current
879 /// thread until it is set.
882 /// use once_cell::sync::OnceCell;
884 /// let mut cell = std::sync::Arc::new(OnceCell::new());
885 /// let t = std::thread::spawn({
886 /// let cell = std::sync::Arc::clone(&cell);
887 /// move || cell.set(92).unwrap()
890 /// // Returns immediately, but might return None.
891 /// let _value_or_none = cell.get();
893 /// // Will return 92, but might block until the other thread does `.set`.
894 /// let value: &u32 = cell.wait();
895 /// assert_eq!(*value, 92);
896 /// t.join().unwrap();;
898 pub fn wait(&self) -> &T
{
899 if !self.0.is_initialized
() {
902 debug_assert
!(self.0.is_initialized
());
903 // Safe b/c of the wait call above and the fact that we didn't
904 // relinquish our borrow.
905 unsafe { self.get_unchecked() }
908 /// Gets the mutable reference to the underlying value.
910 /// Returns `None` if the cell is empty.
912 /// This method is allowed to violate the invariant of writing to a `OnceCell`
913 /// at most once because it requires `&mut` access to `self`. As with all
914 /// interior mutability, `&mut` access permits arbitrary modification:
917 /// use once_cell::sync::OnceCell;
919 /// let mut cell: OnceCell<u32> = OnceCell::new();
920 /// cell.set(92).unwrap();
921 /// cell = OnceCell::new();
923 pub fn get_mut(&mut self) -> Option
<&mut T
> {
927 /// Get the reference to the underlying value, without checking if the
928 /// cell is initialized.
932 /// Caller must ensure that the cell is in initialized state, and that
933 /// the contents are acquired by (synchronized to) this thread.
934 pub unsafe fn get_unchecked(&self) -> &T
{
935 self.0.get_unchecked()
938 /// Sets the contents of this cell to `value`.
940 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
946 /// use once_cell::sync::OnceCell;
948 /// static CELL: OnceCell<i32> = OnceCell::new();
951 /// assert!(CELL.get().is_none());
953 /// std::thread::spawn(|| {
954 /// assert_eq!(CELL.set(92), Ok(()));
955 /// }).join().unwrap();
957 /// assert_eq!(CELL.set(62), Err(62));
958 /// assert_eq!(CELL.get(), Some(&92));
961 pub fn set(&self, value
: T
) -> Result
<(), T
> {
962 match self.try_insert(value
) {
964 Err((_
, value
)) => Err(value
),
968 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
973 /// use once_cell::unsync::OnceCell;
975 /// let cell = OnceCell::new();
976 /// assert!(cell.get().is_none());
978 /// assert_eq!(cell.try_insert(92), Ok(&92));
979 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
981 /// assert!(cell.get().is_some());
983 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
984 let mut value
= Some(value
);
985 let res
= self.get_or_init(|| unsafe { take_unchecked(&mut value) }
);
988 Some(value
) => Err((res
, value
)),
992 /// Gets the contents of the cell, initializing it with `f` if the cell
995 /// Many threads may call `get_or_init` concurrently with different
996 /// initializing functions, but it is guaranteed that only one function
997 /// will be executed.
1001 /// If `f` panics, the panic is propagated to the caller, and the cell
1002 /// remains uninitialized.
1004 /// It is an error to reentrantly initialize the cell from `f`. The
1005 /// exact outcome is unspecified. Current implementation deadlocks, but
1006 /// this may be changed to a panic in the future.
1010 /// use once_cell::sync::OnceCell;
1012 /// let cell = OnceCell::new();
1013 /// let value = cell.get_or_init(|| 92);
1014 /// assert_eq!(value, &92);
1015 /// let value = cell.get_or_init(|| unreachable!());
1016 /// assert_eq!(value, &92);
1018 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
1023 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
1025 Err(void
) => match void {}
,
1029 /// Gets the contents of the cell, initializing it with `f` if
1030 /// the cell was empty. If the cell was empty and `f` failed, an
1031 /// error is returned.
1035 /// If `f` panics, the panic is propagated to the caller, and
1036 /// the cell remains uninitialized.
1038 /// It is an error to reentrantly initialize the cell from `f`.
1039 /// The exact outcome is unspecified. Current implementation
1040 /// deadlocks, but this may be changed to a panic in the future.
1044 /// use once_cell::sync::OnceCell;
1046 /// let cell = OnceCell::new();
1047 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
1048 /// assert!(cell.get().is_none());
1049 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
1052 /// assert_eq!(value, Ok(&92));
1053 /// assert_eq!(cell.get(), Some(&92))
1055 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
1057 F
: FnOnce() -> Result
<T
, E
>,
1060 if let Some(value
) = self.get() {
1063 self.0.initialize
(f
)?
;
1065 // Safe b/c value is initialized.
1066 debug_assert
!(self.0.is_initialized
());
1067 Ok(unsafe { self.get_unchecked() }
)
1070 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
1072 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
1077 /// use once_cell::sync::OnceCell;
1079 /// let mut cell: OnceCell<String> = OnceCell::new();
1080 /// assert_eq!(cell.take(), None);
1082 /// let mut cell = OnceCell::new();
1083 /// cell.set("hello".to_string()).unwrap();
1084 /// assert_eq!(cell.take(), Some("hello".to_string()));
1085 /// assert_eq!(cell.get(), None);
1088 /// This method is allowed to violate the invariant of writing to a `OnceCell`
1089 /// at most once because it requires `&mut` access to `self`. As with all
1090 /// interior mutability, `&mut` access permits arbitrary modification:
1093 /// use once_cell::sync::OnceCell;
1095 /// let mut cell: OnceCell<u32> = OnceCell::new();
1096 /// cell.set(92).unwrap();
1097 /// cell = OnceCell::new();
1099 pub fn take(&mut self) -> Option
<T
> {
1100 mem
::replace(self, Self::default()).into_inner()
1103 /// Consumes the `OnceCell`, returning the wrapped value. Returns
1104 /// `None` if the cell was empty.
1109 /// use once_cell::sync::OnceCell;
1111 /// let cell: OnceCell<String> = OnceCell::new();
1112 /// assert_eq!(cell.into_inner(), None);
1114 /// let cell = OnceCell::new();
1115 /// cell.set("hello".to_string()).unwrap();
1116 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
1118 pub fn into_inner(self) -> Option
<T
> {
1123 /// A value which is initialized on the first access.
1125 /// This type is thread-safe and can be used in statics.
1130 /// use std::collections::HashMap;
1132 /// use once_cell::sync::Lazy;
1134 /// static HASHMAP: Lazy<HashMap<i32, String>> = Lazy::new(|| {
1135 /// println!("initializing");
1136 /// let mut m = HashMap::new();
1137 /// m.insert(13, "Spica".to_string());
1138 /// m.insert(74, "Hoyten".to_string());
1143 /// println!("ready");
1144 /// std::thread::spawn(|| {
1145 /// println!("{:?}", HASHMAP.get(&13));
1146 /// }).join().unwrap();
1147 /// println!("{:?}", HASHMAP.get(&74));
1152 /// // Some("Spica")
1153 /// // Some("Hoyten")
1156 pub struct Lazy
<T
, F
= fn() -> T
> {
1158 init
: Cell
<Option
<F
>>,
1161 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
1162 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1163 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
1167 // We never create a `&F` from a `&Lazy<T, F>` so it is fine to not impl
1168 // `Sync` for `F`. We do create a `&mut Option<F>` in `force`, but this is
1169 // properly synchronized, so it only happens once so it also does not
1170 // contribute to this impl.
1171 unsafe impl<T
, F
: Send
> Sync
for Lazy
<T
, F
> where OnceCell
<T
>: Sync {}
1172 // auto-derived `Send` impl is OK.
1174 #[cfg(feature = "std")]
1175 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
1177 impl<T
, F
> Lazy
<T
, F
> {
1178 /// Creates a new lazy value with the given initializing
1180 pub const fn new(f
: F
) -> Lazy
<T
, F
> {
1181 Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1184 /// Consumes this `Lazy` returning the stored value.
1186 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
1187 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
1188 let cell
= this
.cell
;
1189 let init
= this
.init
;
1190 cell
.into_inner().ok_or_else(|| {
1191 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
1196 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
1197 /// Forces the evaluation of this lazy value and
1198 /// returns a reference to the result. This is equivalent
1199 /// to the `Deref` impl, but is explicit.
1203 /// use once_cell::sync::Lazy;
1205 /// let lazy = Lazy::new(|| 92);
1207 /// assert_eq!(Lazy::force(&lazy), &92);
1208 /// assert_eq!(&*lazy, &92);
1210 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
1211 this
.cell
.get_or_init(|| match this
.init
.take() {
1213 None
=> panic
!("Lazy instance has previously been poisoned"),
1218 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
1220 fn deref(&self) -> &T
{
1225 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
1226 fn deref_mut(&mut self) -> &mut T
{
1228 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
1232 impl<T
: Default
> Default
for Lazy
<T
> {
1233 /// Creates a new lazy value using `Default` as the initializing function.
1234 fn default() -> Lazy
<T
> {
1235 Lazy
::new(T
::default)
1240 /// struct S(*mut ());
1241 /// unsafe impl Sync for S {}
1243 /// fn share<T: Sync>(_: &T) {}
1244 /// share(&once_cell::sync::OnceCell::<S>::new());
1248 /// struct S(*mut ());
1249 /// unsafe impl Sync for S {}
1251 /// fn share<T: Sync>(_: &T) {}
1252 /// share(&once_cell::sync::Lazy::<S>::new(|| unimplemented!()));
1257 #[cfg(feature = "race")]
1260 #[cfg(feature = "std")]
1261 unsafe fn take_unchecked
<T
>(val
: &mut Option
<T
>) -> T
{
1265 debug_assert
!(false);
1266 std
::hint
::unreachable_unchecked()