1use core::fmt;
2
3#[derive(Clone, Copy, PartialEq, Eq, Hash)]
5pub struct Flags(u8);
6
7impl fmt::Debug for Flags {
8 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9 f.debug_set().finish()
10 }
11}
12
13impl Flags {
14 #[inline]
16 #[must_use]
17 pub const fn empty() -> Self {
18 Self(0)
19 }
20
21 #[inline]
25 #[must_use]
26 pub const fn from_bits(bits: u8) -> Self {
27 Self(bits & 0b11)
28 }
29
30 #[inline]
32 #[must_use]
33 pub const fn bits(self) -> u8 {
34 self.0
35 }
36
37 #[inline]
43 #[must_use]
44 pub const fn is_any_set(self, other: Self) -> bool {
45 self.0 & other.0 != 0
46 }
47
48 #[inline]
54 #[must_use]
55 pub const fn is_all_set(self, other: Self) -> bool {
56 (self.0 & other.0) ^ other.0 == 0
57 }
58
59 #[inline]
61 pub fn set(&mut self, other: Self) {
62 self.0 |= other.0;
63 }
64
65 #[inline]
67 pub fn set_if<F>(&mut self, other: Self, f: F)
68 where
69 F: FnOnce() -> bool,
70 {
71 if f() {
72 self.set(other);
73 }
74 }
75
76 #[inline]
78 pub fn unset(&mut self, other: Self) {
79 self.0 &= !other.0;
80 }
81
82 #[inline]
84 pub fn unset_if<F>(&mut self, other: Self, f: F)
85 where
86 F: FnOnce() -> bool,
87 {
88 if f() {
89 self.unset(other);
90 }
91 }
92
93 #[inline]
98 pub fn set_or_unset(&mut self, other: Self, set: bool) {
99 if set {
100 self.set(other);
101 } else {
102 self.unset(other);
103 }
104 }
105
106 #[inline]
108 pub fn set_or_unset_with<F>(&mut self, other: Self, f: F)
109 where
110 F: FnOnce() -> bool,
111 {
112 self.set_or_unset(other, f());
113 }
114}