qualia_core_db/net/peer/runtime/
incarnation.rs1use crate::net::qdnf::errors::QdnfError;
3use core::sync::atomic::{AtomicUsize, Ordering};
4static NEXT: AtomicUsize = AtomicUsize::new(1);
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub struct CanonicalIncarnation(usize);
7impl CanonicalIncarnation {
8 pub const UNASSIGNED: Self = Self(0);
9 pub const fn assigned(self) -> bool {
10 self.0 != 0
11 }
12 pub(crate) fn bind(&mut self) -> Result<Self, QdnfError> {
13 if !self.assigned() {
14 *self = Self(next(&NEXT)?);
15 }
16 Ok(*self)
17 }
18 pub(crate) fn fresh() -> Result<Self, QdnfError> {
19 Ok(Self(next(&NEXT)?))
20 }
21}
22fn next(source: &AtomicUsize) -> Result<usize, QdnfError> {
23 source
24 .try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
25 .map_err(|_| QdnfError::StaleGeneration)
26}
27#[cfg(test)]
28mod tests {
29 use super::*;
30 #[test]
31 fn once_bound_is_stable_and_new_value_is_distinct() {
32 let mut a = CanonicalIncarnation::UNASSIGNED;
33 let mut b = CanonicalIncarnation::UNASSIGNED;
34 assert!(!a.assigned());
35 let first = a.bind().unwrap();
36 assert!(first.assigned());
37 assert_eq!(a.bind(), Ok(first));
38 assert_ne!(b.bind().unwrap(), first);
39 let moved = a;
40 assert_eq!(moved, first);
41 }
42 #[test]
43 fn exhaustion_never_wraps_or_changes_source() {
44 let source = AtomicUsize::new(usize::MAX);
45 assert_eq!(next(&source), Err(QdnfError::StaleGeneration));
46 assert_eq!(source.load(Ordering::Relaxed), usize::MAX);
47 }
48}