Skip to content

Commit

Permalink
Add acknowledgement, default, and debug
Browse files Browse the repository at this point in the history
  • Loading branch information
sergerad committed Sep 4, 2024
1 parent 5e35119 commit 4e18021
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
4 changes: 4 additions & 0 deletions core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
30 changes: 28 additions & 2 deletions core/src/utils/sync/racy_lock.rs
Original file line number Diff line number Diff line change
@@ -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 <https://github.com/matklad/once_cell/blob/v1.19.0/src/race.rs#L294>.
///
/// Performs lazy evaluation and can be used for statics.
pub struct RacyLock<T, F = fn() -> T>
Expand Down Expand Up @@ -67,6 +68,24 @@ where
}
}

impl<T: Default> Default for RacyLock<T> {
/// Creates a new lock that will evaluate the underlying value base on `T::default`.
#[inline]
fn default() -> RacyLock<T> {
RacyLock::new(T::default)
}
}

impl<T, F> fmt::Debug for RacyLock<T, F>
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<T, F> Deref for RacyLock<T, F>
where
F: Fn() -> T,
Expand Down Expand Up @@ -101,6 +120,13 @@ mod tests {

use super::*;

#[test]
fn deref_default() {
// Lock a copy type and validate default value.
let lock: RacyLock<i32> = RacyLock::default();
assert_eq!(*lock, 0);
}

#[test]
fn deref_copy() {
// Lock a copy type and validate value.
Expand Down

0 comments on commit 4e18021

Please sign in to comment.