]> git.proxmox.com Git - rustc.git/blob - vendor/once_cell/src/lib.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / vendor / once_cell / src / lib.rs
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 //! #[derive(Debug)]
212 //! pub struct LateInit<T> { cell: OnceCell<T> }
213 //!
214 //! impl<T> LateInit<T> {
215 //! pub fn init(&self, value: T) {
216 //! assert!(self.cell.set(value).is_ok())
217 //! }
218 //! }
219 //!
220 //! impl<T> Default for LateInit<T> {
221 //! fn default() -> Self { LateInit { cell: OnceCell::default() } }
222 //! }
223 //!
224 //! impl<T> std::ops::Deref for LateInit<T> {
225 //! type Target = T;
226 //! fn deref(&self) -> &T {
227 //! self.cell.get().unwrap()
228 //! }
229 //! }
230 //!
231 //! #[derive(Default, Debug)]
232 //! struct A<'a> {
233 //! b: LateInit<&'a B<'a>>,
234 //! }
235 //!
236 //! #[derive(Default, Debug)]
237 //! struct B<'a> {
238 //! a: LateInit<&'a A<'a>>
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 //! println!("{:?}", a.b.a.b.a);
247 //! }
248 //! ```
249 //!
250 //! # Comparison with std
251 //!
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 |
257 //!
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 |
263 //!
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`.
267 //!
268 //! # Minimum Supported `rustc` Version
269 //!
270 //! This crate's minimum supported `rustc` version is `1.36.0`.
271 //!
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.
275 //!
276 //! # Implementation details
277 //!
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.
281 //!
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.
287 //!
288 //! This crate uses `unsafe`.
289 //!
290 //! [`std::sync::Once`]: https://doc.rust-lang.org/std/sync/struct.Once.html
291 //!
292 //! # F.A.Q.
293 //!
294 //! **Should I use lazy_static or once_cell?**
295 //!
296 //! To the first approximation, `once_cell` is both more flexible and more convenient than `lazy_static`
297 //! and should be preferred.
298 //!
299 //! Unlike `once_cell`, `lazy_static` supports spinlock-based implementation of blocking which works with
300 //! `#![no_std]`.
301 //!
302 //! `lazy_static` has received significantly more real world testing, but `once_cell` is also a widely
303 //! used crate.
304 //!
305 //! **Should I use the sync or unsync flavor?**
306 //!
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.
310 //!
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.
313 //!
314 //! **Does this crate support async?**
315 //!
316 //! No, but you can use [`async_once_cell`](https://crates.io/crates/async_once_cell) instead.
317 //!
318 //! # Related crates
319 //!
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)
326 //!
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).
329
330 #![cfg_attr(not(feature = "std"), no_std)]
331
332 #[cfg(feature = "alloc")]
333 extern crate alloc;
334
335 #[cfg(feature = "std")]
336 #[cfg(feature = "parking_lot")]
337 #[path = "imp_pl.rs"]
338 mod imp;
339
340 #[cfg(feature = "std")]
341 #[cfg(not(feature = "parking_lot"))]
342 #[path = "imp_std.rs"]
343 mod imp;
344
345 /// Single-threaded version of `OnceCell`.
346 pub mod unsync {
347 use core::{
348 cell::{Cell, UnsafeCell},
349 fmt, hint, mem,
350 ops::{Deref, DerefMut},
351 };
352
353 #[cfg(feature = "std")]
354 use std::panic::{RefUnwindSafe, UnwindSafe};
355
356 /// A cell which can be written to only once. It is not thread safe.
357 ///
358 /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&`
359 /// references to the contents.
360 ///
361 /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
362 ///
363 /// # Example
364 /// ```
365 /// use once_cell::unsync::OnceCell;
366 ///
367 /// let cell = OnceCell::new();
368 /// assert!(cell.get().is_none());
369 ///
370 /// let value: &String = cell.get_or_init(|| {
371 /// "Hello, World!".to_string()
372 /// });
373 /// assert_eq!(value, "Hello, World!");
374 /// assert!(cell.get().is_some());
375 /// ```
376 pub struct OnceCell<T> {
377 // Invariant: written to at most once.
378 inner: UnsafeCell<Option<T>>,
379 }
380
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
384 // `Drop`.
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> {}
389
390 impl<T> Default for OnceCell<T> {
391 fn default() -> Self {
392 Self::new()
393 }
394 }
395
396 impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
398 match self.get() {
399 Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
400 None => f.write_str("OnceCell(Uninit)"),
401 }
402 }
403 }
404
405 impl<T: Clone> Clone for OnceCell<T> {
406 fn clone(&self) -> OnceCell<T> {
407 match self.get() {
408 Some(value) => OnceCell::with_value(value.clone()),
409 None => OnceCell::new(),
410 }
411 }
412
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(),
417 }
418 }
419 }
420
421 impl<T: PartialEq> PartialEq for OnceCell<T> {
422 fn eq(&self, other: &Self) -> bool {
423 self.get() == other.get()
424 }
425 }
426
427 impl<T: Eq> Eq for OnceCell<T> {}
428
429 impl<T> From<T> for OnceCell<T> {
430 fn from(value: T) -> Self {
431 OnceCell::with_value(value)
432 }
433 }
434
435 impl<T> OnceCell<T> {
436 /// Creates a new empty cell.
437 pub const fn new() -> OnceCell<T> {
438 OnceCell { inner: UnsafeCell::new(None) }
439 }
440
441 /// Creates a new initialized cell.
442 pub const fn with_value(value: T) -> OnceCell<T> {
443 OnceCell { inner: UnsafeCell::new(Some(value)) }
444 }
445
446 /// Gets a reference to the underlying value.
447 ///
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()
452 }
453
454 /// Gets a mutable reference to the underlying value.
455 ///
456 /// Returns `None` if the cell is empty.
457 ///
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:
461 ///
462 /// ```
463 /// use once_cell::unsync::OnceCell;
464 ///
465 /// let mut cell: OnceCell<u32> = OnceCell::new();
466 /// cell.set(92).unwrap();
467 /// cell = OnceCell::new();
468 /// ```
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()
472 }
473
474 /// Sets the contents of this cell to `value`.
475 ///
476 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
477 /// full.
478 ///
479 /// # Example
480 /// ```
481 /// use once_cell::unsync::OnceCell;
482 ///
483 /// let cell = OnceCell::new();
484 /// assert!(cell.get().is_none());
485 ///
486 /// assert_eq!(cell.set(92), Ok(()));
487 /// assert_eq!(cell.set(62), Err(62));
488 ///
489 /// assert!(cell.get().is_some());
490 /// ```
491 pub fn set(&self, value: T) -> Result<(), T> {
492 match self.try_insert(value) {
493 Ok(_) => Ok(()),
494 Err((_, value)) => Err(value),
495 }
496 }
497
498 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
499 ///
500 /// # Example
501 /// ```
502 /// use once_cell::unsync::OnceCell;
503 ///
504 /// let cell = OnceCell::new();
505 /// assert!(cell.get().is_none());
506 ///
507 /// assert_eq!(cell.try_insert(92), Ok(&92));
508 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
509 ///
510 /// assert!(cell.get().is_some());
511 /// ```
512 pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
513 if let Some(old) = self.get() {
514 return Err((old, value));
515 }
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.
521 *slot = Some(value);
522 Ok(match &*slot {
523 Some(value) => value,
524 None => unsafe { hint::unreachable_unchecked() },
525 })
526 }
527
528 /// Gets the contents of the cell, initializing it with `f`
529 /// if the cell was empty.
530 ///
531 /// # Panics
532 ///
533 /// If `f` panics, the panic is propagated to the caller, and the cell
534 /// remains uninitialized.
535 ///
536 /// It is an error to reentrantly initialize the cell from `f`. Doing
537 /// so results in a panic.
538 ///
539 /// # Example
540 /// ```
541 /// use once_cell::unsync::OnceCell;
542 ///
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);
548 /// ```
549 pub fn get_or_init<F>(&self, f: F) -> &T
550 where
551 F: FnOnce() -> T,
552 {
553 enum Void {}
554 match self.get_or_try_init(|| Ok::<T, Void>(f())) {
555 Ok(val) => val,
556 Err(void) => match void {},
557 }
558 }
559
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.
563 ///
564 /// # Panics
565 ///
566 /// If `f` panics, the panic is propagated to the caller, and the cell
567 /// remains uninitialized.
568 ///
569 /// It is an error to reentrantly initialize the cell from `f`. Doing
570 /// so results in a panic.
571 ///
572 /// # Example
573 /// ```
574 /// use once_cell::unsync::OnceCell;
575 ///
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, ()> {
580 /// Ok(92)
581 /// });
582 /// assert_eq!(value, Ok(&92));
583 /// assert_eq!(cell.get(), Some(&92))
584 /// ```
585 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
586 where
587 F: FnOnce() -> Result<T, E>,
588 {
589 if let Some(val) = self.get() {
590 return Ok(val);
591 }
592 let val = f()?;
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())
599 }
600
601 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
602 ///
603 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
604 ///
605 /// # Examples
606 ///
607 /// ```
608 /// use once_cell::unsync::OnceCell;
609 ///
610 /// let mut cell: OnceCell<String> = OnceCell::new();
611 /// assert_eq!(cell.take(), None);
612 ///
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);
617 /// ```
618 ///
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:
622 ///
623 /// ```
624 /// use once_cell::unsync::OnceCell;
625 ///
626 /// let mut cell: OnceCell<u32> = OnceCell::new();
627 /// cell.set(92).unwrap();
628 /// cell = OnceCell::new();
629 /// ```
630 pub fn take(&mut self) -> Option<T> {
631 mem::replace(self, Self::default()).into_inner()
632 }
633
634 /// Consumes the `OnceCell`, returning the wrapped value.
635 ///
636 /// Returns `None` if the cell was empty.
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use once_cell::unsync::OnceCell;
642 ///
643 /// let cell: OnceCell<String> = OnceCell::new();
644 /// assert_eq!(cell.into_inner(), None);
645 ///
646 /// let cell = OnceCell::new();
647 /// cell.set("hello".to_string()).unwrap();
648 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
649 /// ```
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()
654 }
655 }
656
657 /// A value which is initialized on the first access.
658 ///
659 /// # Example
660 /// ```
661 /// use once_cell::unsync::Lazy;
662 ///
663 /// let lazy: Lazy<i32> = Lazy::new(|| {
664 /// println!("initializing");
665 /// 92
666 /// });
667 /// println!("ready");
668 /// println!("{}", *lazy);
669 /// println!("{}", *lazy);
670 ///
671 /// // Prints:
672 /// // ready
673 /// // initializing
674 /// // 92
675 /// // 92
676 /// ```
677 pub struct Lazy<T, F = fn() -> T> {
678 cell: OnceCell<T>,
679 init: Cell<Option<F>>,
680 }
681
682 #[cfg(feature = "std")]
683 impl<T, F: RefUnwindSafe> RefUnwindSafe for Lazy<T, F> where OnceCell<T>: RefUnwindSafe {}
684
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()
688 }
689 }
690
691 impl<T, F> Lazy<T, F> {
692 /// Creates a new lazy value with the given initializing function.
693 ///
694 /// # Example
695 /// ```
696 /// # fn main() {
697 /// use once_cell::unsync::Lazy;
698 ///
699 /// let hello = "Hello, World!".to_string();
700 ///
701 /// let lazy = Lazy::new(|| hello.to_uppercase());
702 ///
703 /// assert_eq!(&*lazy, "HELLO, WORLD!");
704 /// # }
705 /// ```
706 pub const fn new(init: F) -> Lazy<T, F> {
707 Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
708 }
709
710 /// Consumes this `Lazy` returning the stored value.
711 ///
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"))
718 })
719 }
720 }
721
722 impl<T, F: FnOnce() -> T> Lazy<T, F> {
723 /// Forces the evaluation of this lazy value and returns a reference to
724 /// the result.
725 ///
726 /// This is equivalent to the `Deref` impl, but is explicit.
727 ///
728 /// # Example
729 /// ```
730 /// use once_cell::unsync::Lazy;
731 ///
732 /// let lazy = Lazy::new(|| 92);
733 ///
734 /// assert_eq!(Lazy::force(&lazy), &92);
735 /// assert_eq!(&*lazy, &92);
736 /// ```
737 pub fn force(this: &Lazy<T, F>) -> &T {
738 this.cell.get_or_init(|| match this.init.take() {
739 Some(f) => f(),
740 None => panic!("Lazy instance has previously been poisoned"),
741 })
742 }
743 }
744
745 impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
746 type Target = T;
747 fn deref(&self) -> &T {
748 Lazy::force(self)
749 }
750 }
751
752 impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
753 fn deref_mut(&mut self) -> &mut T {
754 Lazy::force(self);
755 self.cell.get_mut().unwrap_or_else(|| unreachable!())
756 }
757 }
758
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)
763 }
764 }
765 }
766
767 /// Thread-safe, blocking version of `OnceCell`.
768 #[cfg(feature = "std")]
769 pub mod sync {
770 use std::{
771 cell::Cell,
772 fmt, mem,
773 ops::{Deref, DerefMut},
774 panic::RefUnwindSafe,
775 };
776
777 use crate::{imp::OnceCell as Imp, take_unchecked};
778
779 /// A thread-safe cell which can be written to only once.
780 ///
781 /// `OnceCell` provides `&` references to the contents without RAII guards.
782 ///
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
787 /// effects of `f`.
788 ///
789 /// # Example
790 /// ```
791 /// use once_cell::sync::OnceCell;
792 ///
793 /// static CELL: OnceCell<String> = OnceCell::new();
794 /// assert!(CELL.get().is_none());
795 ///
796 /// std::thread::spawn(|| {
797 /// let value: &String = CELL.get_or_init(|| {
798 /// "Hello, World!".to_string()
799 /// });
800 /// assert_eq!(value, "Hello, World!");
801 /// }).join().unwrap();
802 ///
803 /// let value: Option<&String> = CELL.get();
804 /// assert!(value.is_some());
805 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
806 /// ```
807 pub struct OnceCell<T>(Imp<T>);
808
809 impl<T> Default for OnceCell<T> {
810 fn default() -> OnceCell<T> {
811 OnceCell::new()
812 }
813 }
814
815 impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
816 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
817 match self.get() {
818 Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
819 None => f.write_str("OnceCell(Uninit)"),
820 }
821 }
822 }
823
824 impl<T: Clone> Clone for OnceCell<T> {
825 fn clone(&self) -> OnceCell<T> {
826 match self.get() {
827 Some(value) => Self::with_value(value.clone()),
828 None => Self::new(),
829 }
830 }
831
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(),
836 }
837 }
838 }
839
840 impl<T> From<T> for OnceCell<T> {
841 fn from(value: T) -> Self {
842 Self::with_value(value)
843 }
844 }
845
846 impl<T: PartialEq> PartialEq for OnceCell<T> {
847 fn eq(&self, other: &OnceCell<T>) -> bool {
848 self.get() == other.get()
849 }
850 }
851
852 impl<T: Eq> Eq for OnceCell<T> {}
853
854 impl<T> OnceCell<T> {
855 /// Creates a new empty cell.
856 pub const fn new() -> OnceCell<T> {
857 OnceCell(Imp::new())
858 }
859
860 /// Creates a new initialized cell.
861 pub const fn with_value(value: T) -> OnceCell<T> {
862 OnceCell(Imp::with_value(value))
863 }
864
865 /// Gets the reference to the underlying value.
866 ///
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() })
873 } else {
874 None
875 }
876 }
877
878 /// Gets the reference to the underlying value, blocking the current
879 /// thread until it is set.
880 ///
881 /// ```
882 /// use once_cell::sync::OnceCell;
883 ///
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()
888 /// });
889 ///
890 /// // Returns immediately, but might return None.
891 /// let _value_or_none = cell.get();
892 ///
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();;
897 /// ```
898 pub fn wait(&self) -> &T {
899 if !self.0.is_initialized() {
900 self.0.wait()
901 }
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() }
906 }
907
908 /// Gets the mutable reference to the underlying value.
909 ///
910 /// Returns `None` if the cell is empty.
911 ///
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:
915 ///
916 /// ```
917 /// use once_cell::sync::OnceCell;
918 ///
919 /// let mut cell: OnceCell<u32> = OnceCell::new();
920 /// cell.set(92).unwrap();
921 /// cell = OnceCell::new();
922 /// ```
923 pub fn get_mut(&mut self) -> Option<&mut T> {
924 self.0.get_mut()
925 }
926
927 /// Get the reference to the underlying value, without checking if the
928 /// cell is initialized.
929 ///
930 /// # Safety
931 ///
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()
936 }
937
938 /// Sets the contents of this cell to `value`.
939 ///
940 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
941 /// full.
942 ///
943 /// # Example
944 ///
945 /// ```
946 /// use once_cell::sync::OnceCell;
947 ///
948 /// static CELL: OnceCell<i32> = OnceCell::new();
949 ///
950 /// fn main() {
951 /// assert!(CELL.get().is_none());
952 ///
953 /// std::thread::spawn(|| {
954 /// assert_eq!(CELL.set(92), Ok(()));
955 /// }).join().unwrap();
956 ///
957 /// assert_eq!(CELL.set(62), Err(62));
958 /// assert_eq!(CELL.get(), Some(&92));
959 /// }
960 /// ```
961 pub fn set(&self, value: T) -> Result<(), T> {
962 match self.try_insert(value) {
963 Ok(_) => Ok(()),
964 Err((_, value)) => Err(value),
965 }
966 }
967
968 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
969 ///
970 /// # Example
971 ///
972 /// ```
973 /// use once_cell::unsync::OnceCell;
974 ///
975 /// let cell = OnceCell::new();
976 /// assert!(cell.get().is_none());
977 ///
978 /// assert_eq!(cell.try_insert(92), Ok(&92));
979 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
980 ///
981 /// assert!(cell.get().is_some());
982 /// ```
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) });
986 match value {
987 None => Ok(res),
988 Some(value) => Err((res, value)),
989 }
990 }
991
992 /// Gets the contents of the cell, initializing it with `f` if the cell
993 /// was empty.
994 ///
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.
998 ///
999 /// # Panics
1000 ///
1001 /// If `f` panics, the panic is propagated to the caller, and the cell
1002 /// remains uninitialized.
1003 ///
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.
1007 ///
1008 /// # Example
1009 /// ```
1010 /// use once_cell::sync::OnceCell;
1011 ///
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);
1017 /// ```
1018 pub fn get_or_init<F>(&self, f: F) -> &T
1019 where
1020 F: FnOnce() -> T,
1021 {
1022 enum Void {}
1023 match self.get_or_try_init(|| Ok::<T, Void>(f())) {
1024 Ok(val) => val,
1025 Err(void) => match void {},
1026 }
1027 }
1028
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.
1032 ///
1033 /// # Panics
1034 ///
1035 /// If `f` panics, the panic is propagated to the caller, and
1036 /// the cell remains uninitialized.
1037 ///
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.
1041 ///
1042 /// # Example
1043 /// ```
1044 /// use once_cell::sync::OnceCell;
1045 ///
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, ()> {
1050 /// Ok(92)
1051 /// });
1052 /// assert_eq!(value, Ok(&92));
1053 /// assert_eq!(cell.get(), Some(&92))
1054 /// ```
1055 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
1056 where
1057 F: FnOnce() -> Result<T, E>,
1058 {
1059 // Fast path check
1060 if let Some(value) = self.get() {
1061 return Ok(value);
1062 }
1063 self.0.initialize(f)?;
1064
1065 // Safe b/c value is initialized.
1066 debug_assert!(self.0.is_initialized());
1067 Ok(unsafe { self.get_unchecked() })
1068 }
1069
1070 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
1071 ///
1072 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
1073 ///
1074 /// # Examples
1075 ///
1076 /// ```
1077 /// use once_cell::sync::OnceCell;
1078 ///
1079 /// let mut cell: OnceCell<String> = OnceCell::new();
1080 /// assert_eq!(cell.take(), None);
1081 ///
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);
1086 /// ```
1087 ///
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:
1091 ///
1092 /// ```
1093 /// use once_cell::sync::OnceCell;
1094 ///
1095 /// let mut cell: OnceCell<u32> = OnceCell::new();
1096 /// cell.set(92).unwrap();
1097 /// cell = OnceCell::new();
1098 /// ```
1099 pub fn take(&mut self) -> Option<T> {
1100 mem::replace(self, Self::default()).into_inner()
1101 }
1102
1103 /// Consumes the `OnceCell`, returning the wrapped value. Returns
1104 /// `None` if the cell was empty.
1105 ///
1106 /// # Examples
1107 ///
1108 /// ```
1109 /// use once_cell::sync::OnceCell;
1110 ///
1111 /// let cell: OnceCell<String> = OnceCell::new();
1112 /// assert_eq!(cell.into_inner(), None);
1113 ///
1114 /// let cell = OnceCell::new();
1115 /// cell.set("hello".to_string()).unwrap();
1116 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
1117 /// ```
1118 pub fn into_inner(self) -> Option<T> {
1119 self.0.into_inner()
1120 }
1121 }
1122
1123 /// A value which is initialized on the first access.
1124 ///
1125 /// This type is thread-safe and can be used in statics.
1126 ///
1127 /// # Example
1128 ///
1129 /// ```
1130 /// use std::collections::HashMap;
1131 ///
1132 /// use once_cell::sync::Lazy;
1133 ///
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());
1139 /// m
1140 /// });
1141 ///
1142 /// fn main() {
1143 /// println!("ready");
1144 /// std::thread::spawn(|| {
1145 /// println!("{:?}", HASHMAP.get(&13));
1146 /// }).join().unwrap();
1147 /// println!("{:?}", HASHMAP.get(&74));
1148 ///
1149 /// // Prints:
1150 /// // ready
1151 /// // initializing
1152 /// // Some("Spica")
1153 /// // Some("Hoyten")
1154 /// }
1155 /// ```
1156 pub struct Lazy<T, F = fn() -> T> {
1157 cell: OnceCell<T>,
1158 init: Cell<Option<F>>,
1159 }
1160
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()
1164 }
1165 }
1166
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.
1173
1174 #[cfg(feature = "std")]
1175 impl<T, F: RefUnwindSafe> RefUnwindSafe for Lazy<T, F> where OnceCell<T>: RefUnwindSafe {}
1176
1177 impl<T, F> Lazy<T, F> {
1178 /// Creates a new lazy value with the given initializing
1179 /// function.
1180 pub const fn new(f: F) -> Lazy<T, F> {
1181 Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1182 }
1183
1184 /// Consumes this `Lazy` returning the stored value.
1185 ///
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"))
1192 })
1193 }
1194 }
1195
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.
1200 ///
1201 /// # Example
1202 /// ```
1203 /// use once_cell::sync::Lazy;
1204 ///
1205 /// let lazy = Lazy::new(|| 92);
1206 ///
1207 /// assert_eq!(Lazy::force(&lazy), &92);
1208 /// assert_eq!(&*lazy, &92);
1209 /// ```
1210 pub fn force(this: &Lazy<T, F>) -> &T {
1211 this.cell.get_or_init(|| match this.init.take() {
1212 Some(f) => f(),
1213 None => panic!("Lazy instance has previously been poisoned"),
1214 })
1215 }
1216 }
1217
1218 impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
1219 type Target = T;
1220 fn deref(&self) -> &T {
1221 Lazy::force(self)
1222 }
1223 }
1224
1225 impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
1226 fn deref_mut(&mut self) -> &mut T {
1227 Lazy::force(self);
1228 self.cell.get_mut().unwrap_or_else(|| unreachable!())
1229 }
1230 }
1231
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)
1236 }
1237 }
1238
1239 /// ```compile_fail
1240 /// struct S(*mut ());
1241 /// unsafe impl Sync for S {}
1242 ///
1243 /// fn share<T: Sync>(_: &T) {}
1244 /// share(&once_cell::sync::OnceCell::<S>::new());
1245 /// ```
1246 ///
1247 /// ```compile_fail
1248 /// struct S(*mut ());
1249 /// unsafe impl Sync for S {}
1250 ///
1251 /// fn share<T: Sync>(_: &T) {}
1252 /// share(&once_cell::sync::Lazy::<S>::new(|| unimplemented!()));
1253 /// ```
1254 fn _dummy() {}
1255 }
1256
1257 #[cfg(feature = "race")]
1258 pub mod race;
1259
1260 #[cfg(feature = "std")]
1261 unsafe fn take_unchecked<T>(val: &mut Option<T>) -> T {
1262 match val.take() {
1263 Some(it) => it,
1264 None => {
1265 debug_assert!(false);
1266 std::hint::unreachable_unchecked()
1267 }
1268 }
1269 }