tenda_common/
source.rs

1use std::{
2    fmt::Display,
3    hash::Hash,
4    sync::atomic::{AtomicUsize, Ordering},
5};
6
7static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
8static DUMMY_ID: UniqueId = UniqueId(0);
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct UniqueId(usize);
12
13impl UniqueId {
14    pub fn new() -> Self {
15        UniqueId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
16    }
17}
18
19impl Default for UniqueId {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25#[derive(Debug, Clone, Copy, Eq)]
26pub struct IdentifiedSource {
27    id: UniqueId,
28    name: Option<&'static str>,
29}
30
31impl IdentifiedSource {
32    pub fn new() -> Self {
33        IdentifiedSource {
34            id: UniqueId::new(),
35            name: None,
36        }
37    }
38
39    pub fn dummy() -> Self {
40        IdentifiedSource {
41            id: DUMMY_ID,
42            name: None,
43        }
44    }
45
46    pub fn set_name(&mut self, name: &'static str) {
47        self.name = Some(name);
48    }
49
50    pub fn id(&self) -> UniqueId {
51        self.id
52    }
53
54    pub fn name(&self) -> Option<&'static str> {
55        self.name
56    }
57}
58
59impl Default for IdentifiedSource {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl PartialEq for IdentifiedSource {
66    fn eq(&self, other: &Self) -> bool {
67        self.id == other.id
68    }
69}
70
71impl Hash for IdentifiedSource {
72    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
73        self.id.hash(state);
74    }
75}
76
77impl Display for IdentifiedSource {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        if let Some(name) = self.name {
80            write!(f, "{}", name)
81        } else {
82            write!(f, "<anĂ´nimo {}>", self.id.0)
83        }
84    }
85}