// Why do we need `T: Send`? // Thread A creates a `OnceCell` and shares it with // scoped thread B, which fills the cell, which is // then destroyed by A. That is, destructor observes // a sent value. unsafeimpl<T: Sync + Send> Sync for OnceCell<T> {} unsafeimpl<T: Send> Send for OnceCell<T> {}
impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceCell<T> {} impl<T: UnwindSafe> UnwindSafe for OnceCell<T> {}
/// Safety: synchronizes with store to value via Release/Acquire. #[inline] pub(crate) fn is_initialized(&self) -> bool { self.state.load(Ordering::Acquire) == COMPLETE
}
/// Safety: synchronizes with store to value via `is_initialized` or mutex /// lock/unlock, writes value only once because of the mutex. #[cold] pub(crate) fn initialize<F, E>(&self, f: F) -> Result<(), E> where
F: FnOnce() -> Result<T, E>,
{ letmut f = Some(f); letmut res: Result<(), E> = Ok(()); let slot: *mut Option<T> = self.value.get();
initialize_inner(&self.state, &mut || { // We are calling user-supplied function and need to be careful. // - if it returns Err, we unlock mutex and return without touching anything // - if it panics, we unlock mutex and propagate panic without touching anything // - if it calls `set` or `get_or_try_init` re-entrantly, we get a deadlock on // mutex, which is important for safety. We *could* detect this and panic, // but that is more complicated // - finally, if it returns Ok, we store the value and store the flag with // `Release`, which synchronizes with `Acquire`s. let f = unsafe { f.take().unwrap_unchecked() }; match f() {
Ok(value) => unsafe { // Safe b/c we have a unique access and no panic may happen // until the cell is marked as initialized.
debug_assert!((*slot).is_none());
*slot = Some(value); true
},
Err(err) => {
res = Err(err); false
}
}
});
res
}
/// Get the reference to the underlying value, without checking if the cell /// is initialized. /// /// # Safety /// /// Caller must ensure that the cell is in initialized state, and that /// the contents are acquired by (synchronized to) this thread. pub(crate) unsafefn get_unchecked(&self) -> &T {
debug_assert!(self.is_initialized()); let slot = &*self.value.get();
slot.as_ref().unwrap_unchecked()
}
/// Gets the mutable reference to the underlying value. /// Returns `None` if the cell is empty. pub(crate) fn get_mut(&mutself) -> Option<&>mut T> { // Safe b/c we have an exclusive access let slot: &mut Option<T> = unsafe { &mut *self.value.get() };
slot.as_mut()
}
/// Consumes this `OnceCell`, returning the wrapped value. /// Returns `None` if the cell was empty. pub(crate) fn into_inner(self) -> Option<T> { self.value.into_inner()
}
}
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.