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