/
bitflags_custom_bits.rs
140 lines (116 loc) · 2.73 KB
/
bitflags_custom_bits.rs
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
use std::{
fmt::{
self,
Debug,
Display,
LowerHex,
UpperHex,
Octal,
Binary,
},
ops::{
BitAnd,
BitOr,
BitXor,
BitAndAssign,
BitOrAssign,
BitXorAssign,
Not,
},
};
use bitflags::{bitflags, Bits, parser::{ParseError, WriteHex, ParseHex}};
// Ideally we'd actually want this to work, but currently need something like `num`'s `Zero`
// With some design work it could be made possible
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct MyInt(u8);
impl Bits for MyInt {
const EMPTY: Self = MyInt(u8::MIN);
const ALL: Self = MyInt(u8::MAX);
}
impl BitAnd for MyInt {
type Output = Self;
fn bitand(self, other: Self) -> Self {
MyInt(self.0 & other.0)
}
}
impl BitOr for MyInt {
type Output = Self;
fn bitor(self, other: Self) -> Self {
MyInt(self.0 | other.0)
}
}
impl BitXor for MyInt {
type Output = Self;
fn bitxor(self, other: Self) -> Self {
MyInt(self.0 ^ other.0)
}
}
impl BitAndAssign for MyInt {
fn bitand_assign(&mut self, other: Self) {
self.0 &= other.0
}
}
impl BitOrAssign for MyInt {
fn bitor_assign(&mut self, other: Self) {
self.0 |= other.0
}
}
impl BitXorAssign for MyInt {
fn bitxor_assign(&mut self, other: Self) {
self.0 ^= other.0
}
}
impl Not for MyInt {
type Output = MyInt;
fn not(self) -> Self {
MyInt(!self.0)
}
}
impl Debug for MyInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.0, f)
}
}
impl Display for MyInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
impl LowerHex for MyInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
LowerHex::fmt(&self.0, f)
}
}
impl UpperHex for MyInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
UpperHex::fmt(&self.0, f)
}
}
impl Octal for MyInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Octal::fmt(&self.0, f)
}
}
impl Binary for MyInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Binary::fmt(&self.0, f)
}
}
impl ParseHex for MyInt {
fn parse_hex(input: &str) -> Result<Self, ParseError> {
Ok(MyInt(u8::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))?))
}
}
impl WriteHex for MyInt {
fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
write!(writer, "{:x}", self.0)
}
}
bitflags! {
struct Flags128: MyInt {
const A = MyInt(0b0000_0001u8);
const B = MyInt(0b0000_0010u8);
const C = MyInt(0b0000_0100u8);
}
}
fn main() {}