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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use core::{mem, fmt, ops, hash};
#[repr(transparent)]
#[derive(Clone, Copy, Default)]
pub struct Bits<T>(pub T);
macro_rules! impl_bits {
($($ty:ident),*) => {$(
impl Bits<$ty> {
#[inline(always)]
pub const fn get(&self, idx: u32) -> bool {
self.0.wrapping_shr(idx) & 1 != 0
}
#[inline(always)]
pub const fn set(self, idx: u32) -> Self {
const ONE: $ty = 1;
Self(self.0 | ONE.wrapping_shl(idx))
}
#[inline(always)]
pub const fn unset(self, idx: u32) -> Self {
Self(self.0 & !(1 << idx))
}
#[inline(always)]
pub const fn toggle(self, idx: u32) -> Self {
Self(self.0 ^ (1 << idx))
}
#[inline(always)]
pub const fn empty(&self) -> bool {
self.0 == 0
}
#[inline(always)]
pub const fn reset(&self) -> Self {
Self(0)
}
#[inline(always)]
pub const fn flip(&self) -> Self {
Self(self.0.reverse_bits())
}
#[inline(always)]
pub const fn len(&self) -> usize {
Self::size()
}
#[inline(always)]
pub const fn size() -> usize {
mem::size_of::<$ty>() * 8
}
}
impl PartialEq<Bits<$ty>> for $ty {
#[inline(always)]
fn eq(&self, other: &Bits<$ty>) -> bool {
PartialEq::eq(self, &other.0)
}
}
impl fmt::Debug for Bits<$ty> {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, fmt)
}
}
impl fmt::Display for Bits<$ty> {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, fmt)
}
}
impl fmt::Binary for Bits<$ty> {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Binary::fmt(&self.0, fmt)
}
}
impl PartialEq<$ty> for Bits<$ty> {
#[inline(always)]
fn eq(&self, other: &$ty) -> bool {
PartialEq::eq(&self.0, other)
}
}
impl ops::Deref for Bits<$ty> {
type Target = $ty;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for Bits<$ty> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl hash::Hash for Bits<$ty> {
#[inline(always)]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
hash::Hash::hash(&self.0, state)
}
}
impl From<$ty> for Bits<$ty> {
#[inline(always)]
fn from(val: $ty) -> Self {
Self(val)
}
}
impl Into<$ty> for Bits<$ty> {
#[inline(always)]
fn into(self) -> $ty {
self.0
}
}
)*};
}
impl_bits!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);