1use core::{
2fmt,
3 ops::{BitAnd, BitOr, BitXor, Not},
4};
56use crate::{
7iter,
8 parser::{ParseError, ParseHex, WriteHex},
9};
1011/**
12A defined flags value that may be named or unnamed.
13*/
14#[derive(#[automatically_derived]
impl<B: ::core::fmt::Debug> ::core::fmt::Debug for Flag<B> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Flag", "name",
&self.name, "value", &&self.value)
}
}Debug)]
15pub struct Flag<B> {
16 name: &'static str,
17 value: B,
18}
1920impl<B> Flag<B> {
21/**
22 Define a flag.
2324 If `name` is non-empty then the flag is named, otherwise it's unnamed.
25 */
26pub const fn new(name: &'static str, value: B) -> Self {
27Flag { name, value }
28 }
2930/**
31 Get the name of this flag.
3233 If the flag is unnamed then the returned string will be empty.
34 */
35pub const fn name(&self) -> &'static str {
36self.name
37 }
3839/**
40 Get the flags value of this flag.
41 */
42pub const fn value(&self) -> &B {
43&self.value
44 }
4546/**
47 Whether the flag is named.
4849 If [`Flag::name`] returns a non-empty string then this method will return `true`.
50 */
51pub const fn is_named(&self) -> bool {
52 !self.name.is_empty()
53 }
5455/**
56 Whether the flag is unnamed.
5758 If [`Flag::name`] returns a non-empty string then this method will return `false`.
59 */
60pub const fn is_unnamed(&self) -> bool {
61self.name.is_empty()
62 }
63}
6465/**
66A set of defined flags using a bits type as storage.
6768## Implementing `Flags`
6970This trait is implemented by the [`bitflags`](macro.bitflags.html) macro:
7172```
73use bitflags::bitflags;
7475bitflags! {
76 struct MyFlags: u8 {
77 const A = 1;
78 const B = 1 << 1;
79 }
80}
81```
8283It can also be implemented manually:
8485```
86use bitflags::{Flag, Flags};
8788struct MyFlags(u8);
8990impl Flags for MyFlags {
91 const FLAGS: &'static [Flag<Self>] = &[
92 Flag::new("A", MyFlags(1)),
93 Flag::new("B", MyFlags(1 << 1)),
94 ];
9596 type Bits = u8;
9798 fn from_bits_retain(bits: Self::Bits) -> Self {
99 MyFlags(bits)
100 }
101102 fn bits(&self) -> Self::Bits {
103 self.0
104 }
105}
106```
107108## Using `Flags`
109110The `Flags` trait can be used generically to work with any flags types. In this example,
111we can count the number of defined named flags:
112113```
114# use bitflags::{bitflags, Flags};
115fn defined_flags<F: Flags>() -> usize {
116 F::FLAGS.iter().filter(|f| f.is_named()).count()
117}
118119bitflags! {
120 struct MyFlags: u8 {
121 const A = 1;
122 const B = 1 << 1;
123 const C = 1 << 2;
124125 const _ = !0;
126 }
127}
128129assert_eq!(3, defined_flags::<MyFlags>());
130```
131*/
132pub trait Flags: Sized + 'static {
133/// The set of defined flags.
134const FLAGS: &'static [Flag<Self>];
135136/// The underlying bits type.
137type Bits: Bits;
138139/// Get a flags value with all bits unset.
140fn empty() -> Self {
141Self::from_bits_retain(Self::Bits::EMPTY)
142 }
143144/// Get a flags value with all known bits set.
145fn all() -> Self {
146let mut truncated = Self::Bits::EMPTY;
147148for flag in Self::FLAGS.iter() {
149 truncated = truncated | flag.value().bits();
150 }
151152Self::from_bits_retain(truncated)
153 }
154155/// Get a flags value with all bits from named flags set.
156 ///
157 /// This method is equivalent to [`Flags::all`] unless [`Flags::FLAGS`] contains unnamed flags.
158fn all_named() -> Self {
159Self::from_bits_retain(
160Self::FLAGS161 .iter()
162 .filter(|f| !f.name().is_empty())
163 .fold(Self::empty().bits(), |acc, f| acc | f.value().bits()),
164 )
165 }
166167/// Get the known bits from a flags value.
168fn known_bits(&self) -> Self::Bits {
169self.bits() & Self::all().bits()
170 }
171172/// Get the unknown bits from a flags value.
173fn unknown_bits(&self) -> Self::Bits {
174self.bits() & !Self::all().bits()
175 }
176177/// This method will return `true` if any unknown bits are set.
178fn contains_unknown_bits(&self) -> bool {
179self.unknown_bits() != Self::Bits::EMPTY180 }
181182/// Get the underlying bits value.
183 ///
184 /// The returned value is exactly the bits set in this flags value.
185fn bits(&self) -> Self::Bits;
186187/// Convert from a bits value.
188 ///
189 /// This method will return `None` if any unknown bits are set.
190fn from_bits(bits: Self::Bits) -> Option<Self> {
191let truncated = Self::from_bits_truncate(bits);
192193if truncated.bits() == bits {
194Some(truncated)
195 } else {
196None197 }
198 }
199200/// Convert from a bits value, unsetting any unknown bits.
201fn from_bits_truncate(bits: Self::Bits) -> Self {
202Self::from_bits_retain(bits & Self::all().bits())
203 }
204205/// Convert from a bits value exactly.
206fn from_bits_retain(bits: Self::Bits) -> Self;
207208/// Get a flags value with the bits of a flag with the given name set.
209 ///
210 /// This method will return `None` if `name` is empty or doesn't
211 /// correspond to any named flag.
212fn from_name(name: &str) -> Option<Self> {
213// Don't parse empty names as empty flags
214if name.is_empty() {
215return None;
216 }
217218for flag in Self::FLAGS {
219if flag.name() == name {
220return Some(Self::from_bits_retain(flag.value().bits()));
221 }
222 }
223224None225 }
226227/// Yield a set of contained flags values.
228 ///
229 /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
230 /// will be yielded together as a final flags value.
231fn iter(&self) -> iter::Iter<Self> {
232 iter::Iter::new(self)
233 }
234235/// Yield a set of contained named flags values.
236 ///
237 /// This method is like [`Flags::iter`], except only yields bits in contained named flags.
238 /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
239fn iter_names(&self) -> iter::IterNames<Self> {
240 iter::IterNames::new(self)
241 }
242243/// Yield a set of all named flags defined by [`Self::FLAGS`].
244fn iter_defined_names() -> iter::IterDefinedNames<Self> {
245 iter::IterDefinedNames::new()
246 }
247248/// Get an iterator over all defined names for this flags value.
249 ///
250 /// This iterator will yield all defined names for the flags value, including
251 /// any convenience flags.
252fn iter_equal_names(&self) -> iter::IterEqualNames<Self> {
253 iter::IterEqualNames::new(self)
254 }
255256/// Whether all bits in this flags value are unset.
257fn is_empty(&self) -> bool {
258self.bits() == Self::Bits::EMPTY259 }
260261/// Whether all known bits in this flags value are set.
262fn is_all(&self) -> bool {
263// NOTE: We check against `Self::all` here, not `Self::Bits::ALL`
264 // because the set of all flags may not use all bits
265Self::all().bits() | self.bits() == self.bits()
266 }
267268/// Whether any set bits in `other` are also set in `self`.
269fn intersects(&self, other: Self) -> bool270where
271Self: Sized,
272 {
273self.bits() & other.bits() != Self::Bits::EMPTY274 }
275276/// Whether all set bits in `other` are also set in `self`.
277fn contains(&self, other: Self) -> bool278where
279Self: Sized,
280 {
281self.bits() & other.bits() == other.bits()
282 }
283284/// Remove any unknown bits from the flags.
285fn truncate(&mut self)
286where
287Self: Sized,
288 {
289*self = Self::from_bits_truncate(self.bits());
290 }
291292/// The bitwise or (`|`) of the bits in `self` and `other`.
293fn insert(&mut self, other: Self)
294where
295Self: Sized,
296 {
297*self = Self::from_bits_retain(self.bits()).union(other);
298 }
299300/// The intersection of `self` with the complement of `other` (`&!`).
301 ///
302 /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
303 /// `remove` won't truncate `other`, but the `!` operator will.
304fn remove(&mut self, other: Self)
305where
306Self: Sized,
307 {
308*self = Self::from_bits_retain(self.bits()).difference(other);
309 }
310311/// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
312fn toggle(&mut self, other: Self)
313where
314Self: Sized,
315 {
316*self = Self::from_bits_retain(self.bits()).symmetric_difference(other);
317 }
318319/// Call [`Flags::insert`] when `value` is `true` or [`Flags::remove`] when `value` is `false`.
320fn set(&mut self, other: Self, value: bool)
321where
322Self: Sized,
323 {
324if value {
325self.insert(other);
326 } else {
327self.remove(other);
328 }
329 }
330331/// Unsets all bits in the flags.
332fn clear(&mut self)
333where
334Self: Sized,
335 {
336*self = Self::empty();
337 }
338339/// The bitwise and (`&`) of the bits in `self` and `other`.
340#[must_use]
341fn intersection(self, other: Self) -> Self {
342Self::from_bits_retain(self.bits() & other.bits())
343 }
344345/// The bitwise or (`|`) of the bits in `self` and `other`.
346#[must_use]
347fn union(self, other: Self) -> Self {
348Self::from_bits_retain(self.bits() | other.bits())
349 }
350351/// The intersection of `self` with the complement of `other` (`&!`).
352 ///
353 /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
354 /// `difference` won't truncate `other`, but the `!` operator will.
355#[must_use]
356fn difference(self, other: Self) -> Self {
357Self::from_bits_retain(self.bits() & !other.bits())
358 }
359360/// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
361#[must_use]
362fn symmetric_difference(self, other: Self) -> Self {
363Self::from_bits_retain(self.bits() ^ other.bits())
364 }
365366/// The bitwise negation (`!`) of the bits in `self`, truncating the result.
367#[must_use]
368fn complement(self) -> Self {
369Self::from_bits_truncate(!self.bits())
370 }
371}
372373/**
374A bits type that can be used as storage for a flags type.
375*/
376pub trait Bits:
377Clone378 + Copy379 + PartialEq380 + BitAnd<Output = Self>
381 + BitOr<Output = Self>
382 + BitXor<Output = Self>
383 + Not<Output = Self>
384 + Sized385 + 'static
386{
387/// A value with all bits unset.
388const EMPTY: Self;
389390/// A value with all bits set.
391const ALL: Self;
392}
393394// Not re-exported: prevent custom `Bits` impls being used in the `bitflags!` macro,
395// or they may fail to compile based on crate features
396pub trait Primitive {}
397398macro_rules! impl_bits {
399 ($($u:ty, $i:ty,)*) => {
400 $(
401impl Bits for $u {
402const EMPTY: $u = 0;
403const ALL: $u = <$u>::MAX;
404 }
405406impl Bits for $i {
407const EMPTY: $i = 0;
408const ALL: $i = <$u>::MAX as $i;
409 }
410411impl ParseHex for $u {
412fn parse_hex(input: &str) -> Result<Self, ParseError> {
413 <$u>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
414 }
415 }
416417impl ParseHex for $i {
418fn parse_hex(input: &str) -> Result<Self, ParseError> {
419 <$i>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
420 }
421 }
422423impl WriteHex for $u {
424fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
425write!(writer, "{:x}", self)
426 }
427 }
428429impl WriteHex for $i {
430fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
431write!(writer, "{:x}", self)
432 }
433 }
434435impl Primitive for $i {}
436impl Primitive for $u {}
437 )*
438 }
439}
440441impl Bits for usize {
const EMPTY: usize = 0;
const ALL: usize = <usize>::MAX;
}
impl Bits for isize {
const EMPTY: isize = 0;
const ALL: isize = <usize>::MAX as isize;
}
impl ParseHex for usize {
fn parse_hex(input: &str) -> Result<Self, ParseError> {
<usize>::from_str_radix(input,
16).map_err(|_| ParseError::invalid_hex_flag(input))
}
}
impl ParseHex for isize {
fn parse_hex(input: &str) -> Result<Self, ParseError> {
<isize>::from_str_radix(input,
16).map_err(|_| ParseError::invalid_hex_flag(input))
}
}
impl WriteHex for usize {
fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
writer.write_fmt(format_args!("{0:x}", self))
}
}
impl WriteHex for isize {
fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
writer.write_fmt(format_args!("{0:x}", self))
}
}
impl Primitive for isize {}
impl Primitive for usize {}impl_bits! {
442u8, i8,
443u16, i16,
444u32, i32,
445u64, i64,
446u128, i128,
447usize, isize,
448}449450/// A trait for referencing the `bitflags`-owned internal type
451/// without exposing it publicly.
452pub trait PublicFlags {
453/// The type of the underlying storage.
454type Primitive: Primitive;
455456/// The type of the internal field on the generated flags type.
457type Internal;
458}
459460#[doc(hidden)]
461#[deprecated(note = "use the `Flags` trait instead")]
462pub trait BitFlags: ImplementedByBitFlagsMacro + Flags {
463/// An iterator over enabled flags in an instance of the type.
464type Iter: Iterator<Item = Self>;
465466/// An iterator over the raw names and bits for enabled flags in an instance of the type.
467type IterNames: Iterator<Item = (&'static str, Self)>;
468}
469470#[allow(deprecated)]
471impl<B: Flags> BitFlagsfor B {
472type Iter = iter::Iter<Self>;
473type IterNames = iter::IterNames<Self>;
474}
475476impl<B: Flags> ImplementedByBitFlagsMacrofor B {}
477478/// A marker trait that signals that an implementation of `BitFlags` came from the `bitflags!` macro.
479///
480/// There's nothing stopping an end-user from implementing this trait, but we don't guarantee their
481/// manual implementations won't break between non-breaking releases.
482#[doc(hidden)]
483pub trait ImplementedByBitFlagsMacro {}
484485pub(crate) mod __private {
486pub use super::{ImplementedByBitFlagsMacro, PublicFlags};
487}