use std::fmt;
use std::num::NonZeroU64;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SimpleIdentity {
unique_id: NonZeroU64,
}
impl SimpleIdentity {
pub(crate) fn new() -> Self {
SimpleIdentity {
unique_id: NonZeroU64::new(NEXT_ID.fetch_add(1, Ordering::Relaxed)).unwrap_or(NonZeroU64::MIN),
}
}
#[must_use]
pub(crate) fn get(self) -> u64 {
self.unique_id.get()
}
}
impl fmt::Display for SimpleIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{{{}}}", self.unique_id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identities_are_unique_and_ordered() {
let a = SimpleIdentity::new();
let b = SimpleIdentity::new();
assert!(a < b);
assert_ne!(a, b);
assert_eq!(a.to_string(), format!("{{{}}}", a.unique_id));
}
}