channels_packet/
flags.rs

1use core::fmt;
2
3/// Frame flags.
4#[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	/// Create a new set of frame flags with no flag set.
15	#[inline]
16	#[must_use]
17	pub const fn empty() -> Self {
18		Self(0)
19	}
20
21	/// Create a new set of frame flags from `bits`.
22	///
23	/// The upper 6 bits of `bits` are discarded.
24	#[inline]
25	#[must_use]
26	pub const fn from_bits(bits: u8) -> Self {
27		Self(bits & 0b11)
28	}
29
30	/// Get the bit representation of the flags.
31	#[inline]
32	#[must_use]
33	pub const fn bits(self) -> u8 {
34		self.0
35	}
36
37	/// Check whether any flag in `other` is set in `self`.
38	///
39	/// If `other` contains only one flag, this method behaves identical to [`is_all_set()`].
40	///
41	/// [`is_all_set()`]: Self::is_all_set
42	#[inline]
43	#[must_use]
44	pub const fn is_any_set(self, other: Self) -> bool {
45		self.0 & other.0 != 0
46	}
47
48	/// Check whether all flags in `other` are set in `self`.
49	///
50	/// If `other` contains only one flag, this method behaves identical to [`is_any_set()`].
51	///
52	/// [`is_any_set()`]: Self::is_any_set
53	#[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	/// Set the flags of `other` in `self`.
60	#[inline]
61	pub fn set(&mut self, other: Self) {
62		self.0 |= other.0;
63	}
64
65	/// Set the flags of `other` in `self` if the predicate _f_ returns `true`.
66	#[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	/// Unset the flags of `other` in `self`.
77	#[inline]
78	pub fn unset(&mut self, other: Self) {
79		self.0 &= !other.0;
80	}
81
82	/// Unset the flags of `other` in `self` if the predicate _f_ returns `true`.
83	#[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	/// Set or unset the flags of `other` in `self` depending on `set`.
94	///
95	/// If `set` is `true`, this method will set the flags of `other` in `self`. If `set`
96	/// is `false`, it will unset them.
97	#[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	/// Set or unset the flags of `other` in `self` based on a predicate _f_.
107	#[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}