5 use crate::sys_common::mutex::Mutex;
8 // We never call `lock.init()`, so it is UB to attempt to acquire this mutex reentrantly!
10 ptr: Cell<*mut Arc<T>>,
14 const fn done<T>() -> *mut Arc<T> { 1_usize as *mut _ }
16 unsafe impl<T> Sync for Lazy<T> {}
19 pub const fn new() -> Lazy<T> {
22 ptr: Cell::new(ptr::null_mut()),
27 impl<T: Send + Sync + 'static> Lazy<T> {
28 /// Safety: `init` must not call `get` on the variable that is being
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();
35 } else if ptr == done() {
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
48 let registered = sys_common::at_exit(move || {
50 let _guard = self.lock.lock();
51 self.ptr.replace(done())
53 drop(Box::from_raw(ptr))
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.
59 if registered.is_ok() {
60 self.ptr.set(Box::into_raw(Box::new(ret.clone())));