1use std::borrow;
2use std::sync::atomic::{self, AtomicUsize};
3
4static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub struct Id(Internal);
9
10impl Id {
11 pub const fn new(id: &'static str) -> Self {
13 Self(Internal::Custom(borrow::Cow::Borrowed(id)))
14 }
15
16 pub fn unique() -> Self {
20 let id = NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed);
21
22 Self(Internal::Unique(id))
23 }
24}
25
26impl From<&'static str> for Id {
27 fn from(value: &'static str) -> Self {
28 Self::new(value)
29 }
30}
31
32impl From<String> for Id {
33 fn from(value: String) -> Self {
34 Self(Internal::Custom(borrow::Cow::Owned(value)))
35 }
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39enum Internal {
40 Unique(usize),
41 Custom(borrow::Cow<'static, str>),
42}
43
44#[cfg(test)]
45mod tests {
46 use super::Id;
47
48 #[test]
49 fn unique_generates_different_ids() {
50 let a = Id::unique();
51 let b = Id::unique();
52
53 assert_ne!(a, b);
54 }
55}