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/// This method will return `true` if any unknown bits are set.
156fn contains_unknown_bits(&self) -> bool {
157Self::all().bits() & self.bits() != self.bits()
158 }
159160/// Get the underlying bits value.
161 ///
162 /// The returned value is exactly the bits set in this flags value.
163fn bits(&self) -> Self::Bits;
164165/// Convert from a bits value.
166 ///
167 /// This method will return `None` if any unknown bits are set.
168fn from_bits(bits: Self::Bits) -> Option<Self> {
169let truncated = Self::from_bits_truncate(bits);
170171if truncated.bits() == bits {
172Some(truncated)
173 } else {
174None175 }
176 }
177178/// Convert from a bits value, unsetting any unknown bits.
179fn from_bits_truncate(bits: Self::Bits) -> Self {
180Self::from_bits_retain(bits & Self::all().bits())
181 }
182183/// Convert from a bits value exactly.
184fn from_bits_retain(bits: Self::Bits) -> Self;
185186/// Get a flags value with the bits of a flag with the given name set.
187 ///
188 /// This method will return `None` if `name` is empty or doesn't
189 /// correspond to any named flag.
190fn from_name(name: &str) -> Option<Self> {
191// Don't parse empty names as empty flags
192if name.is_empty() {
193return None;
194 }
195196for flag in Self::FLAGS {
197if flag.name() == name {
198return Some(Self::from_bits_retain(flag.value().bits()));
199 }
200 }
201202None203 }
204205/// Yield a set of contained flags values.
206 ///
207 /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
208 /// will be yielded together as a final flags value.
209fn iter(&self) -> iter::Iter<Self> {
210 iter::Iter::new(self)
211 }
212213/// Yield a set of contained named flags values.
214 ///
215 /// This method is like [`Flags::iter`], except only yields bits in contained named flags.
216 /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
217fn iter_names(&self) -> iter::IterNames<Self> {
218 iter::IterNames::new(self)
219 }
220221/// Yield a set of all named flags defined by [`Self::FLAGS`].
222fn iter_defined_names() -> iter::IterDefinedNames<Self> {
223 iter::IterDefinedNames::new()
224 }
225226/// Whether all bits in this flags value are unset.
227fn is_empty(&self) -> bool {
228self.bits() == Self::Bits::EMPTY229 }
230231/// Whether all known bits in this flags value are set.
232fn is_all(&self) -> bool {
233// NOTE: We check against `Self::all` here, not `Self::Bits::ALL`
234 // because the set of all flags may not use all bits
235Self::all().bits() | self.bits() == self.bits()
236 }
237238/// Whether any set bits in a source flags value are also set in a target flags value.
239fn intersects(&self, other: Self) -> bool240where
241Self: Sized,
242 {
243self.bits() & other.bits() != Self::Bits::EMPTY244 }
245246/// Whether all set bits in a source flags value are also set in a target flags value.
247fn contains(&self, other: Self) -> bool248where
249Self: Sized,
250 {
251self.bits() & other.bits() == other.bits()
252 }
253254/// Remove any unknown bits from the flags.
255fn truncate(&mut self)
256where
257Self: Sized,
258 {
259*self = Self::from_bits_truncate(self.bits());
260 }
261262/// The bitwise or (`|`) of the bits in two flags values.
263fn insert(&mut self, other: Self)
264where
265Self: Sized,
266 {
267*self = Self::from_bits_retain(self.bits()).union(other);
268 }
269270/// The intersection of a source flags value with the complement of a target flags value (`&!`).
271 ///
272 /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
273 /// `remove` won't truncate `other`, but the `!` operator will.
274fn remove(&mut self, other: Self)
275where
276Self: Sized,
277 {
278*self = Self::from_bits_retain(self.bits()).difference(other);
279 }
280281/// The bitwise exclusive-or (`^`) of the bits in two flags values.
282fn toggle(&mut self, other: Self)
283where
284Self: Sized,
285 {
286*self = Self::from_bits_retain(self.bits()).symmetric_difference(other);
287 }
288289/// Call [`Flags::insert`] when `value` is `true` or [`Flags::remove`] when `value` is `false`.
290fn set(&mut self, other: Self, value: bool)
291where
292Self: Sized,
293 {
294if value {
295self.insert(other);
296 } else {
297self.remove(other);
298 }
299 }
300301/// Unsets all bits in the flags.
302fn clear(&mut self)
303where
304Self: Sized,
305 {
306*self = Self::empty();
307 }
308309/// The bitwise and (`&`) of the bits in two flags values.
310#[must_use]
311fn intersection(self, other: Self) -> Self {
312Self::from_bits_retain(self.bits() & other.bits())
313 }
314315/// The bitwise or (`|`) of the bits in two flags values.
316#[must_use]
317fn union(self, other: Self) -> Self {
318Self::from_bits_retain(self.bits() | other.bits())
319 }
320321/// The intersection of a source flags value with the complement of a target flags value (`&!`).
322 ///
323 /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
324 /// `difference` won't truncate `other`, but the `!` operator will.
325#[must_use]
326fn difference(self, other: Self) -> Self {
327Self::from_bits_retain(self.bits() & !other.bits())
328 }
329330/// The bitwise exclusive-or (`^`) of the bits in two flags values.
331#[must_use]
332fn symmetric_difference(self, other: Self) -> Self {
333Self::from_bits_retain(self.bits() ^ other.bits())
334 }
335336/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
337#[must_use]
338fn complement(self) -> Self {
339Self::from_bits_truncate(!self.bits())
340 }
341}
342343/**
344A bits type that can be used as storage for a flags type.
345*/
346pub trait Bits:
347Clone348 + Copy349 + PartialEq350 + BitAnd<Output = Self>
351 + BitOr<Output = Self>
352 + BitXor<Output = Self>
353 + Not<Output = Self>
354 + Sized355 + 'static
356{
357/// A value with all bits unset.
358const EMPTY: Self;
359360/// A value with all bits set.
361const ALL: Self;
362}
363364// Not re-exported: prevent custom `Bits` impls being used in the `bitflags!` macro,
365// or they may fail to compile based on crate features
366pub trait Primitive {}
367368macro_rules! impl_bits {
369 ($($u:ty, $i:ty,)*) => {
370 $(
371impl Bits for $u {
372const EMPTY: $u = 0;
373const ALL: $u = <$u>::MAX;
374 }
375376impl Bits for $i {
377const EMPTY: $i = 0;
378const ALL: $i = <$u>::MAX as $i;
379 }
380381impl ParseHex for $u {
382fn parse_hex(input: &str) -> Result<Self, ParseError> {
383 <$u>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
384 }
385 }
386387impl ParseHex for $i {
388fn parse_hex(input: &str) -> Result<Self, ParseError> {
389 <$i>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
390 }
391 }
392393impl WriteHex for $u {
394fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
395write!(writer, "{:x}", self)
396 }
397 }
398399impl WriteHex for $i {
400fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
401write!(writer, "{:x}", self)
402 }
403 }
404405impl Primitive for $i {}
406impl Primitive for $u {}
407 )*
408 }
409}
410411impl 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! {
412u8, i8,
413u16, i16,
414u32, i32,
415u64, i64,
416u128, i128,
417usize, isize,
418}419420/// A trait for referencing the `bitflags`-owned internal type
421/// without exposing it publicly.
422pub trait PublicFlags {
423/// The type of the underlying storage.
424type Primitive: Primitive;
425426/// The type of the internal field on the generated flags type.
427type Internal;
428}
429430#[doc(hidden)]
431#[deprecated(note = "use the `Flags` trait instead")]
432pub trait BitFlags: ImplementedByBitFlagsMacro + Flags {
433/// An iterator over enabled flags in an instance of the type.
434type Iter: Iterator<Item = Self>;
435436/// An iterator over the raw names and bits for enabled flags in an instance of the type.
437type IterNames: Iterator<Item = (&'static str, Self)>;
438}
439440#[allow(deprecated)]
441impl<B: Flags> BitFlagsfor B {
442type Iter = iter::Iter<Self>;
443type IterNames = iter::IterNames<Self>;
444}
445446impl<B: Flags> ImplementedByBitFlagsMacrofor B {}
447448/// A marker trait that signals that an implementation of `BitFlags` came from the `bitflags!` macro.
449///
450/// There's nothing stopping an end-user from implementing this trait, but we don't guarantee their
451/// manual implementations won't break between non-breaking releases.
452#[doc(hidden)]
453pub trait ImplementedByBitFlagsMacro {}
454455pub(crate) mod __private {
456pub use super::{ImplementedByBitFlagsMacro, PublicFlags};
457}