]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/lazy.rs
24965ff69318435e874eaad52f9dc8a1b58edcc3
[rust.git] / src / libstd / io / lazy.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use cell::Cell;
12 use ptr;
13 use sync::Arc;
14 use sys_common;
15 use sys_common::mutex::Mutex;
16
17 pub struct Lazy<T> {
18     // We never call `lock.init()`, so it is UB to attempt to acquire this mutex reentrantly!
19     lock: Mutex,
20     ptr: Cell<*mut Arc<T>>,
21 }
22
23 #[inline]
24 const fn done<T>() -> *mut Arc<T> { 1_usize as *mut _ }
25
26 unsafe impl<T> Sync for Lazy<T> {}
27
28 impl<T> Lazy<T> {
29     pub const fn new() -> Lazy<T> {
30         Lazy {
31             lock: Mutex::new(),
32             ptr: Cell::new(ptr::null_mut()),
33         }
34     }
35 }
36
37 impl<T: Send + Sync + 'static> Lazy<T> {
38     /// Safety: `init` must not call `get` on the variable that is being
39     /// initialized.
40     pub unsafe fn get(&'static self, init: fn() -> Arc<T>) -> Option<Arc<T>> {
41         let _guard = self.lock.lock();
42         let ptr = self.ptr.get();
43         if ptr.is_null() {
44             Some(self.init(init))
45         } else if ptr == done() {
46             None
47         } else {
48             Some((*ptr).clone())
49         }
50     }
51
52     // Must only be called with `lock` held
53     unsafe fn init(&'static self, init: fn() -> Arc<T>) -> Arc<T> {
54         // If we successfully register an at exit handler, then we cache the
55         // `Arc` allocation in our own internal box (it will get deallocated by
56         // the at exit handler). Otherwise we just return the freshly allocated
57         // `Arc`.
58         let registered = sys_common::at_exit(move || {
59             let ptr = {
60                 let _guard = self.lock.lock();
61                 self.ptr.replace(done())
62             };
63             drop(Box::from_raw(ptr))
64         });
65         // This could reentrantly call `init` again, which is a problem
66         // because our `lock` allows reentrancy!
67         // That's why `get` is unsafe and requires the caller to ensure no reentrancy happens.
68         let ret = init();
69         if registered.is_ok() {
70             self.ptr.set(Box::into_raw(Box::new(ret.clone())));
71         }
72         ret
73     }
74 }