Skip to main content

arcis_compiler/utils/
unique_id.rs

1use serde::{Deserialize, Serialize};
2use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
3
4static UNIQUE_ID: AtomicUsize = AtomicUsize::new(0);
5
6/// A id unique within a process or within a single file.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(into = "()")]
9#[serde(from = "()")]
10pub struct UniqueId(usize);
11
12impl UniqueId {
13    pub fn new() -> UniqueId {
14        let unique_id = UNIQUE_ID.fetch_add(1, Relaxed);
15        UniqueId(unique_id)
16    }
17}
18
19impl Default for UniqueId {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl From<()> for UniqueId {
26    fn from(_: ()) -> Self {
27        UniqueId::new()
28    }
29}
30
31impl From<UniqueId> for () {
32    fn from(_: UniqueId) -> Self {}
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    #[test]
39    fn cloning() {
40        let unique_id = UniqueId::new();
41        #[allow(clippy::clone_on_copy)]
42        let cloned = unique_id.clone();
43        // Clones (and copies) are indeed equal to themselves.
44        assert_eq!(unique_id, cloned);
45    }
46
47    #[test]
48    fn serialization() {
49        let unique_id = UniqueId::new();
50        let serialized = bincode::serialize(&unique_id).unwrap();
51        let deserialized: UniqueId = bincode::deserialize(&serialized).unwrap();
52
53        // They should NOT be equal.
54        // Serialized unique ids are different from the ones that we directly created.
55        assert_ne!(unique_id, deserialized);
56    }
57}