lsm_tree/seqno.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
// Copyright (c) 2024-present, fjall-rs
// This source code is licensed under both the Apache 2.0 and MIT License
// (found in the LICENSE-* files in the repository)
use crate::SeqNo;
use std::sync::{
atomic::{
AtomicU64,
Ordering::{Acquire, Release},
},
Arc,
};
/// Thread-safe sequence number generator
///
/// # Examples
///
/// ```
/// # use lsm_tree::{AbstractTree, Config, SequenceNumberCounter};
/// #
/// # let path = tempfile::tempdir()?;
/// let tree = Config::new(path).open()?;
///
/// let seqno = SequenceNumberCounter::default();
///
/// // Do some inserts...
/// tree.insert("a".as_bytes(), "abc", seqno.next());
/// tree.insert("b".as_bytes(), "abc", seqno.next());
/// tree.insert("c".as_bytes(), "abc", seqno.next());
///
/// // Maybe create a snapshot
/// let snapshot = tree.snapshot(seqno.get());
///
/// // Create a batch
/// let batch_seqno = seqno.next();
/// tree.remove("a".as_bytes(), batch_seqno);
/// tree.remove("b".as_bytes(), batch_seqno);
/// tree.remove("c".as_bytes(), batch_seqno);
/// #
/// # assert!(tree.is_empty()?);
/// # Ok::<(), lsm_tree::Error>(())
/// ```
#[derive(Clone, Default, Debug)]
pub struct SequenceNumberCounter(Arc<AtomicU64>);
impl std::ops::Deref for SequenceNumberCounter {
type Target = Arc<AtomicU64>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl SequenceNumberCounter {
/// Creates a new counter, setting it to some previous value
#[must_use]
pub fn new(prev: SeqNo) -> Self {
Self(Arc::new(AtomicU64::new(prev)))
}
/// Gets the next sequence number, without incrementing the counter.
///
/// This should only be used when creating a snapshot.
#[must_use]
pub fn get(&self) -> SeqNo {
self.load(Acquire)
}
/// Gets the next sequence number.
#[must_use]
pub fn next(&self) -> SeqNo {
self.fetch_add(1, Release)
}
}