use core::{
mem::ManuallyDrop,
sync::atomic::{self, Ordering},
};
use super::utils::Backoff;
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
pub(super) use core::sync::atomic::AtomicU64 as AtomicStamp;
#[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))]
pub(super) use core::sync::atomic::AtomicUsize as AtomicStamp;
#[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))]
pub(super) type Stamp = usize;
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
pub(super) type Stamp = u64;
pub(super) type AtomicChunk = AtomicStamp;
pub(super) type Chunk = Stamp;
pub(super) struct SeqLock {
state: AtomicStamp,
}
impl SeqLock {
#[inline]
pub(super) const fn new() -> Self {
Self { state: AtomicStamp::new(0) }
}
#[inline]
pub(super) fn optimistic_read(&self) -> Option<Stamp> {
let state = self.state.load(Ordering::Acquire);
if state == 1 {
None
} else {
Some(state)
}
}
#[inline]
pub(super) fn validate_read(&self, stamp: Stamp) -> bool {
atomic::fence(Ordering::Acquire);
self.state.load(Ordering::Relaxed) == stamp
}
#[inline]
pub(super) fn write(&self) -> SeqLockWriteGuard<'_> {
let mut backoff = Backoff::new();
loop {
let previous = self.state.swap(1, Ordering::Acquire);
if previous != 1 {
atomic::fence(Ordering::Release);
return SeqLockWriteGuard { lock: self, state: previous };
}
while self.state.load(Ordering::Relaxed) == 1 {
backoff.snooze();
}
}
}
}
#[must_use]
pub(super) struct SeqLockWriteGuard<'a> {
lock: &'a SeqLock,
state: Stamp,
}
impl SeqLockWriteGuard<'_> {
#[inline]
pub(super) fn abort(self) {
let this = ManuallyDrop::new(self);
this.lock.state.store(this.state, Ordering::Release);
}
}
impl Drop for SeqLockWriteGuard<'_> {
#[inline]
fn drop(&mut self) {
self.lock.state.store(self.state.wrapping_add(2), Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::SeqLock;
#[test]
fn smoke() {
let lock = SeqLock::new();
let before = lock.optimistic_read().unwrap();
assert!(lock.validate_read(before));
{
let _guard = lock.write();
}
assert!(!lock.validate_read(before));
let after = lock.optimistic_read().unwrap();
assert_ne!(before, after);
}
#[test]
fn test_abort() {
let lock = SeqLock::new();
let before = lock.optimistic_read().unwrap();
{
let guard = lock.write();
guard.abort();
}
let after = lock.optimistic_read().unwrap();
assert_eq!(before, after, "aborted write does not update the stamp");
}
}