#![doc(
html_logo_url = "https://raw.githubusercontent.com/vertexclique/kovan/master/art/kovan-square.svg"
)]
extern crate alloc;
mod errors;
mod node;
mod transaction;
mod var;
pub use errors::StmError;
pub use transaction::Transaction;
pub use var::TVar;
use kovan::pin;
use std::sync::atomic::AtomicU64;
pub struct Stm {
global_clock: AtomicU64,
}
impl Stm {
pub const fn new() -> Self {
Self {
global_clock: AtomicU64::new(0),
}
}
}
impl Default for Stm {
fn default() -> Self {
Self::new()
}
}
impl Stm {
pub fn atomically<F, T>(&self, f: F) -> T
where
F: FnMut(&mut Transaction) -> Result<T, StmError>,
{
match self.try_atomically(f) {
Ok(result) => result,
Err(e) => panic!("Transaction failed with error: {:?}", e),
}
}
pub fn try_atomically<F, T>(&self, mut f: F) -> Result<T, StmError>
where
F: FnMut(&mut Transaction) -> Result<T, StmError>,
{
#[cfg(not(feature = "shuttle"))]
let mut conflicts = 0u32;
loop {
let committed = {
let guard = pin();
let mut tx = Transaction::new(self, &guard);
match f(&mut tx) {
Ok(result) => tx.commit().then_some(result),
Err(StmError::Retry) => {
drop(tx);
drop(guard);
#[cfg(feature = "shuttle")]
shuttle::hint::spin_loop();
#[cfg(not(feature = "shuttle"))]
std::thread::yield_now();
continue;
}
Err(e) => return Err(e),
}
};
if let Some(result) = committed {
return Ok(result);
}
#[cfg(feature = "shuttle")]
shuttle::hint::spin_loop();
#[cfg(not(feature = "shuttle"))]
back_off(&mut conflicts);
}
}
pub fn tvar<T: Send + Sync + 'static>(&self, data: T) -> TVar<T> {
TVar::new(data)
}
}
pub static STM: Stm = Stm::new();
pub fn atomically<F, T>(f: F) -> T
where
F: FnMut(&mut Transaction) -> Result<T, StmError>,
{
STM.atomically(f)
}
pub fn try_atomically<F, T>(f: F) -> Result<T, StmError>
where
F: FnMut(&mut Transaction) -> Result<T, StmError>,
{
STM.try_atomically(f)
}
#[cfg(not(feature = "shuttle"))]
fn back_off(conflicts: &mut u32) {
if *conflicts < 6 {
for _ in 0..1u32 << *conflicts {
core::hint::spin_loop();
}
*conflicts += 1;
} else {
std::thread::yield_now();
}
}