#[path = "imp.rs"]
pub(super) mod imp;
use core::{
mem::ManuallyDrop,
sync::atomic::{self, AtomicUsize, Ordering},
};
use crate::utils::Backoff;
pub(crate) struct SeqLock {
state: AtomicUsize,
}
impl SeqLock {
pub(crate) const fn new() -> Self {
Self { state: AtomicUsize::new(0) }
}
#[cfg(any(test, not(portable_atomic_cmpxchg16b_dynamic)))]
#[inline]
pub(crate) fn optimistic_read(&self) -> Option<usize> {
let state = self.state.load(Ordering::Acquire);
if state == 1 {
None
} else {
Some(state)
}
}
#[cfg(any(test, not(portable_atomic_cmpxchg16b_dynamic)))]
#[inline]
pub(crate) fn validate_read(&self, stamp: usize) -> bool {
atomic::fence(Ordering::Acquire);
self.state.load(Ordering::Relaxed) == stamp
}
#[inline]
pub(crate) fn write(&'static 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(crate) struct SeqLockWriteGuard {
lock: &'static SeqLock,
state: usize,
}
impl SeqLockWriteGuard {
#[inline]
pub(crate) 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 test_abort() {
static LK: SeqLock = SeqLock::new();
let before = LK.optimistic_read().unwrap();
{
let guard = LK.write();
guard.abort();
}
let after = LK.optimistic_read().unwrap();
assert_eq!(before, after, "aborted write does not update the stamp");
}
}