Coverage Report

Created: 2026-04-09 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/once_cell-1.17.0/src/lib.rs
Line
Count
Source
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> {
397
0
        fn default() -> Self {
398
0
            Self::new()
399
0
        }
400
    }
401
402
    impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
403
0
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
404
0
            match self.get() {
405
0
                Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
406
0
                None => f.write_str("OnceCell(Uninit)"),
407
            }
408
0
        }
409
    }
410
411
    impl<T: Clone> Clone for OnceCell<T> {
412
0
        fn clone(&self) -> OnceCell<T> {
413
0
            match self.get() {
414
0
                Some(value) => OnceCell::with_value(value.clone()),
415
0
                None => OnceCell::new(),
416
            }
417
0
        }
418
419
0
        fn clone_from(&mut self, source: &Self) {
420
0
            match (self.get_mut(), source.get()) {
421
0
                (Some(this), Some(source)) => this.clone_from(source),
422
0
                _ => *self = source.clone(),
423
            }
424
0
        }
425
    }
426
427
    impl<T: PartialEq> PartialEq for OnceCell<T> {
428
0
        fn eq(&self, other: &Self) -> bool {
429
0
            self.get() == other.get()
430
0
        }
431
    }
432
433
    impl<T: Eq> Eq for OnceCell<T> {}
434
435
    impl<T> From<T> for OnceCell<T> {
436
0
        fn from(value: T) -> Self {
437
0
            OnceCell::with_value(value)
438
0
        }
439
    }
440
441
    impl<T> OnceCell<T> {
442
        /// Creates a new empty cell.
443
0
        pub const fn new() -> OnceCell<T> {
444
0
            OnceCell { inner: UnsafeCell::new(None) }
445
0
        }
446
447
        /// Creates a new initialized cell.
448
0
        pub const fn with_value(value: T) -> OnceCell<T> {
449
0
            OnceCell { inner: UnsafeCell::new(Some(value)) }
450
0
        }
451
452
        /// Gets a reference to the underlying value.
453
        ///
454
        /// Returns `None` if the cell is empty.
455
        #[inline]
456
0
        pub fn get(&self) -> Option<&T> {
457
            // Safe due to `inner`'s invariant
458
0
            unsafe { &*self.inner.get() }.as_ref()
459
0
        }
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]
478
0
        pub fn get_mut(&mut self) -> Option<&mut T> {
479
            // Safe because we have unique access
480
0
            unsafe { &mut *self.inner.get() }.as_mut()
481
0
        }
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
        /// ```
500
0
        pub fn set(&self, value: T) -> Result<(), T> {
501
0
            match self.try_insert(value) {
502
0
                Ok(_) => Ok(()),
503
0
                Err((_, value)) => Err(value),
504
            }
505
0
        }
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
        /// ```
521
0
        pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
522
0
            if let Some(old) = self.get() {
523
0
                return Err((old, value));
524
0
            }
525
526
0
            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
0
            *slot = Some(value);
532
0
            Ok(unsafe { unwrap_unchecked(slot.as_ref()) })
533
0
        }
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
        /// ```
556
0
        pub fn get_or_init<F>(&self, f: F) -> &T
557
0
        where
558
0
            F: FnOnce() -> T,
559
        {
560
            enum Void {}
561
0
            match self.get_or_try_init(|| Ok::<T, Void>(f())) {
562
0
                Ok(val) => val,
563
                Err(void) => match void {},
564
            }
565
0
        }
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
        /// ```
592
0
        pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
593
0
        where
594
0
            F: FnOnce() -> Result<T, E>,
595
        {
596
0
            if let Some(val) = self.get() {
597
0
                return Ok(val);
598
0
            }
599
0
            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
0
            assert!(self.set(val).is_ok(), "reentrant init");
605
0
            Ok(unsafe { unwrap_unchecked(self.get()) })
606
0
        }
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
        /// ```
637
0
        pub fn take(&mut self) -> Option<T> {
638
0
            mem::replace(self, Self::default()).into_inner()
639
0
        }
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
        /// ```
657
0
        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
0
            self.inner.into_inner()
661
0
        }
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> {
692
0
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
693
0
            f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
694
0
        }
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
        /// ```
712
0
        pub const fn new(init: F) -> Lazy<T, F> {
713
0
            Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
714
0
        }
715
716
        /// Consumes this `Lazy` returning the stored value.
717
        ///
718
        /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
719
0
        pub fn into_value(this: Lazy<T, F>) -> Result<T, F> {
720
0
            let cell = this.cell;
721
0
            let init = this.init;
722
0
            cell.into_inner().ok_or_else(|| {
723
0
                init.take().unwrap_or_else(|| panic!("Lazy instance has previously been poisoned"))
724
0
            })
725
0
        }
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
        /// ```
743
0
        pub fn force(this: &Lazy<T, F>) -> &T {
744
0
            this.cell.get_or_init(|| match this.init.take() {
745
0
                Some(f) => f(),
746
0
                None => panic!("Lazy instance has previously been poisoned"),
747
0
            })
748
0
        }
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
        /// ```
764
0
        pub fn force_mut(this: &mut Lazy<T, F>) -> &mut T {
765
0
            Self::force(this);
766
0
            Self::get_mut(this).unwrap_or_else(|| unreachable!())
767
0
        }
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
        /// ```
782
0
        pub fn get(this: &Lazy<T, F>) -> Option<&T> {
783
0
            this.cell.get()
784
0
        }
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
        /// ```
799
0
        pub fn get_mut(this: &mut Lazy<T, F>) -> Option<&mut T> {
800
0
            this.cell.get_mut()
801
0
        }
802
    }
803
804
    impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
805
        type Target = T;
806
0
        fn deref(&self) -> &T {
807
0
            Lazy::force(self)
808
0
        }
809
    }
810
811
    impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
812
0
        fn deref_mut(&mut self) -> &mut T {
813
0
            Lazy::force(self);
814
0
            self.cell.get_mut().unwrap_or_else(|| unreachable!())
815
0
        }
816
    }
817
818
    impl<T: Default> Default for Lazy<T> {
819
        /// Creates a new lazy value using `Default` as the initializing function.
820
0
        fn default() -> Lazy<T> {
821
0
            Lazy::new(T::default)
822
0
        }
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> {
869
0
        fn default() -> OnceCell<T> {
870
0
            OnceCell::new()
871
0
        }
872
    }
873
874
    impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
875
0
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
876
0
            match self.get() {
877
0
                Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
878
0
                None => f.write_str("OnceCell(Uninit)"),
879
            }
880
0
        }
881
    }
882
883
    impl<T: Clone> Clone for OnceCell<T> {
884
0
        fn clone(&self) -> OnceCell<T> {
885
0
            match self.get() {
886
0
                Some(value) => Self::with_value(value.clone()),
887
0
                None => Self::new(),
888
            }
889
0
        }
890
891
0
        fn clone_from(&mut self, source: &Self) {
892
0
            match (self.get_mut(), source.get()) {
893
0
                (Some(this), Some(source)) => this.clone_from(source),
894
0
                _ => *self = source.clone(),
895
            }
896
0
        }
897
    }
898
899
    impl<T> From<T> for OnceCell<T> {
900
0
        fn from(value: T) -> Self {
901
0
            Self::with_value(value)
902
0
        }
903
    }
904
905
    impl<T: PartialEq> PartialEq for OnceCell<T> {
906
0
        fn eq(&self, other: &OnceCell<T>) -> bool {
907
0
            self.get() == other.get()
908
0
        }
909
    }
910
911
    impl<T: Eq> Eq for OnceCell<T> {}
912
913
    impl<T> OnceCell<T> {
914
        /// Creates a new empty cell.
915
0
        pub const fn new() -> OnceCell<T> {
916
0
            OnceCell(Imp::new())
917
0
        }
918
919
        /// Creates a new initialized cell.
920
0
        pub const fn with_value(value: T) -> OnceCell<T> {
921
0
            OnceCell(Imp::with_value(value))
922
0
        }
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.
928
17.7k
        pub fn get(&self) -> Option<&T> {
929
17.7k
            if self.0.is_initialized() {
930
                // Safe b/c value is initialized.
931
0
                Some(unsafe { self.get_unchecked() })
932
            } else {
933
17.7k
                None
934
            }
935
17.7k
        }
<once_cell::sync::OnceCell<alloc::string::String>>::get
Line
Count
Source
928
17.7k
        pub fn get(&self) -> Option<&T> {
929
17.7k
            if self.0.is_initialized() {
930
                // Safe b/c value is initialized.
931
0
                Some(unsafe { self.get_unchecked() })
932
            } else {
933
17.7k
                None
934
            }
935
17.7k
        }
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::get
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")]
958
0
        pub fn wait(&self) -> &T {
959
0
            if !self.0.is_initialized() {
960
0
                self.0.wait()
961
0
            }
962
0
            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
0
            unsafe { self.get_unchecked() }
966
0
        }
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]
984
0
        pub fn get_mut(&mut self) -> Option<&mut T> {
985
0
            self.0.get_mut()
986
0
        }
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]
996
0
        pub unsafe fn get_unchecked(&self) -> &T {
997
0
            self.0.get_unchecked()
998
0
        }
Unexecuted instantiation: <once_cell::sync::OnceCell<alloc::string::String>>::get_unchecked
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::get_unchecked
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
        /// ```
1023
0
        pub fn set(&self, value: T) -> Result<(), T> {
1024
0
            match self.try_insert(value) {
1025
0
                Ok(_) => Ok(()),
1026
0
                Err((_, value)) => Err(value),
1027
            }
1028
0
        }
Unexecuted instantiation: <once_cell::sync::OnceCell<alloc::string::String>>::set
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::set
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
        /// ```
1045
0
        pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
1046
0
            let mut value = Some(value);
1047
0
            let res = self.get_or_init(|| unsafe { unwrap_unchecked(value.take()) });
Unexecuted instantiation: <once_cell::sync::OnceCell<alloc::string::String>>::try_insert::{closure#0}
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::try_insert::{closure#0}
1048
0
            match value {
1049
0
                None => Ok(res),
1050
0
                Some(value) => Err((res, value)),
1051
            }
1052
0
        }
Unexecuted instantiation: <once_cell::sync::OnceCell<alloc::string::String>>::try_insert
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::try_insert
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
        /// ```
1080
0
        pub fn get_or_init<F>(&self, f: F) -> &T
1081
0
        where
1082
0
            F: FnOnce() -> T,
1083
        {
1084
            enum Void {}
1085
0
            match self.get_or_try_init(|| Ok::<T, Void>(f())) {
Unexecuted instantiation: <once_cell::sync::OnceCell<alloc::string::String>>::get_or_init::<<once_cell::sync::OnceCell<alloc::string::String>>::try_insert::{closure#0}>::{closure#0}
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::get_or_init::<_>::{closure#0}
1086
0
                Ok(val) => val,
1087
                Err(void) => match void {},
1088
            }
1089
0
        }
Unexecuted instantiation: <once_cell::sync::OnceCell<alloc::string::String>>::get_or_init::<<once_cell::sync::OnceCell<alloc::string::String>>::try_insert::{closure#0}>
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::get_or_init::<_>
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
        /// ```
1117
0
        pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
1118
0
        where
1119
0
            F: FnOnce() -> Result<T, E>,
1120
        {
1121
            // Fast path check
1122
0
            if let Some(value) = self.get() {
1123
0
                return Ok(value);
1124
0
            }
1125
1126
0
            self.0.initialize(f)?;
1127
1128
            // Safe b/c value is initialized.
1129
0
            debug_assert!(self.0.is_initialized());
1130
0
            Ok(unsafe { self.get_unchecked() })
1131
0
        }
Unexecuted instantiation: <once_cell::sync::OnceCell<alloc::string::String>>::get_or_try_init::<<once_cell::sync::OnceCell<alloc::string::String>>::get_or_init<<once_cell::sync::OnceCell<alloc::string::String>>::try_insert::{closure#0}>::{closure#0}, <once_cell::sync::OnceCell<_>>::get_or_init::Void>
Unexecuted instantiation: <once_cell::sync::OnceCell<_>>::get_or_try_init::<_, _>
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
        /// ```
1162
0
        pub fn take(&mut self) -> Option<T> {
1163
0
            mem::replace(self, Self::default()).into_inner()
1164
0
        }
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]
1182
0
        pub fn into_inner(self) -> Option<T> {
1183
0
            self.0.into_inner()
1184
0
        }
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> {
1226
0
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1227
0
            f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
1228
0
        }
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.
1243
0
        pub const fn new(f: F) -> Lazy<T, F> {
1244
0
            Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1245
0
        }
1246
1247
        /// Consumes this `Lazy` returning the stored value.
1248
        ///
1249
        /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
1250
0
        pub fn into_value(this: Lazy<T, F>) -> Result<T, F> {
1251
0
            let cell = this.cell;
1252
0
            let init = this.init;
1253
0
            cell.into_inner().ok_or_else(|| {
1254
0
                init.take().unwrap_or_else(|| panic!("Lazy instance has previously been poisoned"))
1255
0
            })
1256
0
        }
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
        /// ```
1273
0
        pub fn force(this: &Lazy<T, F>) -> &T {
1274
0
            this.cell.get_or_init(|| match this.init.take() {
1275
0
                Some(f) => f(),
1276
0
                None => panic!("Lazy instance has previously been poisoned"),
1277
0
            })
1278
0
        }
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
        /// ```
1292
0
        pub fn force_mut(this: &mut Lazy<T, F>) -> &mut T {
1293
0
            Self::force(this);
1294
0
            Self::get_mut(this).unwrap_or_else(|| unreachable!())
1295
0
        }
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
        /// ```
1310
0
        pub fn get(this: &Lazy<T, F>) -> Option<&T> {
1311
0
            this.cell.get()
1312
0
        }
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
        /// ```
1327
0
        pub fn get_mut(this: &mut Lazy<T, F>) -> Option<&mut T> {
1328
0
            this.cell.get_mut()
1329
0
        }
1330
    }
1331
1332
    impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
1333
        type Target = T;
1334
0
        fn deref(&self) -> &T {
1335
0
            Lazy::force(self)
1336
0
        }
1337
    }
1338
1339
    impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
1340
0
        fn deref_mut(&mut self) -> &mut T {
1341
0
            Lazy::force(self);
1342
0
            self.cell.get_mut().unwrap_or_else(|| unreachable!())
1343
0
        }
1344
    }
1345
1346
    impl<T: Default> Default for Lazy<T> {
1347
        /// Creates a new lazy value using `Default` as the initializing function.
1348
0
        fn default() -> Lazy<T> {
1349
0
            Lazy::new(T::default)
1350
0
        }
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
    /// ```
1368
0
    fn _dummy() {}
1369
}
1370
1371
#[cfg(feature = "race")]
1372
pub mod race;
1373
1374
// Remove once MSRV is at least 1.58.
1375
#[inline]
1376
0
unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1377
0
    match val {
1378
0
        Some(value) => value,
1379
        None => {
1380
0
            debug_assert!(false);
1381
0
            core::hint::unreachable_unchecked()
1382
        }
1383
    }
1384
0
}
Unexecuted instantiation: once_cell::unwrap_unchecked::<<once_cell::sync::OnceCell<alloc::string::String>>::get_or_init<<once_cell::sync::OnceCell<alloc::string::String>>::try_insert::{closure#0}>::{closure#0}>
Unexecuted instantiation: once_cell::unwrap_unchecked::<alloc::string::String>
Unexecuted instantiation: once_cell::unwrap_unchecked::<&alloc::string::String>
Unexecuted instantiation: once_cell::unwrap_unchecked::<_>