1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
    Appellation: atomic <mod>
    Contrib: FL03 <jo3mccain@icloud.com>
*/
use core::borrow::{Borrow, BorrowMut};
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};

///
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[repr(C)]
pub struct AtomicId(usize);

impl AtomicId {
    pub fn new() -> Self {
        static COUNTER: AtomicUsize = AtomicUsize::new(1);
        Self(COUNTER.fetch_add(1, Relaxed))
    }

    pub fn next(&self) -> Self {
        Self::new()
    }

    pub fn set(&mut self, id: usize) {
        self.0 = id;
    }

    pub const fn get(&self) -> usize {
        self.0
    }

    pub fn into_inner(self) -> usize {
        self.0
    }
}

impl AsRef<usize> for AtomicId {
    fn as_ref(&self) -> &usize {
        &self.0
    }
}

impl AsMut<usize> for AtomicId {
    fn as_mut(&mut self) -> &mut usize {
        &mut self.0
    }
}

impl Borrow<usize> for AtomicId {
    fn borrow(&self) -> &usize {
        &self.0
    }
}

impl BorrowMut<usize> for AtomicId {
    fn borrow_mut(&mut self) -> &mut usize {
        &mut self.0
    }
}

impl Default for AtomicId {
    fn default() -> Self {
        Self::new()
    }
}

impl Deref for AtomicId {
    type Target = usize;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for AtomicId {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl From<usize> for AtomicId {
    fn from(id: usize) -> Self {
        Self(id)
    }
}

impl From<AtomicId> for usize {
    fn from(id: AtomicId) -> Self {
        id.0
    }
}

macro_rules! fmt_atomic {
    ($($trait:ident($($fmt:tt)*)),*) => {
        $(
            fmt_atomic!(@impl $trait($($fmt)*));
        )*
    };
    (@impl $trait:ident($($fmt:tt)*)) => {
        impl core::fmt::$trait for AtomicId {
            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(f, $($fmt)*, self.0)
            }
        }
    };
}

fmt_atomic! {
    Binary("{:b}"),
    Debug("{:?}"),
    Display("{}"),
    LowerExp("{:e}"),
    LowerHex("{:x}"),
    Octal("{:o}"),
    UpperExp("{:E}"),
    UpperHex("{:X}")
}

impl<S> PartialEq<S> for AtomicId
where
    usize: PartialEq<S>,
{
    fn eq(&self, other: &S) -> bool {
        self.0.eq(other)
    }
}