diff --git a/core/README.md b/core/README.md index 3d2175b6b..9d8ff7387 100644 --- a/core/README.md +++ b/core/README.md @@ -11,3 +11,7 @@ This crate contains core components used by Miden VM. These components include: ## License This project is [MIT licensed](../LICENSE). + +## Acknowledgements + +The `racy_lock` module found under `core/src/utils/sync` is based on the [once_cell](https://crates.io/crates/once_cell) crate's implementation of `race::OnceBox`. diff --git a/core/src/utils/sync/racy_lock.rs b/core/src/utils/sync/racy_lock.rs index d59054858..df3a7f264 100644 --- a/core/src/utils/sync/racy_lock.rs +++ b/core/src/utils/sync/racy_lock.rs @@ -1,17 +1,18 @@ use alloc::boxed::Box; use core::{ + fmt, ops::Deref, ptr, sync::atomic::{AtomicPtr, Ordering}, }; /// Thread-safe, non-blocking, "first one wins" flavor of `once_cell::sync::OnceCell` -/// with the same interface as `std::sync::LazyLock`. +/// with the same interface as `std::sync::RacyLock`. /// /// The underlying implementation is based on `once_cell::sync::race::OnceBox` which relies on /// `core::atomic::AtomicPtr` to ensure that the data race results in a single successful /// write to the relevant pointer, namely the first write. -/// See https://github.com/matklad/once_cell/blob/v1.19.0/src/race.rs#L294. +/// See . /// /// Performs lazy evaluation and can be used for statics. pub struct RacyLock T> @@ -67,6 +68,24 @@ where } } +impl Default for RacyLock { + /// Creates a new lock that will evaluate the underlying value base on `T::default`. + #[inline] + fn default() -> RacyLock { + RacyLock::new(T::default) + } +} + +impl fmt::Debug for RacyLock +where + T: fmt::Debug, + F: Fn() -> T, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "RacyLock({:?})", self.inner.load(Ordering::Relaxed)) + } +} + impl Deref for RacyLock where F: Fn() -> T, @@ -101,6 +120,13 @@ mod tests { use super::*; + #[test] + fn deref_default() { + // Lock a copy type and validate default value. + let lock: RacyLock = RacyLock::default(); + assert_eq!(*lock, 0); + } + #[test] fn deref_copy() { // Lock a copy type and validate value.