]> git.proxmox.com Git - rustc.git/blob - vendor/once_cell/src/lib.rs
New upstream version 1.66.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.56.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 panic::{RefUnwindSafe, UnwindSafe},
352 };
353
354 /// A cell which can be written to only once. It is not thread safe.
355 ///
356 /// Unlike [`std::cell::RefCell`], a `OnceCell` provides simple `&`
357 /// references to the contents.
358 ///
359 /// [`std::cell::RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
360 ///
361 /// # Example
362 /// ```
363 /// use once_cell::unsync::OnceCell;
364 ///
365 /// let cell = OnceCell::new();
366 /// assert!(cell.get().is_none());
367 ///
368 /// let value: &String = cell.get_or_init(|| {
369 /// "Hello, World!".to_string()
370 /// });
371 /// assert_eq!(value, "Hello, World!");
372 /// assert!(cell.get().is_some());
373 /// ```
374 pub struct OnceCell<T> {
375 // Invariant: written to at most once.
376 inner: UnsafeCell<Option<T>>,
377 }
378
379 // Similarly to a `Sync` bound on `sync::OnceCell`, we can use
380 // `&unsync::OnceCell` to sneak a `T` through `catch_unwind`,
381 // by initializing the cell in closure and extracting the value in the
382 // `Drop`.
383 impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceCell<T> {}
384 impl<T: UnwindSafe> UnwindSafe for OnceCell<T> {}
385
386 impl<T> Default for OnceCell<T> {
387 fn default() -> Self {
388 Self::new()
389 }
390 }
391
392 impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
393 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
394 match self.get() {
395 Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
396 None => f.write_str("OnceCell(Uninit)"),
397 }
398 }
399 }
400
401 impl<T: Clone> Clone for OnceCell<T> {
402 fn clone(&self) -> OnceCell<T> {
403 match self.get() {
404 Some(value) => OnceCell::with_value(value.clone()),
405 None => OnceCell::new(),
406 }
407 }
408
409 fn clone_from(&mut self, source: &Self) {
410 match (self.get_mut(), source.get()) {
411 (Some(this), Some(source)) => this.clone_from(source),
412 _ => *self = source.clone(),
413 }
414 }
415 }
416
417 impl<T: PartialEq> PartialEq for OnceCell<T> {
418 fn eq(&self, other: &Self) -> bool {
419 self.get() == other.get()
420 }
421 }
422
423 impl<T: Eq> Eq for OnceCell<T> {}
424
425 impl<T> From<T> for OnceCell<T> {
426 fn from(value: T) -> Self {
427 OnceCell::with_value(value)
428 }
429 }
430
431 impl<T> OnceCell<T> {
432 /// Creates a new empty cell.
433 pub const fn new() -> OnceCell<T> {
434 OnceCell { inner: UnsafeCell::new(None) }
435 }
436
437 /// Creates a new initialized cell.
438 pub const fn with_value(value: T) -> OnceCell<T> {
439 OnceCell { inner: UnsafeCell::new(Some(value)) }
440 }
441
442 /// Gets a reference to the underlying value.
443 ///
444 /// Returns `None` if the cell is empty.
445 pub fn get(&self) -> Option<&T> {
446 // Safe due to `inner`'s invariant
447 unsafe { &*self.inner.get() }.as_ref()
448 }
449
450 /// Gets a mutable reference to the underlying value.
451 ///
452 /// Returns `None` if the cell is empty.
453 ///
454 /// This method is allowed to violate the invariant of writing to a `OnceCell`
455 /// at most once because it requires `&mut` access to `self`. As with all
456 /// interior mutability, `&mut` access permits arbitrary modification:
457 ///
458 /// ```
459 /// use once_cell::unsync::OnceCell;
460 ///
461 /// let mut cell: OnceCell<u32> = OnceCell::new();
462 /// cell.set(92).unwrap();
463 /// *cell.get_mut().unwrap() = 93;
464 /// assert_eq!(cell.get(), Some(&93));
465 /// ```
466 pub fn get_mut(&mut self) -> Option<&mut T> {
467 // Safe because we have unique access
468 unsafe { &mut *self.inner.get() }.as_mut()
469 }
470
471 /// Sets the contents of this cell to `value`.
472 ///
473 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
474 /// full.
475 ///
476 /// # Example
477 /// ```
478 /// use once_cell::unsync::OnceCell;
479 ///
480 /// let cell = OnceCell::new();
481 /// assert!(cell.get().is_none());
482 ///
483 /// assert_eq!(cell.set(92), Ok(()));
484 /// assert_eq!(cell.set(62), Err(62));
485 ///
486 /// assert!(cell.get().is_some());
487 /// ```
488 pub fn set(&self, value: T) -> Result<(), T> {
489 match self.try_insert(value) {
490 Ok(_) => Ok(()),
491 Err((_, value)) => Err(value),
492 }
493 }
494
495 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
496 ///
497 /// # Example
498 /// ```
499 /// use once_cell::unsync::OnceCell;
500 ///
501 /// let cell = OnceCell::new();
502 /// assert!(cell.get().is_none());
503 ///
504 /// assert_eq!(cell.try_insert(92), Ok(&92));
505 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
506 ///
507 /// assert!(cell.get().is_some());
508 /// ```
509 pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
510 if let Some(old) = self.get() {
511 return Err((old, value));
512 }
513 let slot = unsafe { &mut *self.inner.get() };
514 // This is the only place where we set the slot, no races
515 // due to reentrancy/concurrency are possible, and we've
516 // checked that slot is currently `None`, so this write
517 // maintains the `inner`'s invariant.
518 *slot = Some(value);
519 Ok(match &*slot {
520 Some(value) => value,
521 None => unsafe { hint::unreachable_unchecked() },
522 })
523 }
524
525 /// Gets the contents of the cell, initializing it with `f`
526 /// if the cell was empty.
527 ///
528 /// # Panics
529 ///
530 /// If `f` panics, the panic is propagated to the caller, and the cell
531 /// remains uninitialized.
532 ///
533 /// It is an error to reentrantly initialize the cell from `f`. Doing
534 /// so results in a panic.
535 ///
536 /// # Example
537 /// ```
538 /// use once_cell::unsync::OnceCell;
539 ///
540 /// let cell = OnceCell::new();
541 /// let value = cell.get_or_init(|| 92);
542 /// assert_eq!(value, &92);
543 /// let value = cell.get_or_init(|| unreachable!());
544 /// assert_eq!(value, &92);
545 /// ```
546 pub fn get_or_init<F>(&self, f: F) -> &T
547 where
548 F: FnOnce() -> T,
549 {
550 enum Void {}
551 match self.get_or_try_init(|| Ok::<T, Void>(f())) {
552 Ok(val) => val,
553 Err(void) => match void {},
554 }
555 }
556
557 /// Gets the contents of the cell, initializing it with `f` if
558 /// the cell was empty. If the cell was empty and `f` failed, an
559 /// error is returned.
560 ///
561 /// # Panics
562 ///
563 /// If `f` panics, the panic is propagated to the caller, and the cell
564 /// remains uninitialized.
565 ///
566 /// It is an error to reentrantly initialize the cell from `f`. Doing
567 /// so results in a panic.
568 ///
569 /// # Example
570 /// ```
571 /// use once_cell::unsync::OnceCell;
572 ///
573 /// let cell = OnceCell::new();
574 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
575 /// assert!(cell.get().is_none());
576 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
577 /// Ok(92)
578 /// });
579 /// assert_eq!(value, Ok(&92));
580 /// assert_eq!(cell.get(), Some(&92))
581 /// ```
582 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
583 where
584 F: FnOnce() -> Result<T, E>,
585 {
586 if let Some(val) = self.get() {
587 return Ok(val);
588 }
589 let val = f()?;
590 // Note that *some* forms of reentrant initialization might lead to
591 // UB (see `reentrant_init` test). I believe that just removing this
592 // `assert`, while keeping `set/get` would be sound, but it seems
593 // better to panic, rather than to silently use an old value.
594 assert!(self.set(val).is_ok(), "reentrant init");
595 Ok(self.get().unwrap())
596 }
597
598 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
599 ///
600 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
601 ///
602 /// # Examples
603 ///
604 /// ```
605 /// use once_cell::unsync::OnceCell;
606 ///
607 /// let mut cell: OnceCell<String> = OnceCell::new();
608 /// assert_eq!(cell.take(), None);
609 ///
610 /// let mut cell = OnceCell::new();
611 /// cell.set("hello".to_string()).unwrap();
612 /// assert_eq!(cell.take(), Some("hello".to_string()));
613 /// assert_eq!(cell.get(), None);
614 /// ```
615 ///
616 /// This method is allowed to violate the invariant of writing to a `OnceCell`
617 /// at most once because it requires `&mut` access to `self`. As with all
618 /// interior mutability, `&mut` access permits arbitrary modification:
619 ///
620 /// ```
621 /// use once_cell::unsync::OnceCell;
622 ///
623 /// let mut cell: OnceCell<u32> = OnceCell::new();
624 /// cell.set(92).unwrap();
625 /// cell = OnceCell::new();
626 /// ```
627 pub fn take(&mut self) -> Option<T> {
628 mem::replace(self, Self::default()).into_inner()
629 }
630
631 /// Consumes the `OnceCell`, returning the wrapped value.
632 ///
633 /// Returns `None` if the cell was empty.
634 ///
635 /// # Examples
636 ///
637 /// ```
638 /// use once_cell::unsync::OnceCell;
639 ///
640 /// let cell: OnceCell<String> = OnceCell::new();
641 /// assert_eq!(cell.into_inner(), None);
642 ///
643 /// let cell = OnceCell::new();
644 /// cell.set("hello".to_string()).unwrap();
645 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
646 /// ```
647 pub fn into_inner(self) -> Option<T> {
648 // Because `into_inner` takes `self` by value, the compiler statically verifies
649 // that it is not currently borrowed. So it is safe to move out `Option<T>`.
650 self.inner.into_inner()
651 }
652 }
653
654 /// A value which is initialized on the first access.
655 ///
656 /// # Example
657 /// ```
658 /// use once_cell::unsync::Lazy;
659 ///
660 /// let lazy: Lazy<i32> = Lazy::new(|| {
661 /// println!("initializing");
662 /// 92
663 /// });
664 /// println!("ready");
665 /// println!("{}", *lazy);
666 /// println!("{}", *lazy);
667 ///
668 /// // Prints:
669 /// // ready
670 /// // initializing
671 /// // 92
672 /// // 92
673 /// ```
674 pub struct Lazy<T, F = fn() -> T> {
675 cell: OnceCell<T>,
676 init: Cell<Option<F>>,
677 }
678
679 impl<T, F: RefUnwindSafe> RefUnwindSafe for Lazy<T, F> where OnceCell<T>: RefUnwindSafe {}
680
681 impl<T: fmt::Debug, F> fmt::Debug for Lazy<T, F> {
682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
683 f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
684 }
685 }
686
687 impl<T, F> Lazy<T, F> {
688 /// Creates a new lazy value with the given initializing function.
689 ///
690 /// # Example
691 /// ```
692 /// # fn main() {
693 /// use once_cell::unsync::Lazy;
694 ///
695 /// let hello = "Hello, World!".to_string();
696 ///
697 /// let lazy = Lazy::new(|| hello.to_uppercase());
698 ///
699 /// assert_eq!(&*lazy, "HELLO, WORLD!");
700 /// # }
701 /// ```
702 pub const fn new(init: F) -> Lazy<T, F> {
703 Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }
704 }
705
706 /// Consumes this `Lazy` returning the stored value.
707 ///
708 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
709 pub fn into_value(this: Lazy<T, F>) -> Result<T, F> {
710 let cell = this.cell;
711 let init = this.init;
712 cell.into_inner().ok_or_else(|| {
713 init.take().unwrap_or_else(|| panic!("Lazy instance has previously been poisoned"))
714 })
715 }
716 }
717
718 impl<T, F: FnOnce() -> T> Lazy<T, F> {
719 /// Forces the evaluation of this lazy value and returns a reference to
720 /// the result.
721 ///
722 /// This is equivalent to the `Deref` impl, but is explicit.
723 ///
724 /// # Example
725 /// ```
726 /// use once_cell::unsync::Lazy;
727 ///
728 /// let lazy = Lazy::new(|| 92);
729 ///
730 /// assert_eq!(Lazy::force(&lazy), &92);
731 /// assert_eq!(&*lazy, &92);
732 /// ```
733 pub fn force(this: &Lazy<T, F>) -> &T {
734 this.cell.get_or_init(|| match this.init.take() {
735 Some(f) => f(),
736 None => panic!("Lazy instance has previously been poisoned"),
737 })
738 }
739
740 /// Forces the evaluation of this lazy value and returns a mutable reference to
741 /// the result.
742 ///
743 /// This is equivalent to the `DerefMut` impl, but is explicit.
744 ///
745 /// # Example
746 /// ```
747 /// use once_cell::unsync::Lazy;
748 ///
749 /// let mut lazy = Lazy::new(|| 92);
750 ///
751 /// assert_eq!(Lazy::force_mut(&mut lazy), &92);
752 /// assert_eq!(*lazy, 92);
753 /// ```
754 pub fn force_mut(this: &mut Lazy<T, F>) -> &mut T {
755 Self::force(this);
756 Self::get_mut(this).unwrap_or_else(|| unreachable!())
757 }
758
759 /// Gets the reference to the result of this lazy value if
760 /// it was initialized, otherwise returns `None`.
761 ///
762 /// # Example
763 /// ```
764 /// use once_cell::unsync::Lazy;
765 ///
766 /// let lazy = Lazy::new(|| 92);
767 ///
768 /// assert_eq!(Lazy::get(&lazy), None);
769 /// assert_eq!(&*lazy, &92);
770 /// assert_eq!(Lazy::get(&lazy), Some(&92));
771 /// ```
772 pub fn get(this: &Lazy<T, F>) -> Option<&T> {
773 this.cell.get()
774 }
775
776 /// Gets the mutable reference to the result of this lazy value if
777 /// it was initialized, otherwise returns `None`.
778 ///
779 /// # Example
780 /// ```
781 /// use once_cell::unsync::Lazy;
782 ///
783 /// let mut lazy = Lazy::new(|| 92);
784 ///
785 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
786 /// assert_eq!(*lazy, 92);
787 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
788 /// ```
789 pub fn get_mut(this: &mut Lazy<T, F>) -> Option<&mut T> {
790 this.cell.get_mut()
791 }
792 }
793
794 impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
795 type Target = T;
796 fn deref(&self) -> &T {
797 Lazy::force(self)
798 }
799 }
800
801 impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
802 fn deref_mut(&mut self) -> &mut T {
803 Lazy::force(self);
804 self.cell.get_mut().unwrap_or_else(|| unreachable!())
805 }
806 }
807
808 impl<T: Default> Default for Lazy<T> {
809 /// Creates a new lazy value using `Default` as the initializing function.
810 fn default() -> Lazy<T> {
811 Lazy::new(T::default)
812 }
813 }
814 }
815
816 /// Thread-safe, blocking version of `OnceCell`.
817 #[cfg(feature = "std")]
818 pub mod sync {
819 use std::{
820 cell::Cell,
821 fmt, mem,
822 ops::{Deref, DerefMut},
823 panic::RefUnwindSafe,
824 };
825
826 use crate::{imp::OnceCell as Imp, take_unchecked};
827
828 /// A thread-safe cell which can be written to only once.
829 ///
830 /// `OnceCell` provides `&` references to the contents without RAII guards.
831 ///
832 /// Reading a non-`None` value out of `OnceCell` establishes a
833 /// happens-before relationship with a corresponding write. For example, if
834 /// thread A initializes the cell with `get_or_init(f)`, and thread B
835 /// subsequently reads the result of this call, B also observes all the side
836 /// effects of `f`.
837 ///
838 /// # Example
839 /// ```
840 /// use once_cell::sync::OnceCell;
841 ///
842 /// static CELL: OnceCell<String> = OnceCell::new();
843 /// assert!(CELL.get().is_none());
844 ///
845 /// std::thread::spawn(|| {
846 /// let value: &String = CELL.get_or_init(|| {
847 /// "Hello, World!".to_string()
848 /// });
849 /// assert_eq!(value, "Hello, World!");
850 /// }).join().unwrap();
851 ///
852 /// let value: Option<&String> = CELL.get();
853 /// assert!(value.is_some());
854 /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
855 /// ```
856 pub struct OnceCell<T>(Imp<T>);
857
858 impl<T> Default for OnceCell<T> {
859 fn default() -> OnceCell<T> {
860 OnceCell::new()
861 }
862 }
863
864 impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
865 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
866 match self.get() {
867 Some(v) => f.debug_tuple("OnceCell").field(v).finish(),
868 None => f.write_str("OnceCell(Uninit)"),
869 }
870 }
871 }
872
873 impl<T: Clone> Clone for OnceCell<T> {
874 fn clone(&self) -> OnceCell<T> {
875 match self.get() {
876 Some(value) => Self::with_value(value.clone()),
877 None => Self::new(),
878 }
879 }
880
881 fn clone_from(&mut self, source: &Self) {
882 match (self.get_mut(), source.get()) {
883 (Some(this), Some(source)) => this.clone_from(source),
884 _ => *self = source.clone(),
885 }
886 }
887 }
888
889 impl<T> From<T> for OnceCell<T> {
890 fn from(value: T) -> Self {
891 Self::with_value(value)
892 }
893 }
894
895 impl<T: PartialEq> PartialEq for OnceCell<T> {
896 fn eq(&self, other: &OnceCell<T>) -> bool {
897 self.get() == other.get()
898 }
899 }
900
901 impl<T: Eq> Eq for OnceCell<T> {}
902
903 impl<T> OnceCell<T> {
904 /// Creates a new empty cell.
905 pub const fn new() -> OnceCell<T> {
906 OnceCell(Imp::new())
907 }
908
909 /// Creates a new initialized cell.
910 pub const fn with_value(value: T) -> OnceCell<T> {
911 OnceCell(Imp::with_value(value))
912 }
913
914 /// Gets the reference to the underlying value.
915 ///
916 /// Returns `None` if the cell is empty, or being initialized. This
917 /// method never blocks.
918 pub fn get(&self) -> Option<&T> {
919 if self.0.is_initialized() {
920 // Safe b/c value is initialized.
921 Some(unsafe { self.get_unchecked() })
922 } else {
923 None
924 }
925 }
926
927 /// Gets the reference to the underlying value, blocking the current
928 /// thread until it is set.
929 ///
930 /// ```
931 /// use once_cell::sync::OnceCell;
932 ///
933 /// let mut cell = std::sync::Arc::new(OnceCell::new());
934 /// let t = std::thread::spawn({
935 /// let cell = std::sync::Arc::clone(&cell);
936 /// move || cell.set(92).unwrap()
937 /// });
938 ///
939 /// // Returns immediately, but might return None.
940 /// let _value_or_none = cell.get();
941 ///
942 /// // Will return 92, but might block until the other thread does `.set`.
943 /// let value: &u32 = cell.wait();
944 /// assert_eq!(*value, 92);
945 /// t.join().unwrap();;
946 /// ```
947 pub fn wait(&self) -> &T {
948 if !self.0.is_initialized() {
949 self.0.wait()
950 }
951 debug_assert!(self.0.is_initialized());
952 // Safe b/c of the wait call above and the fact that we didn't
953 // relinquish our borrow.
954 unsafe { self.get_unchecked() }
955 }
956
957 /// Gets the mutable reference to the underlying value.
958 ///
959 /// Returns `None` if the cell is empty.
960 ///
961 /// This method is allowed to violate the invariant of writing to a `OnceCell`
962 /// at most once because it requires `&mut` access to `self`. As with all
963 /// interior mutability, `&mut` access permits arbitrary modification:
964 ///
965 /// ```
966 /// use once_cell::sync::OnceCell;
967 ///
968 /// let mut cell: OnceCell<u32> = OnceCell::new();
969 /// cell.set(92).unwrap();
970 /// cell = OnceCell::new();
971 /// ```
972 pub fn get_mut(&mut self) -> Option<&mut T> {
973 self.0.get_mut()
974 }
975
976 /// Get the reference to the underlying value, without checking if the
977 /// cell is initialized.
978 ///
979 /// # Safety
980 ///
981 /// Caller must ensure that the cell is in initialized state, and that
982 /// the contents are acquired by (synchronized to) this thread.
983 pub unsafe fn get_unchecked(&self) -> &T {
984 self.0.get_unchecked()
985 }
986
987 /// Sets the contents of this cell to `value`.
988 ///
989 /// Returns `Ok(())` if the cell was empty and `Err(value)` if it was
990 /// full.
991 ///
992 /// # Example
993 ///
994 /// ```
995 /// use once_cell::sync::OnceCell;
996 ///
997 /// static CELL: OnceCell<i32> = OnceCell::new();
998 ///
999 /// fn main() {
1000 /// assert!(CELL.get().is_none());
1001 ///
1002 /// std::thread::spawn(|| {
1003 /// assert_eq!(CELL.set(92), Ok(()));
1004 /// }).join().unwrap();
1005 ///
1006 /// assert_eq!(CELL.set(62), Err(62));
1007 /// assert_eq!(CELL.get(), Some(&92));
1008 /// }
1009 /// ```
1010 pub fn set(&self, value: T) -> Result<(), T> {
1011 match self.try_insert(value) {
1012 Ok(_) => Ok(()),
1013 Err((_, value)) => Err(value),
1014 }
1015 }
1016
1017 /// Like [`set`](Self::set), but also returns a reference to the final cell value.
1018 ///
1019 /// # Example
1020 ///
1021 /// ```
1022 /// use once_cell::unsync::OnceCell;
1023 ///
1024 /// let cell = OnceCell::new();
1025 /// assert!(cell.get().is_none());
1026 ///
1027 /// assert_eq!(cell.try_insert(92), Ok(&92));
1028 /// assert_eq!(cell.try_insert(62), Err((&92, 62)));
1029 ///
1030 /// assert!(cell.get().is_some());
1031 /// ```
1032 pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
1033 let mut value = Some(value);
1034 let res = self.get_or_init(|| unsafe { take_unchecked(&mut value) });
1035 match value {
1036 None => Ok(res),
1037 Some(value) => Err((res, value)),
1038 }
1039 }
1040
1041 /// Gets the contents of the cell, initializing it with `f` if the cell
1042 /// was empty.
1043 ///
1044 /// Many threads may call `get_or_init` concurrently with different
1045 /// initializing functions, but it is guaranteed that only one function
1046 /// will be executed.
1047 ///
1048 /// # Panics
1049 ///
1050 /// If `f` panics, the panic is propagated to the caller, and the cell
1051 /// remains uninitialized.
1052 ///
1053 /// It is an error to reentrantly initialize the cell from `f`. The
1054 /// exact outcome is unspecified. Current implementation deadlocks, but
1055 /// this may be changed to a panic in the future.
1056 ///
1057 /// # Example
1058 /// ```
1059 /// use once_cell::sync::OnceCell;
1060 ///
1061 /// let cell = OnceCell::new();
1062 /// let value = cell.get_or_init(|| 92);
1063 /// assert_eq!(value, &92);
1064 /// let value = cell.get_or_init(|| unreachable!());
1065 /// assert_eq!(value, &92);
1066 /// ```
1067 pub fn get_or_init<F>(&self, f: F) -> &T
1068 where
1069 F: FnOnce() -> T,
1070 {
1071 enum Void {}
1072 match self.get_or_try_init(|| Ok::<T, Void>(f())) {
1073 Ok(val) => val,
1074 Err(void) => match void {},
1075 }
1076 }
1077
1078 /// Gets the contents of the cell, initializing it with `f` if
1079 /// the cell was empty. If the cell was empty and `f` failed, an
1080 /// error is returned.
1081 ///
1082 /// # Panics
1083 ///
1084 /// If `f` panics, the panic is propagated to the caller, and
1085 /// the cell remains uninitialized.
1086 ///
1087 /// It is an error to reentrantly initialize the cell from `f`.
1088 /// The exact outcome is unspecified. Current implementation
1089 /// deadlocks, but this may be changed to a panic in the future.
1090 ///
1091 /// # Example
1092 /// ```
1093 /// use once_cell::sync::OnceCell;
1094 ///
1095 /// let cell = OnceCell::new();
1096 /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
1097 /// assert!(cell.get().is_none());
1098 /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
1099 /// Ok(92)
1100 /// });
1101 /// assert_eq!(value, Ok(&92));
1102 /// assert_eq!(cell.get(), Some(&92))
1103 /// ```
1104 pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
1105 where
1106 F: FnOnce() -> Result<T, E>,
1107 {
1108 // Fast path check
1109 if let Some(value) = self.get() {
1110 return Ok(value);
1111 }
1112 self.0.initialize(f)?;
1113
1114 // Safe b/c value is initialized.
1115 debug_assert!(self.0.is_initialized());
1116 Ok(unsafe { self.get_unchecked() })
1117 }
1118
1119 /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
1120 ///
1121 /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```
1126 /// use once_cell::sync::OnceCell;
1127 ///
1128 /// let mut cell: OnceCell<String> = OnceCell::new();
1129 /// assert_eq!(cell.take(), None);
1130 ///
1131 /// let mut cell = OnceCell::new();
1132 /// cell.set("hello".to_string()).unwrap();
1133 /// assert_eq!(cell.take(), Some("hello".to_string()));
1134 /// assert_eq!(cell.get(), None);
1135 /// ```
1136 ///
1137 /// This method is allowed to violate the invariant of writing to a `OnceCell`
1138 /// at most once because it requires `&mut` access to `self`. As with all
1139 /// interior mutability, `&mut` access permits arbitrary modification:
1140 ///
1141 /// ```
1142 /// use once_cell::sync::OnceCell;
1143 ///
1144 /// let mut cell: OnceCell<u32> = OnceCell::new();
1145 /// cell.set(92).unwrap();
1146 /// cell = OnceCell::new();
1147 /// ```
1148 pub fn take(&mut self) -> Option<T> {
1149 mem::replace(self, Self::default()).into_inner()
1150 }
1151
1152 /// Consumes the `OnceCell`, returning the wrapped value. Returns
1153 /// `None` if the cell was empty.
1154 ///
1155 /// # Examples
1156 ///
1157 /// ```
1158 /// use once_cell::sync::OnceCell;
1159 ///
1160 /// let cell: OnceCell<String> = OnceCell::new();
1161 /// assert_eq!(cell.into_inner(), None);
1162 ///
1163 /// let cell = OnceCell::new();
1164 /// cell.set("hello".to_string()).unwrap();
1165 /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
1166 /// ```
1167 pub fn into_inner(self) -> Option<T> {
1168 self.0.into_inner()
1169 }
1170 }
1171
1172 /// A value which is initialized on the first access.
1173 ///
1174 /// This type is thread-safe and can be used in statics.
1175 ///
1176 /// # Example
1177 ///
1178 /// ```
1179 /// use std::collections::HashMap;
1180 ///
1181 /// use once_cell::sync::Lazy;
1182 ///
1183 /// static HASHMAP: Lazy<HashMap<i32, String>> = Lazy::new(|| {
1184 /// println!("initializing");
1185 /// let mut m = HashMap::new();
1186 /// m.insert(13, "Spica".to_string());
1187 /// m.insert(74, "Hoyten".to_string());
1188 /// m
1189 /// });
1190 ///
1191 /// fn main() {
1192 /// println!("ready");
1193 /// std::thread::spawn(|| {
1194 /// println!("{:?}", HASHMAP.get(&13));
1195 /// }).join().unwrap();
1196 /// println!("{:?}", HASHMAP.get(&74));
1197 ///
1198 /// // Prints:
1199 /// // ready
1200 /// // initializing
1201 /// // Some("Spica")
1202 /// // Some("Hoyten")
1203 /// }
1204 /// ```
1205 pub struct Lazy<T, F = fn() -> T> {
1206 cell: OnceCell<T>,
1207 init: Cell<Option<F>>,
1208 }
1209
1210 impl<T: fmt::Debug, F> fmt::Debug for Lazy<T, F> {
1211 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1212 f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").finish()
1213 }
1214 }
1215
1216 // We never create a `&F` from a `&Lazy<T, F>` so it is fine to not impl
1217 // `Sync` for `F`. We do create a `&mut Option<F>` in `force`, but this is
1218 // properly synchronized, so it only happens once so it also does not
1219 // contribute to this impl.
1220 unsafe impl<T, F: Send> Sync for Lazy<T, F> where OnceCell<T>: Sync {}
1221 // auto-derived `Send` impl is OK.
1222
1223 impl<T, F: RefUnwindSafe> RefUnwindSafe for Lazy<T, F> where OnceCell<T>: RefUnwindSafe {}
1224
1225 impl<T, F> Lazy<T, F> {
1226 /// Creates a new lazy value with the given initializing
1227 /// function.
1228 pub const fn new(f: F) -> Lazy<T, F> {
1229 Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }
1230 }
1231
1232 /// Consumes this `Lazy` returning the stored value.
1233 ///
1234 /// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
1235 pub fn into_value(this: Lazy<T, F>) -> Result<T, F> {
1236 let cell = this.cell;
1237 let init = this.init;
1238 cell.into_inner().ok_or_else(|| {
1239 init.take().unwrap_or_else(|| panic!("Lazy instance has previously been poisoned"))
1240 })
1241 }
1242 }
1243
1244 impl<T, F: FnOnce() -> T> Lazy<T, F> {
1245 /// Forces the evaluation of this lazy value and
1246 /// returns a reference to the result. This is equivalent
1247 /// to the `Deref` impl, but is explicit.
1248 ///
1249 /// # Example
1250 /// ```
1251 /// use once_cell::sync::Lazy;
1252 ///
1253 /// let lazy = Lazy::new(|| 92);
1254 ///
1255 /// assert_eq!(Lazy::force(&lazy), &92);
1256 /// assert_eq!(&*lazy, &92);
1257 /// ```
1258 pub fn force(this: &Lazy<T, F>) -> &T {
1259 this.cell.get_or_init(|| match this.init.take() {
1260 Some(f) => f(),
1261 None => panic!("Lazy instance has previously been poisoned"),
1262 })
1263 }
1264
1265 /// Forces the evaluation of this lazy value and
1266 /// returns a mutable reference to the result. This is equivalent
1267 /// to the `Deref` impl, but is explicit.
1268 ///
1269 /// # Example
1270 /// ```
1271 /// use once_cell::sync::Lazy;
1272 ///
1273 /// let mut lazy = Lazy::new(|| 92);
1274 ///
1275 /// assert_eq!(Lazy::force_mut(&mut lazy), &mut 92);
1276 /// ```
1277 pub fn force_mut(this: &mut Lazy<T, F>) -> &mut T {
1278 Self::force(this);
1279 Self::get_mut(this).unwrap_or_else(|| unreachable!())
1280 }
1281
1282 /// Gets the reference to the result of this lazy value if
1283 /// it was initialized, otherwise returns `None`.
1284 ///
1285 /// # Example
1286 /// ```
1287 /// use once_cell::sync::Lazy;
1288 ///
1289 /// let lazy = Lazy::new(|| 92);
1290 ///
1291 /// assert_eq!(Lazy::get(&lazy), None);
1292 /// assert_eq!(&*lazy, &92);
1293 /// assert_eq!(Lazy::get(&lazy), Some(&92));
1294 /// ```
1295 pub fn get(this: &Lazy<T, F>) -> Option<&T> {
1296 this.cell.get()
1297 }
1298
1299 /// Gets the reference to the result of this lazy value if
1300 /// it was initialized, otherwise returns `None`.
1301 ///
1302 /// # Example
1303 /// ```
1304 /// use once_cell::sync::Lazy;
1305 ///
1306 /// let mut lazy = Lazy::new(|| 92);
1307 ///
1308 /// assert_eq!(Lazy::get_mut(&mut lazy), None);
1309 /// assert_eq!(&*lazy, &92);
1310 /// assert_eq!(Lazy::get_mut(&mut lazy), Some(&mut 92));
1311 /// ```
1312 pub fn get_mut(this: &mut Lazy<T, F>) -> Option<&mut T> {
1313 this.cell.get_mut()
1314 }
1315 }
1316
1317 impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
1318 type Target = T;
1319 fn deref(&self) -> &T {
1320 Lazy::force(self)
1321 }
1322 }
1323
1324 impl<T, F: FnOnce() -> T> DerefMut for Lazy<T, F> {
1325 fn deref_mut(&mut self) -> &mut T {
1326 Lazy::force(self);
1327 self.cell.get_mut().unwrap_or_else(|| unreachable!())
1328 }
1329 }
1330
1331 impl<T: Default> Default for Lazy<T> {
1332 /// Creates a new lazy value using `Default` as the initializing function.
1333 fn default() -> Lazy<T> {
1334 Lazy::new(T::default)
1335 }
1336 }
1337
1338 /// ```compile_fail
1339 /// struct S(*mut ());
1340 /// unsafe impl Sync for S {}
1341 ///
1342 /// fn share<T: Sync>(_: &T) {}
1343 /// share(&once_cell::sync::OnceCell::<S>::new());
1344 /// ```
1345 ///
1346 /// ```compile_fail
1347 /// struct S(*mut ());
1348 /// unsafe impl Sync for S {}
1349 ///
1350 /// fn share<T: Sync>(_: &T) {}
1351 /// share(&once_cell::sync::Lazy::<S>::new(|| unimplemented!()));
1352 /// ```
1353 fn _dummy() {}
1354 }
1355
1356 #[cfg(feature = "race")]
1357 pub mod race;
1358
1359 #[cfg(feature = "std")]
1360 unsafe fn take_unchecked<T>(val: &mut Option<T>) -> T {
1361 match val.take() {
1362 Some(it) => it,
1363 None => {
1364 debug_assert!(false);
1365 std::hint::unreachable_unchecked()
1366 }
1367 }
1368 }