mln_engine/draw/
identity.rs1use std::fmt;
2use std::num::NonZeroU64;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5static NEXT_ID: AtomicU64 = AtomicU64::new(1);
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct SimpleIdentity {
15 unique_id: NonZeroU64,
16}
17
18impl SimpleIdentity {
19 pub(crate) fn new() -> Self {
21 SimpleIdentity {
22 unique_id: NonZeroU64::new(NEXT_ID.fetch_add(1, Ordering::Relaxed)).unwrap_or(NonZeroU64::MIN),
23 }
24 }
25
26 #[must_use]
28 pub(crate) fn get(self) -> u64 {
29 self.unique_id.get()
30 }
31}
32
33impl fmt::Display for SimpleIdentity {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 write!(f, "{{{}}}", self.unique_id)
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 #[test]
45 fn identities_are_unique_and_ordered() {
46 let a = SimpleIdentity::new();
47 let b = SimpleIdentity::new();
48 assert!(a < b);
49 assert_ne!(a, b);
50 assert_eq!(a.to_string(), format!("{{{}}}", a.unique_id));
51 }
52}