use std::num::NonZeroU64;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_IDENTITY: AtomicU64 = AtomicU64::new(1);
pub(crate) fn next_identity() -> NonZeroU64 {
let raw = NEXT_IDENTITY.fetch_add(1, Ordering::Relaxed);
NonZeroU64::new(raw).expect("identity counter starts at 1 and only increases")
}
macro_rules! identity_newtype {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct $name(NonZeroU64);
impl $name {
pub fn fresh() -> Self {
Self($crate::lifecycle_identity::next_identity())
}
}
};
}
identity_newtype!(
BindingIdentity
);
identity_newtype!(
ObserverToken
);
identity_newtype!(
CandidateIdentity
);
identity_newtype!(
GenerationIdentity
);
identity_newtype!(
PublicationIdentity
);
identity_newtype!(
SnapshotIdentity
);
identity_newtype!(
AuthorityIdentity
);
identity_newtype!(
ProvenanceIdentity
);
identity_newtype!(
OperationIdentity
);
identity_newtype!(
EvaluationIdentity
);
identity_newtype!(
WorktreeScanId
);
identity_newtype!(
ProducingRuntimeIdentity
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ObservationTime(NonZeroU64);
impl ObservationTime {
pub fn fresh() -> Self {
Self(next_identity())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ObserverEpoch(u64);
impl ObserverEpoch {
pub const fn initial() -> Self {
Self(0)
}
pub const fn advanced(self) -> Self {
Self(self.0 + 1)
}
pub const fn raw(self) -> u64 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InvalidationSequence(u64);
impl InvalidationSequence {
pub const fn initial() -> Self {
Self(0)
}
pub const fn advanced(self) -> Self {
Self(self.0 + 1)
}
pub const fn raw(self) -> u64 {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_counter_serves_every_identity_kind() {
let a = GenerationIdentity::fresh().0;
let b = AuthorityIdentity::fresh().0;
let c = OperationIdentity::fresh().0;
let d = ObservationTime::fresh().0;
let mut raws = vec![a, b, c, d];
raws.sort_unstable();
raws.dedup();
assert_eq!(raws.len(), 4, "one shared counter must not repeat a value");
}
#[test]
fn a_fresh_identity_never_repeats_within_its_own_kind() {
let first = GenerationIdentity::fresh();
let second = GenerationIdentity::fresh();
assert_ne!(first, second);
}
#[test]
fn monotonic_positions_never_rewind() {
let epoch = ObserverEpoch::initial();
assert!(epoch.advanced() > epoch);
let sequence = InvalidationSequence::initial();
assert!(sequence.advanced() > sequence);
}
}