xet_runtime/utils/
unique_id.rs1use 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)]
7#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
8pub struct UniqueId(pub u64);
9
10impl UniqueId {
11 pub fn new() -> Self {
12 Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
13 }
14
15 pub fn null() -> Self {
16 Self(0)
17 }
18}
19
20impl Default for UniqueId {
21 fn default() -> Self {
22 Self::new()
23 }
24}
25
26#[cfg(feature = "python")]
27#[pyo3::pymethods]
28impl UniqueId {
29 fn __repr__(&self) -> String {
30 format!("UniqueId({})", self.0)
31 }
32
33 fn __hash__(&self) -> u64 {
34 self.0
35 }
36
37 fn __eq__(&self, other: &Self) -> bool {
38 self.0 == other.0
39 }
40}
41
42impl fmt::Display for UniqueId {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 write!(f, "{}", self.0)
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use std::collections::HashMap;
51
52 use super::*;
53
54 #[test]
55 fn test_unique_id_basics() {
56 let id1 = UniqueId::new();
57 let id2 = UniqueId::new();
58 assert_ne!(id1, id2);
59
60 let cloned = id1;
61 assert_eq!(id1, cloned);
62 }
63
64 #[test]
65 fn test_unique_id_display() {
66 let id = UniqueId::new();
67 let s = id.to_string();
68 assert!(!s.is_empty());
69 }
70
71 #[test]
72 fn test_unique_id_hash() {
73 let id = UniqueId::new();
74 let mut map = HashMap::new();
75 map.insert(id, 42);
76 assert_eq!(map[&id], 42);
77 }
78
79 #[test]
80 fn test_unique_id_null() {
81 let null_id = UniqueId::null();
82 let new_id = UniqueId::new();
83 assert_ne!(null_id, new_id);
84 }
85}