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