use core::{ cell::UnsafeCell, ops::Deref, sync::atomic::{AtomicBool, Ordering}, }; pub struct Lazy T> { value: UnsafeCell>, init_func: F, initialized: AtomicBool, } impl T> Lazy { pub const fn new(init_func: F) -> Self { Lazy { value: UnsafeCell::new(None), init_func: init_func, initialized: AtomicBool::new(false), } } } impl T> Deref for Lazy { type Target = T; fn deref(&self) -> &Self::Target { if !self.initialized.load(Ordering::Acquire) { let value = (self.init_func)(); unsafe { *(self.value.get()) = Some(value); } self.initialized.store(true, Ordering::Release); } unsafe { (*self.value.get()) .as_ref() .expect("Lazy value is not initialized!") } } } unsafe impl T + Send> Sync for Lazy {}