use crate::core::types::{RecordEnvelope, TxId};
#[derive(Debug, Clone)]
pub struct TxManager {
clock: TxId,
}
impl TxManager {
pub fn new() -> Self {
Self { clock: 0 }
}
pub fn with_clock(clock: TxId) -> Self {
Self { clock }
}
pub fn current(&self) -> TxId {
self.clock
}
pub fn begin_write(&mut self) -> TxId {
self.clock += 1;
self.clock
}
pub fn snapshot(&self) -> Snapshot {
Snapshot { tx: self.clock }
}
}
impl Default for TxManager {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Snapshot {
tx: TxId,
}
impl Snapshot {
pub fn as_of(tx: TxId) -> Self {
Self { tx }
}
pub fn tx(&self) -> TxId {
self.tx
}
#[inline]
pub fn sees(&self, envelope: &RecordEnvelope) -> bool {
envelope.is_visible(self.tx)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clock_is_monotonic() {
let mut txm = TxManager::new();
assert_eq!(txm.current(), 0);
assert_eq!(txm.begin_write(), 1);
assert_eq!(txm.begin_write(), 2);
assert_eq!(txm.current(), 2);
assert_eq!(txm.snapshot().tx(), 2);
}
#[test]
fn snapshot_isolates_inserts_and_deletes() {
let mut env = RecordEnvelope::new(2, 0);
env.mark_deleted(5);
assert!(!Snapshot::as_of(1).sees(&env)); assert!(Snapshot::as_of(2).sees(&env)); assert!(Snapshot::as_of(4).sees(&env)); assert!(!Snapshot::as_of(5).sees(&env)); assert!(!Snapshot::as_of(9).sees(&env)); }
}