Skip to main content

mln_engine/draw/
identity.rs

1use std::fmt;
2use std::num::NonZeroU64;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5// This is not in the type declaration to minimize include dependencies (C++).
6static NEXT_ID: AtomicU64 = AtomicU64::new(1);
7
8/// A simple unique identifier.
9///
10/// `new` takes the next value of a process-wide counter starting at 1.
11/// Ordering and equality compare the id. Use `Option<SimpleIdentity>` for an
12/// identity that may be absent.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct SimpleIdentity {
15    unique_id: NonZeroU64,
16}
17
18impl SimpleIdentity {
19    /// Returns a new unique identity.
20    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    /// The identity's number, which grows with each new identity.
27    #[must_use]
28    pub(crate) fn get(self) -> u64 {
29        self.unique_id.get()
30    }
31}
32
33/// Formats the identity as `{<id>}`.
34impl 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}