rsdiff_core/id/kinds/
atomic.rs1use core::borrow::{Borrow, BorrowMut};
6use core::ops::{Deref, DerefMut};
7use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};
8
9#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
11#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
12#[repr(C)]
13pub struct AtomicId(usize);
14
15impl AtomicId {
16 pub fn new() -> Self {
17 static COUNTER: AtomicUsize = AtomicUsize::new(1);
18 Self(COUNTER.fetch_add(1, Relaxed))
19 }
20
21 pub fn next(&self) -> Self {
22 Self::new()
23 }
24
25 pub fn set(&mut self, id: usize) {
26 self.0 = id;
27 }
28
29 pub const fn get(&self) -> usize {
30 self.0
31 }
32
33 pub fn into_inner(self) -> usize {
34 self.0
35 }
36}
37
38impl AsRef<usize> for AtomicId {
39 fn as_ref(&self) -> &usize {
40 &self.0
41 }
42}
43
44impl AsMut<usize> for AtomicId {
45 fn as_mut(&mut self) -> &mut usize {
46 &mut self.0
47 }
48}
49
50impl Borrow<usize> for AtomicId {
51 fn borrow(&self) -> &usize {
52 &self.0
53 }
54}
55
56impl BorrowMut<usize> for AtomicId {
57 fn borrow_mut(&mut self) -> &mut usize {
58 &mut self.0
59 }
60}
61
62impl Default for AtomicId {
63 fn default() -> Self {
64 Self::new()
65 }
66}
67
68impl Deref for AtomicId {
69 type Target = usize;
70
71 fn deref(&self) -> &Self::Target {
72 &self.0
73 }
74}
75
76impl DerefMut for AtomicId {
77 fn deref_mut(&mut self) -> &mut Self::Target {
78 &mut self.0
79 }
80}
81
82impl From<usize> for AtomicId {
83 fn from(id: usize) -> Self {
84 Self(id)
85 }
86}
87
88impl From<AtomicId> for usize {
89 fn from(id: AtomicId) -> Self {
90 id.0
91 }
92}
93
94macro_rules! fmt_atomic {
95 ($($trait:ident($($fmt:tt)*)),*) => {
96 $(
97 fmt_atomic!(@impl $trait($($fmt)*));
98 )*
99 };
100 (@impl $trait:ident($($fmt:tt)*)) => {
101 impl core::fmt::$trait for AtomicId {
102 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
103 write!(f, $($fmt)*, self.0)
104 }
105 }
106 };
107}
108
109fmt_atomic! {
110 Binary("{:b}"),
111 Debug("{:?}"),
112 Display("{}"),
113 LowerExp("{:e}"),
114 LowerHex("{:x}"),
115 Octal("{:o}"),
116 UpperExp("{:E}"),
117 UpperHex("{:X}")
118}
119
120impl<S> PartialEq<S> for AtomicId
121where
122 usize: PartialEq<S>,
123{
124 fn eq(&self, other: &S) -> bool {
125 self.0.eq(other)
126 }
127}