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.
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.
15 use sys_common::mutex::Mutex;
18 // We never call `lock.init()`, so it is UB to attempt to acquire this mutex reentrantly!
20 ptr: Cell<*mut Arc<T>>,
24 const fn done<T>() -> *mut Arc<T> { 1_usize as *mut _ }
26 unsafe impl<T> Sync for Lazy<T> {}
29 pub const fn new() -> Lazy<T> {
32 ptr: Cell::new(ptr::null_mut()),
37 impl<T: Send + Sync + 'static> Lazy<T> {
38 /// Safety: `init` must not call `get` on the variable that is being
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();
45 } else if ptr == done() {
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
58 let registered = sys_common::at_exit(move || {
60 let _guard = self.lock.lock();
61 self.ptr.replace(done())
63 drop(Box::from_raw(ptr))
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.
69 if registered.is_ok() {
70 self.ptr.set(Box::into_raw(Box::new(ret.clone())));