#![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, mut f: F) -> T
where
F: FnMut(&mut Transaction) -> Result<T, StmError>,
{
loop {
let guard = pin();
let mut tx = Transaction::new(self, &guard);
match f(&mut tx) {
Ok(result) => {
if tx.commit() {
return result;
}
#[cfg(feature = "shuttle")]
shuttle::hint::spin_loop();
}
Err(e) => {
if let StmError::Retry = e {
#[cfg(feature = "shuttle")]
shuttle::hint::spin_loop();
#[cfg(not(feature = "shuttle"))]
std::thread::yield_now();
continue;
}
panic!("Transaction failed with error: {:?}", e);
}
}
}
}
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)
}