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 the known bits from a flags value.
156fn known_bits(&self) -> Self::Bits {
157self.bits() & Self::all().bits()
158 }
159160/// Get the unknown bits from a flags value.
161fn unknown_bits(&self) -> Self::Bits {
162self.bits() & !Self::all().bits()
163 }
164165/// This method will return `true` if any unknown bits are set.
166fn contains_unknown_bits(&self) -> bool {
167self.unknown_bits() != Self::Bits::EMPTY168 }
169170/// Get the underlying bits value.
171 ///
172 /// The returned value is exactly the bits set in this flags value.
173fn bits(&self) -> Self::Bits;
174175/// Convert from a bits value.
176 ///
177 /// This method will return `None` if any unknown bits are set.
178fn from_bits(bits: Self::Bits) -> Option<Self> {
179let truncated = Self::from_bits_truncate(bits);
180181if truncated.bits() == bits {
182Some(truncated)
183 } else {
184None185 }
186 }
187188/// Convert from a bits value, unsetting any unknown bits.
189fn from_bits_truncate(bits: Self::Bits) -> Self {
190Self::from_bits_retain(bits & Self::all().bits())
191 }
192193/// Convert from a bits value exactly.
194fn from_bits_retain(bits: Self::Bits) -> Self;
195196/// Get a flags value with the bits of a flag with the given name set.
197 ///
198 /// This method will return `None` if `name` is empty or doesn't
199 /// correspond to any named flag.
200fn from_name(name: &str) -> Option<Self> {
201// Don't parse empty names as empty flags
202if name.is_empty() {
203return None;
204 }
205206for flag in Self::FLAGS {
207if flag.name() == name {
208return Some(Self::from_bits_retain(flag.value().bits()));
209 }
210 }
211212None213 }
214215/// Yield a set of contained flags values.
216 ///
217 /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
218 /// will be yielded together as a final flags value.
219fn iter(&self) -> iter::Iter<Self> {
220 iter::Iter::new(self)
221 }
222223/// Yield a set of contained named flags values.
224 ///
225 /// This method is like [`Flags::iter`], except only yields bits in contained named flags.
226 /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
227fn iter_names(&self) -> iter::IterNames<Self> {
228 iter::IterNames::new(self)
229 }
230231/// Yield a set of all named flags defined by [`Self::FLAGS`].
232fn iter_defined_names() -> iter::IterDefinedNames<Self> {
233 iter::IterDefinedNames::new()
234 }
235236/// Whether all bits in this flags value are unset.
237fn is_empty(&self) -> bool {
238self.bits() == Self::Bits::EMPTY239 }
240241/// Whether all known bits in this flags value are set.
242fn is_all(&self) -> bool {
243// NOTE: We check against `Self::all` here, not `Self::Bits::ALL`
244 // because the set of all flags may not use all bits
245Self::all().bits() | self.bits() == self.bits()
246 }
247248/// Whether any set bits in a source flags value are also set in a target flags value.
249fn intersects(&self, other: Self) -> bool250where
251Self: Sized,
252 {
253self.bits() & other.bits() != Self::Bits::EMPTY254 }
255256/// Whether all set bits in a source flags value are also set in a target flags value.
257fn contains(&self, other: Self) -> bool258where
259Self: Sized,
260 {
261self.bits() & other.bits() == other.bits()
262 }
263264/// Remove any unknown bits from the flags.
265fn truncate(&mut self)
266where
267Self: Sized,
268 {
269*self = Self::from_bits_truncate(self.bits());
270 }
271272/// The bitwise or (`|`) of the bits in two flags values.
273fn insert(&mut self, other: Self)
274where
275Self: Sized,
276 {
277*self = Self::from_bits_retain(self.bits()).union(other);
278 }
279280/// The intersection of a source flags value with the complement of a target flags value (`&!`).
281 ///
282 /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
283 /// `remove` won't truncate `other`, but the `!` operator will.
284fn remove(&mut self, other: Self)
285where
286Self: Sized,
287 {
288*self = Self::from_bits_retain(self.bits()).difference(other);
289 }
290291/// The bitwise exclusive-or (`^`) of the bits in two flags values.
292fn toggle(&mut self, other: Self)
293where
294Self: Sized,
295 {
296*self = Self::from_bits_retain(self.bits()).symmetric_difference(other);
297 }
298299/// Call [`Flags::insert`] when `value` is `true` or [`Flags::remove`] when `value` is `false`.
300fn set(&mut self, other: Self, value: bool)
301where
302Self: Sized,
303 {
304if value {
305self.insert(other);
306 } else {
307self.remove(other);
308 }
309 }
310311/// Unsets all bits in the flags.
312fn clear(&mut self)
313where
314Self: Sized,
315 {
316*self = Self::empty();
317 }
318319/// The bitwise and (`&`) of the bits in two flags values.
320#[must_use]
321fn intersection(self, other: Self) -> Self {
322Self::from_bits_retain(self.bits() & other.bits())
323 }
324325/// The bitwise or (`|`) of the bits in two flags values.
326#[must_use]
327fn union(self, other: Self) -> Self {
328Self::from_bits_retain(self.bits() | other.bits())
329 }
330331/// The intersection of a source flags value with the complement of a target flags value (`&!`).
332 ///
333 /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
334 /// `difference` won't truncate `other`, but the `!` operator will.
335#[must_use]
336fn difference(self, other: Self) -> Self {
337Self::from_bits_retain(self.bits() & !other.bits())
338 }
339340/// The bitwise exclusive-or (`^`) of the bits in two flags values.
341#[must_use]
342fn symmetric_difference(self, other: Self) -> Self {
343Self::from_bits_retain(self.bits() ^ other.bits())
344 }
345346/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
347#[must_use]
348fn complement(self) -> Self {
349Self::from_bits_truncate(!self.bits())
350 }
351}
352353/**
354A bits type that can be used as storage for a flags type.
355*/
356pub trait Bits:
357Clone358 + Copy359 + PartialEq360 + BitAnd<Output = Self>
361 + BitOr<Output = Self>
362 + BitXor<Output = Self>
363 + Not<Output = Self>
364 + Sized365 + 'static
366{
367/// A value with all bits unset.
368const EMPTY: Self;
369370/// A value with all bits set.
371const ALL: Self;
372}
373374// Not re-exported: prevent custom `Bits` impls being used in the `bitflags!` macro,
375// or they may fail to compile based on crate features
376pub trait Primitive {}
377378macro_rules! impl_bits {
379 ($($u:ty, $i:ty,)*) => {
380 $(
381impl Bits for $u {
382const EMPTY: $u = 0;
383const ALL: $u = <$u>::MAX;
384 }
385386impl Bits for $i {
387const EMPTY: $i = 0;
388const ALL: $i = <$u>::MAX as $i;
389 }
390391impl ParseHex for $u {
392fn parse_hex(input: &str) -> Result<Self, ParseError> {
393 <$u>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
394 }
395 }
396397impl ParseHex for $i {
398fn parse_hex(input: &str) -> Result<Self, ParseError> {
399 <$i>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
400 }
401 }
402403impl WriteHex for $u {
404fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
405write!(writer, "{:x}", self)
406 }
407 }
408409impl WriteHex for $i {
410fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
411write!(writer, "{:x}", self)
412 }
413 }
414415impl Primitive for $i {}
416impl Primitive for $u {}
417 )*
418 }
419}
420421impl 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! {
422u8, i8,
423u16, i16,
424u32, i32,
425u64, i64,
426u128, i128,
427usize, isize,
428}429430/// A trait for referencing the `bitflags`-owned internal type
431/// without exposing it publicly.
432pub trait PublicFlags {
433/// The type of the underlying storage.
434type Primitive: Primitive;
435436/// The type of the internal field on the generated flags type.
437type Internal;
438}
439440#[doc(hidden)]
441#[deprecated(note = "use the `Flags` trait instead")]
442pub trait BitFlags: ImplementedByBitFlagsMacro + Flags {
443/// An iterator over enabled flags in an instance of the type.
444type Iter: Iterator<Item = Self>;
445446/// An iterator over the raw names and bits for enabled flags in an instance of the type.
447type IterNames: Iterator<Item = (&'static str, Self)>;
448}
449450#[allow(deprecated)]
451impl<B: Flags> BitFlagsfor B {
452type Iter = iter::Iter<Self>;
453type IterNames = iter::IterNames<Self>;
454}
455456impl<B: Flags> ImplementedByBitFlagsMacrofor B {}
457458/// A marker trait that signals that an implementation of `BitFlags` came from the `bitflags!` macro.
459///
460/// There's nothing stopping an end-user from implementing this trait, but we don't guarantee their
461/// manual implementations won't break between non-breaking releases.
462#[doc(hidden)]
463pub trait ImplementedByBitFlagsMacro {}
464465pub(crate) mod __private {
466pub use super::{ImplementedByBitFlagsMacro, PublicFlags};
467}