]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/lazy.rs
Format libstd with rustfmt
[rust.git] / src / libstd / io / lazy.rs
1 use crate::cell::Cell;
2 use crate::ptr;
3 use crate::sync::Arc;
4 use crate::sys_common;
5 use crate::sys_common::mutex::Mutex;
6
7 pub struct Lazy<T> {
8     // We never call `lock.init()`, so it is UB to attempt to acquire this mutex reentrantly!
9     lock: Mutex,
10     ptr: Cell<*mut Arc<T>>,
11 }
12
13 #[inline]
14 const fn done<T>() -> *mut Arc<T> { 1_usize as *mut _ }
15
16 unsafe impl<T> Sync for Lazy<T> {}
17
18 impl<T> Lazy<T> {
19     pub const fn new() -> Lazy<T> {
20         Lazy {
21             lock: Mutex::new(),
22             ptr: Cell::new(ptr::null_mut()),
23         }
24     }
25 }
26
27 impl<T: Send + Sync + 'static> Lazy<T> {
28     /// Safety: `init` must not call `get` on the variable that is being
29     /// initialized.
30     pub unsafe fn get(&'static self, init: fn() -> Arc<T>) -> Option<Arc<T>> {
31         let _guard = self.lock.lock();
32         let ptr = self.ptr.get();
33         if ptr.is_null() {
34             Some(self.init(init))
35         } else if ptr == done() {
36             None
37         } else {
38             Some((*ptr).clone())
39         }
40     }
41
42     // Must only be called with `lock` held
43     unsafe fn init(&'static self, init: fn() -> Arc<T>) -> Arc<T> {
44         // If we successfully register an at exit handler, then we cache the
45         // `Arc` allocation in our own internal box (it will get deallocated by
46         // the at exit handler). Otherwise we just return the freshly allocated
47         // `Arc`.
48         let registered = sys_common::at_exit(move || {
49             let ptr = {
50                 let _guard = self.lock.lock();
51                 self.ptr.replace(done())
52             };
53             drop(Box::from_raw(ptr))
54         });
55         // This could reentrantly call `init` again, which is a problem
56         // because our `lock` allows reentrancy!
57         // That's why `get` is unsafe and requires the caller to ensure no reentrancy happens.
58         let ret = init();
59         if registered.is_ok() {
60             self.ptr.set(Box::into_raw(Box::new(ret.clone())));
61         }
62         ret
63     }
64 }