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.
316 //! * [double-checked-cell](https://github.com/niklasf/double-checked-cell)
317 //! * [lazy-init](https://crates.io/crates/lazy-init)
318 //! * [lazycell](https://crates.io/crates/lazycell)
319 //! * [mitochondria](https://crates.io/crates/mitochondria)
320 //! * [lazy_static](https://crates.io/crates/lazy_static)
322 //! Most of this crate's functionality is available in `std` in nightly Rust.
323 //! See the [tracking issue](https://github.com/rust-lang/rust/issues/74465).
325 #![cfg_attr(not(feature = "std"), no_std)]
327 #[cfg(feature = "alloc")]
330 #[cfg(feature = "std")]
331 #[cfg(feature = "parking_lot")]
332 #[path = "imp_pl.rs"]
335 #[cfg(feature = "std")]
336 #[cfg(not(feature = "parking_lot"))]
337 #[path = "imp_std.rs"]
340 /// Single-threaded version of `OnceCell`.
343 cell
::{Cell, UnsafeCell}
,
345 ops
::{Deref, DerefMut}
,
348 #[cfg(feature = "std")]
349 use std
::panic
::{RefUnwindSafe, UnwindSafe}
;
351 /// A cell which can be written to only once. It is not thread safe.
353 /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&`
354 /// references to the contents.
356 /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
360 /// use once_cell::unsync::OnceCell;
362 /// let cell = OnceCell::new();
363 /// assert!(cell.get().is_none());
365 /// let value: &String = cell.get_or_init(|| {
366 /// "Hello, World!".to_string()
368 /// assert_eq!(value, "Hello, World!");
369 /// assert!(cell.get().is_some());
371 pub struct OnceCell
<T
> {
372 // Invariant: written to at most once.
373 inner
: UnsafeCell
<Option
<T
>>,
376 // Similarly to a `Sync` bound on `sync::OnceCell`, we can use
377 // `&unsync::OnceCell` to sneak a `T` through `catch_unwind`,
378 // by initializing the cell in closure and extracting the value in the
380 #[cfg(feature = "std")]
381 impl<T
: RefUnwindSafe
+ UnwindSafe
> RefUnwindSafe
for OnceCell
<T
> {}
382 #[cfg(feature = "std")]
383 impl<T
: UnwindSafe
> UnwindSafe
for OnceCell
<T
> {}
385 impl<T
> Default
for OnceCell
<T
> {
386 fn default() -> Self {
391 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
392 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
394 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
395 None
=> f
.write_str("OnceCell(Uninit)"),
400 impl<T
: Clone
> Clone
for OnceCell
<T
> {
401 fn clone(&self) -> OnceCell
<T
> {
402 let res
= OnceCell
::new();
403 if let Some(value
) = self.get() {
404 match res
.set(value
.clone()) {
406 Err(_
) => unreachable
!(),
413 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
414 fn eq(&self, other
: &Self) -> bool
{
415 self.get() == other
.get()
419 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
421 impl<T
> From
<T
> for OnceCell
<T
> {
422 fn from(value
: T
) -> Self {
423 OnceCell { inner: UnsafeCell::new(Some(value)) }
427 impl<T
> OnceCell
<T
> {
428 /// Creates a new empty cell.
429 pub const fn new() -> OnceCell
<T
> {
430 OnceCell { inner: UnsafeCell::new(None) }
433 /// Gets a reference to the underlying value.
435 /// Returns `None` if the cell is empty.
436 pub fn get(&self) -> Option
<&T
> {
437 // Safe due to `inner`'s invariant
438 unsafe { &*self.inner.get() }
.as_ref()
441 /// Gets a mutable reference to the underlying value.
443 /// Returns `None` if the cell is empty.
444 pub fn get_mut(&mut self) -> Option
<&mut T
> {
445 // Safe because we have unique access
446 unsafe { &mut *self.inner.get() }
.as_mut()
449 /// Sets the contents of this cell to `value`.
451 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
456 /// use once_cell::unsync::OnceCell;
458 /// let cell = OnceCell::new();
459 /// assert!(cell.get().is_none());
461 /// assert_eq!(cell.set(92), Ok(()));
462 /// assert_eq!(cell.set(62), Err(62));
464 /// assert!(cell.get().is_some());
466 pub fn set(&self, value
: T
) -> Result
<(), T
> {
467 match self.try_insert(value
) {
469 Err((_
, value
)) => Err(value
),
473 /// Like [`set`](Self::set), but also returns a referce to the final cell value.
477 /// use once_cell::unsync::OnceCell;
479 /// let cell = OnceCell::new();
480 /// assert!(cell.get().is_none());
482 /// assert_eq!(cell.try_insert(92), Ok(&92));
483 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
485 /// assert!(cell.get().is_some());
487 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
488 if let Some(old
) = self.get() {
489 return Err((old
, value
));
491 let slot
= unsafe { &mut *self.inner.get() }
;
492 // This is the only place where we set the slot, no races
493 // due to reentrancy/concurrency are possible, and we've
494 // checked that slot is currently `None`, so this write
495 // maintains the `inner`'s invariant.
498 Some(value
) => value
,
499 None
=> unsafe { hint::unreachable_unchecked() }
,
503 /// Gets the contents of the cell, initializing it with `f`
504 /// if the cell was empty.
508 /// If `f` panics, the panic is propagated to the caller, and the cell
509 /// remains uninitialized.
511 /// It is an error to reentrantly initialize the cell from `f`. Doing
512 /// so results in a panic.
516 /// use once_cell::unsync::OnceCell;
518 /// let cell = OnceCell::new();
519 /// let value = cell.get_or_init(|| 92);
520 /// assert_eq!(value, &92);
521 /// let value = cell.get_or_init(|| unreachable!());
522 /// assert_eq!(value, &92);
524 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
529 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
531 Err(void
) => match void {}
,
535 /// Gets the contents of the cell, initializing it with `f` if
536 /// the cell was empty. If the cell was empty and `f` failed, an
537 /// error is returned.
541 /// If `f` panics, the panic is propagated to the caller, and the cell
542 /// remains uninitialized.
544 /// It is an error to reentrantly initialize the cell from `f`. Doing
545 /// so results in a panic.
549 /// use once_cell::unsync::OnceCell;
551 /// let cell = OnceCell::new();
552 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
553 /// assert!(cell.get().is_none());
554 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
557 /// assert_eq!(value, Ok(&92));
558 /// assert_eq!(cell.get(), Some(&92))
560 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
562 F
: FnOnce() -> Result
<T
, E
>,
564 if let Some(val
) = self.get() {
568 // Note that *some* forms of reentrant initialization might lead to
569 // UB (see `reentrant_init` test). I believe that just removing this
570 // `assert`, while keeping `set/get` would be sound, but it seems
571 // better to panic, rather than to silently use an old value.
572 assert
!(self.set(val
).is_ok(), "reentrant init");
573 Ok(self.get().unwrap())
576 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
578 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
583 /// use once_cell::unsync::OnceCell;
585 /// let mut cell: OnceCell<String> = OnceCell::new();
586 /// assert_eq!(cell.take(), None);
588 /// let mut cell = OnceCell::new();
589 /// cell.set("hello".to_string()).unwrap();
590 /// assert_eq!(cell.take(), Some("hello".to_string()));
591 /// assert_eq!(cell.get(), None);
593 pub fn take(&mut self) -> Option
<T
> {
594 mem
::replace(self, Self::default()).into_inner()
597 /// Consumes the `OnceCell`, returning the wrapped value.
599 /// Returns `None` if the cell was empty.
604 /// use once_cell::unsync::OnceCell;
606 /// let cell: OnceCell<String> = OnceCell::new();
607 /// assert_eq!(cell.into_inner(), None);
609 /// let cell = OnceCell::new();
610 /// cell.set("hello".to_string()).unwrap();
611 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
613 pub fn into_inner(self) -> Option
<T
> {
614 // Because `into_inner` takes `self` by value, the compiler statically verifies
615 // that it is not currently borrowed. So it is safe to move out `Option<T>`.
616 self.inner
.into_inner()
620 /// A value which is initialized on the first access.
624 /// use once_cell::unsync::Lazy;
626 /// let lazy: Lazy<i32> = Lazy::new(|| {
627 /// println!("initializing");
630 /// println!("ready");
631 /// println!("{}", *lazy);
632 /// println!("{}", *lazy);
640 pub struct Lazy
<T
, F
= fn() -> T
> {
642 init
: Cell
<Option
<F
>>,
645 #[cfg(feature = "std")]
646 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
648 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
649 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
650 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
654 impl<T
, F
> Lazy
<T
, F
> {
655 /// Creates a new lazy value with the given initializing function.
660 /// use once_cell::unsync::Lazy;
662 /// let hello = "Hello, World!".to_string();
664 /// let lazy = Lazy::new(|| hello.to_uppercase());
666 /// assert_eq!(&*lazy, "HELLO, WORLD!");
669 pub const fn new(init
: F
) -> Lazy
<T
, F
> {
670 Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
673 /// Consumes this `Lazy` returning the stored value.
675 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
676 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
677 let cell
= this
.cell
;
678 let init
= this
.init
;
679 cell
.into_inner().ok_or_else(|| {
680 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
685 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
686 /// Forces the evaluation of this lazy value and returns a reference to
689 /// This is equivalent to the `Deref` impl, but is explicit.
693 /// use once_cell::unsync::Lazy;
695 /// let lazy = Lazy::new(|| 92);
697 /// assert_eq!(Lazy::force(&lazy), &92);
698 /// assert_eq!(&*lazy, &92);
700 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
701 this
.cell
.get_or_init(|| match this
.init
.take() {
703 None
=> panic
!("Lazy instance has previously been poisoned"),
708 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
710 fn deref(&self) -> &T
{
715 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
716 fn deref_mut(&mut self) -> &mut T
{
718 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
722 impl<T
: Default
> Default
for Lazy
<T
> {
723 /// Creates a new lazy value using `Default` as the initializing function.
724 fn default() -> Lazy
<T
> {
725 Lazy
::new(T
::default)
730 /// Thread-safe, blocking version of `OnceCell`.
731 #[cfg(feature = "std")]
736 ops
::{Deref, DerefMut}
,
737 panic
::RefUnwindSafe
,
740 use crate::imp
::OnceCell
as Imp
;
742 /// A thread-safe cell which can be written to only once.
744 /// `OnceCell` provides `&` references to the contents without RAII guards.
746 /// Reading a non-`None` value out of `OnceCell` establishes a
747 /// happens-before relationship with a corresponding write. For example, if
748 /// thread A initializes the cell with `get_or_init(f)`, and thread B
749 /// subsequently reads the result of this call, B also observes all the side
754 /// use once_cell::sync::OnceCell;
756 /// static CELL: OnceCell<String> = OnceCell::new();
757 /// assert!(CELL.get().is_none());
759 /// std::thread::spawn(|| {
760 /// let value: &String = CELL.get_or_init(|| {
761 /// "Hello, World!".to_string()
763 /// assert_eq!(value, "Hello, World!");
764 /// }).join().unwrap();
766 /// let value: Option<&String> = CELL.get();
767 /// assert!(value.is_some());
768 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
770 pub struct OnceCell
<T
>(Imp
<T
>);
772 impl<T
> Default
for OnceCell
<T
> {
773 fn default() -> OnceCell
<T
> {
778 impl<T
: fmt
::Debug
> fmt
::Debug
for OnceCell
<T
> {
779 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
781 Some(v
) => f
.debug_tuple("OnceCell").field(v
).finish(),
782 None
=> f
.write_str("OnceCell(Uninit)"),
787 impl<T
: Clone
> Clone
for OnceCell
<T
> {
788 fn clone(&self) -> OnceCell
<T
> {
789 let res
= OnceCell
::new();
790 if let Some(value
) = self.get() {
791 match res
.set(value
.clone()) {
793 Err(_
) => unreachable
!(),
800 impl<T
> From
<T
> for OnceCell
<T
> {
801 fn from(value
: T
) -> Self {
802 let cell
= Self::new();
803 cell
.get_or_init(|| value
);
808 impl<T
: PartialEq
> PartialEq
for OnceCell
<T
> {
809 fn eq(&self, other
: &OnceCell
<T
>) -> bool
{
810 self.get() == other
.get()
814 impl<T
: Eq
> Eq
for OnceCell
<T
> {}
816 impl<T
> OnceCell
<T
> {
817 /// Creates a new empty cell.
818 pub const fn new() -> OnceCell
<T
> {
822 /// Gets the reference to the underlying value.
824 /// Returns `None` if the cell is empty, or being initialized. This
825 /// method never blocks.
826 pub fn get(&self) -> Option
<&T
> {
827 if self.0.is_initialized
() {
828 // Safe b/c value is initialized.
829 Some(unsafe { self.get_unchecked() }
)
835 /// Gets the mutable reference to the underlying value.
837 /// Returns `None` if the cell is empty.
838 pub fn get_mut(&mut self) -> Option
<&mut T
> {
842 /// Get the reference to the underlying value, without checking if the
843 /// cell is initialized.
847 /// Caller must ensure that the cell is in initialized state, and that
848 /// the contents are acquired by (synchronized to) this thread.
849 pub unsafe fn get_unchecked(&self) -> &T
{
850 self.0.get_unchecked()
853 /// Sets the contents of this cell to `value`.
855 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
861 /// use once_cell::sync::OnceCell;
863 /// static CELL: OnceCell<i32> = OnceCell::new();
866 /// assert!(CELL.get().is_none());
868 /// std::thread::spawn(|| {
869 /// assert_eq!(CELL.set(92), Ok(()));
870 /// }).join().unwrap();
872 /// assert_eq!(CELL.set(62), Err(62));
873 /// assert_eq!(CELL.get(), Some(&92));
876 pub fn set(&self, value
: T
) -> Result
<(), T
> {
877 match self.try_insert(value
) {
879 Err((_
, value
)) => Err(value
),
883 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
888 /// use once_cell::unsync::OnceCell;
890 /// let cell = OnceCell::new();
891 /// assert!(cell.get().is_none());
893 /// assert_eq!(cell.try_insert(92), Ok(&92));
894 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
896 /// assert!(cell.get().is_some());
898 pub fn try_insert(&self, value
: T
) -> Result
<&T
, (&T
, T
)> {
899 let mut value
= Some(value
);
900 let res
= self.get_or_init(|| value
.take().unwrap());
903 Some(value
) => Err((res
, value
)),
907 /// Gets the contents of the cell, initializing it with `f` if the cell
910 /// Many threads may call `get_or_init` concurrently with different
911 /// initializing functions, but it is guaranteed that only one function
912 /// will be executed.
916 /// If `f` panics, the panic is propagated to the caller, and the cell
917 /// remains uninitialized.
919 /// It is an error to reentrantly initialize the cell from `f`. The
920 /// exact outcome is unspecified. Current implementation deadlocks, but
921 /// this may be changed to a panic in the future.
925 /// use once_cell::sync::OnceCell;
927 /// let cell = OnceCell::new();
928 /// let value = cell.get_or_init(|| 92);
929 /// assert_eq!(value, &92);
930 /// let value = cell.get_or_init(|| unreachable!());
931 /// assert_eq!(value, &92);
933 pub fn get_or_init
<F
>(&self, f
: F
) -> &T
938 match self.get_or_try_init(|| Ok
::<T
, Void
>(f())) {
940 Err(void
) => match void {}
,
944 /// Gets the contents of the cell, initializing it with `f` if
945 /// the cell was empty. If the cell was empty and `f` failed, an
946 /// error is returned.
950 /// If `f` panics, the panic is propagated to the caller, and
951 /// the cell remains uninitialized.
953 /// It is an error to reentrantly initialize the cell from `f`.
954 /// The exact outcome is unspecified. Current implementation
955 /// deadlocks, but this may be changed to a panic in the future.
959 /// use once_cell::sync::OnceCell;
961 /// let cell = OnceCell::new();
962 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
963 /// assert!(cell.get().is_none());
964 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
967 /// assert_eq!(value, Ok(&92));
968 /// assert_eq!(cell.get(), Some(&92))
970 pub fn get_or_try_init
<F
, E
>(&self, f
: F
) -> Result
<&T
, E
>
972 F
: FnOnce() -> Result
<T
, E
>,
975 if let Some(value
) = self.get() {
978 self.0.initialize
(f
)?
;
980 // Safe b/c value is initialized.
981 debug_assert
!(self.0.is_initialized
());
982 Ok(unsafe { self.get_unchecked() }
)
985 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
987 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
992 /// use once_cell::sync::OnceCell;
994 /// let mut cell: OnceCell<String> = OnceCell::new();
995 /// assert_eq!(cell.take(), None);
997 /// let mut cell = OnceCell::new();
998 /// cell.set("hello".to_string()).unwrap();
999 /// assert_eq!(cell.take(), Some("hello".to_string()));
1000 /// assert_eq!(cell.get(), None);
1002 pub fn take(&mut self) -> Option
<T
> {
1003 mem
::replace(self, Self::default()).into_inner()
1006 /// Consumes the `OnceCell`, returning the wrapped value. Returns
1007 /// `None` if the cell was empty.
1012 /// use once_cell::sync::OnceCell;
1014 /// let cell: OnceCell<String> = OnceCell::new();
1015 /// assert_eq!(cell.into_inner(), None);
1017 /// let cell = OnceCell::new();
1018 /// cell.set("hello".to_string()).unwrap();
1019 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
1021 pub fn into_inner(self) -> Option
<T
> {
1026 /// A value which is initialized on the first access.
1028 /// This type is thread-safe and can be used in statics.
1033 /// use std::collections::HashMap;
1035 /// use once_cell::sync::Lazy;
1037 /// static HASHMAP: Lazy<HashMap<i32, String>> = Lazy::new(|| {
1038 /// println!("initializing");
1039 /// let mut m = HashMap::new();
1040 /// m.insert(13, "Spica".to_string());
1041 /// m.insert(74, "Hoyten".to_string());
1046 /// println!("ready");
1047 /// std::thread::spawn(|| {
1048 /// println!("{:?}", HASHMAP.get(&13));
1049 /// }).join().unwrap();
1050 /// println!("{:?}", HASHMAP.get(&74));
1055 /// // Some("Spica")
1056 /// // Some("Hoyten")
1059 pub struct Lazy
<T
, F
= fn() -> T
> {
1061 init
: Cell
<Option
<F
>>,
1064 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for Lazy
<T
, F
> {
1065 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1066 f
.debug_struct("Lazy").field("cell", &self.cell
).field("init", &"..").finish()
1070 // We never create a `&F` from a `&Lazy<T, F>` so it is fine to not impl
1071 // `Sync` for `F`. we do create a `&mut Option<F>` in `force`, but this is
1072 // properly synchronized, so it only happens once so it also does not
1073 // contribute to this impl.
1074 unsafe impl<T
, F
: Send
> Sync
for Lazy
<T
, F
> where OnceCell
<T
>: Sync {}
1075 // auto-derived `Send` impl is OK.
1077 #[cfg(feature = "std")]
1078 impl<T
, F
: RefUnwindSafe
> RefUnwindSafe
for Lazy
<T
, F
> where OnceCell
<T
>: RefUnwindSafe {}
1080 impl<T
, F
> Lazy
<T
, F
> {
1081 /// Creates a new lazy value with the given initializing
1083 pub const fn new(f
: F
) -> Lazy
<T
, F
> {
1084 Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1087 /// Consumes this `Lazy` returning the stored value.
1089 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
1090 pub fn into_value(this
: Lazy
<T
, F
>) -> Result
<T
, F
> {
1091 let cell
= this
.cell
;
1092 let init
= this
.init
;
1093 cell
.into_inner().ok_or_else(|| {
1094 init
.take().unwrap_or_else(|| panic
!("Lazy instance has previously been poisoned"))
1099 impl<T
, F
: FnOnce() -> T
> Lazy
<T
, F
> {
1100 /// Forces the evaluation of this lazy value and
1101 /// returns a reference to the result. This is equivalent
1102 /// to the `Deref` impl, but is explicit.
1106 /// use once_cell::sync::Lazy;
1108 /// let lazy = Lazy::new(|| 92);
1110 /// assert_eq!(Lazy::force(&lazy), &92);
1111 /// assert_eq!(&*lazy, &92);
1113 pub fn force(this
: &Lazy
<T
, F
>) -> &T
{
1114 this
.cell
.get_or_init(|| match this
.init
.take() {
1116 None
=> panic
!("Lazy instance has previously been poisoned"),
1121 impl<T
, F
: FnOnce() -> T
> Deref
for Lazy
<T
, F
> {
1123 fn deref(&self) -> &T
{
1128 impl<T
, F
: FnOnce() -> T
> DerefMut
for Lazy
<T
, F
> {
1129 fn deref_mut(&mut self) -> &mut T
{
1131 self.cell
.get_mut().unwrap_or_else(|| unreachable
!())
1135 impl<T
: Default
> Default
for Lazy
<T
> {
1136 /// Creates a new lazy value using `Default` as the initializing function.
1137 fn default() -> Lazy
<T
> {
1138 Lazy
::new(T
::default)
1143 /// struct S(*mut ());
1144 /// unsafe impl Sync for S {}
1146 /// fn share<T: Sync>(_: &T) {}
1147 /// share(&once_cell::sync::OnceCell::<S>::new());
1151 /// struct S(*mut ());
1152 /// unsafe impl Sync for S {}
1154 /// fn share<T: Sync>(_: &T) {}
1155 /// share(&once_cell::sync::Lazy::<S>::new(|| unimplemented!()));
1160 #[cfg(feature = "race")]
1163 #[cfg(feature = "std")]
1164 unsafe fn take_unchecked
<T
>(val
: &mut Option
<T
>) -> T
{
1168 debug_assert
!(false);
1169 std
::hint
::unreachable_unchecked()