Skip to main content

xet_runtime/utils/
unique_id.rs

1use std::fmt;
2use std::sync::atomic::{AtomicU64, Ordering};
3
4static NEXT_ID: AtomicU64 = AtomicU64::new(1);
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
7pub struct UniqueId(u64);
8
9impl UniqueId {
10    pub fn new() -> Self {
11        Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
12    }
13
14    pub fn null() -> Self {
15        Self(0)
16    }
17}
18
19impl Default for UniqueId {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl fmt::Display for UniqueId {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(f, "{}", self.0)
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use std::collections::HashMap;
34
35    use super::*;
36
37    #[test]
38    fn test_unique_id_basics() {
39        let id1 = UniqueId::new();
40        let id2 = UniqueId::new();
41        assert_ne!(id1, id2);
42
43        let cloned = id1;
44        assert_eq!(id1, cloned);
45    }
46
47    #[test]
48    fn test_unique_id_display() {
49        let id = UniqueId::new();
50        let s = id.to_string();
51        assert!(!s.is_empty());
52    }
53
54    #[test]
55    fn test_unique_id_hash() {
56        let id = UniqueId::new();
57        let mut map = HashMap::new();
58        map.insert(id, 42);
59        assert_eq!(map[&id], 42);
60    }
61
62    #[test]
63    fn test_unique_id_null() {
64        let null_id = UniqueId::null();
65        let new_id = UniqueId::new();
66        assert_ne!(null_id, new_id);
67    }
68}