use core::cell::UnsafeCell; use core::mem::MaybeUninit; use core::sync::atomic::{AtomicBool, Ordering}; use std::sync::Once;
pub(crate) struct OnceLock<T> {
once: Once, // Once::is_completed requires Rust 1.43, so use this to track of whether they have been initialized.
is_initialized: AtomicBool,
value: UnsafeCell<MaybeUninit<T>>, // Unlike std::sync::OnceLock, we don't need PhantomData here because // we don't use #[may_dangle].
}
unsafeimpl<T: Sync + Send> Sync for OnceLock<T> {} unsafeimpl<T: Send> Send for OnceLock<T> {}
/// Gets the contents of the cell, initializing it with `f` if the cell /// was empty. /// /// Many threads may call `get_or_init` concurrently with different /// initializing functions, but it is guaranteed that only one function /// will be executed. /// /// # Panics /// /// If `f` panics, the panic is propagated to the caller, and the cell /// remains uninitialized. /// /// It is an error to reentrantly initialize the cell from `f`. The /// exact outcome is unspecified. Current implementation deadlocks, but /// this may be changed to a panic in the future. pub(crate) fn get_or_init<F>(&self, f: F) -> &T where
F: FnOnce() -> T,
{ // Fast path check ifself.is_initialized() { // SAFETY: The inner value has been initialized returnunsafe { self.get_unchecked() };
} self.initialize(f);
debug_assert!(self.is_initialized());
// SAFETY: The inner value has been initialized unsafe { self.get_unchecked() }
}
#[cold] fn initialize<F>(&self, f: F) where
F: FnOnce() -> T,
{ let slot = self.value.get().cast::<T>(); let is_initialized = &self.is_initialized;
self.once.call_once(|| { let value = f(); unsafe {
slot.write(value);
}
is_initialized.store(true, Ordering::Release);
});
}
/// # Safety /// /// The value must be initialized unsafefn get_unchecked(&self) -> &T {
debug_assert!(self.is_initialized());
&*self.value.get().cast::<T>()
}
}
impl<T> Drop for OnceLock<T> { fn drop(&mutself) { ifself.is_initialized() { // SAFETY: The inner value has been initialized unsafe { self.value.get().cast::<T>().drop_in_place() };
}
}
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.11 Sekunden
(vorverarbeitet am 2026-06-23)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.