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