<commit_before>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A typesafe bitmask flag generator useful for sets of C-style bitmask flags.
//! It can be used for creating typesafe wrappers around C APIs.
//!
//! The `bitflags!` macro generates `struct`s that manage a set of flags. The
//! flags should only be defined for integer types, otherwise unexpected type
//! errors may occur at compile time.
//!
//! # Example
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!         const ABC = Self::A.bits | Self::B.bits | Self::C.bits;
//!     }
//! }
//!
//! fn main() {
//!     let e1 = Flags::A | Flags::C;
//!     let e2 = Flags::B | Flags::C;
//!     assert_eq!((e1 | e2), Flags::ABC);   // union
//!     assert_eq!((e1 & e2), Flags::C);     // intersection
//!     assert_eq!((e1 - e2), Flags::A);     // set difference
//!     assert_eq!(!e2, Flags::A);           // set complement
//! }
//! ```
//!
//! See [`example_generated::Flags`](./example_generated/struct.Flags.html) for documentation of code
//! generated by the above `bitflags!` expansion.
//!
//! The generated `struct`s can also be extended with type and trait
//! implementations:
//!
//! ```
//! use std::fmt;
//!
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!     }
//! }
//!
//! impl Flags {
//!     pub fn clear(&mut self) {
//!         self.bits = 0;  // The `bits` field can be accessed from within the
//!                         // same module where the `bitflags!` macro was invoked.
//!     }
//! }
//!
//! impl fmt::Display for Flags {
//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//!         write!(f, "hi!")
//!     }
//! }
//!
//! fn main() {
//!     let mut flags = Flags::A | Flags::B;
//!     flags.clear();
//!     assert!(flags.is_empty());
//!     assert_eq!(format!("{}", flags), "hi!");
//!     assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B");
//!     assert_eq!(format!("{:?}", Flags::B), "B");
//! }
//! ```
//!
//! # Visibility
//!
//! The generated structs and their associated flag constants are not exported
//! out of the current module by default. A definition can be exported out of
//! the current module by adding `pub` before `struct`:
//!
//! ```
//! mod example {
//!     use bitflags::bitflags;
//!
//!     bitflags! {
//!         pub struct Flags1: u32 {
//!             const A = 0b00000001;
//!         }
//!
//! #       pub
//!         struct Flags2: u32 {
//!             const B = 0b00000010;
//!         }
//!     }
//! }
//!
//! fn main() {
//!     let flag1 = example::Flags1::A;
//!     let flag2 = example::Flags2::B; // error: const `B` is private
//! }
//! ```
//!
//! # Attributes
//!
//! Attributes can be attached to the generated `struct`s by placing them
//! before the `struct` keyword.
//!
//! ## Representations
//!
//! It's valid to add a `#[repr(C)]` or `#[repr(transparent)]` attribute to a type
//! generated by `bitflags!`. In these cases, the type is guaranteed to be a newtype.
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     #[repr(transparent)]
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!     }
//! }
//! ```
//!
//! # Trait implementations
//!
//! The `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord` and `Hash`
//! traits are automatically derived for the `struct`s using the `derive` attribute.
//! Additional traits can be derived by providing an explicit `derive`
//! attribute on `struct`.
//!
//! The `Extend` and `FromIterator` traits are implemented for the `struct`s,
//! too: `Extend` adds the union of the instances of the `struct` iterated over,
//! while `FromIterator` calculates the union.
//!
//! The `Binary`, `Debug`, `LowerHex`, `Octal` and `UpperHex` traits are also
//! implemented by displaying the bits value of the internal struct.
//!
//! ## Operators
//!
//! The following operator traits are implemented for the generated `struct`s:
//!
//! - `BitOr` and `BitOrAssign`: union
//! - `BitAnd` and `BitAndAssign`: intersection
//! - `BitXor` and `BitXorAssign`: toggle
//! - `Sub` and `SubAssign`: set difference
//! - `Not`: set complement
//!
//! # Methods
//!
//! The following methods are defined for the generated `struct`s:
//!
//! - `empty`: an empty set of flags
//! - `all`: the set of all defined flags
//! - `bits`: the raw value of the flags currently stored
//! - `from_bits`: convert from underlying bit representation, unless that
//!                representation contains bits that do not correspond to a
//!                defined flag
//! - `from_bits_truncate`: convert from underlying bit representation, dropping
//!                         any bits that do not correspond to defined flags
//! - `from_bits_unchecked`: convert from underlying bit representation, keeping
//!                          all bits (even those not corresponding to defined
//!                          flags)
//! - `is_empty`: `true` if no flags are currently stored
//! - `is_all`: `true` if currently set flags exactly equal all defined flags
//! - `intersects`: `true` if there are flags common to both `self` and `other`
//! - `contains`: `true` if all of the flags in `other` are contained within `self`
//! - `insert`: inserts the specified flags in-place
//! - `remove`: removes the specified flags in-place
//! - `toggle`: the specified flags will be inserted if not present, and removed
//!             if they are.
//! - `set`: inserts or removes the specified flags depending on the passed value
//! - `intersection`: returns a new set of flags, containing only the flags present
//!                   in both `self` and `other` (the argument to the function).
//! - `union`: returns a new set of flags, containing any flags present in
//!            either `self` or `other` (the argument to the function).
//! - `difference`: returns a new set of flags, containing all flags present in
//!                 `self` without any of the flags present in `other` (the
//!                 argument to the function).
//! - `symmetric_difference`: returns a new set of flags, containing all flags
//!                           present in either `self` or `other` (the argument
//!                           to the function), but not both.
//! - `complement`: returns a new set of flags, containing all flags which are
//!                 not set in `self`, but which are allowed for this type.
//!
//! ## Default
//!
//! The `Default` trait is not automatically implemented for the generated structs.
//!
//! If your default value is equal to `0` (which is the same value as calling `empty()`
//! on the generated struct), you can simply derive `Default`:
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     // Results in default value with bits: 0
//!     #[derive(Default)]
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!     }
//! }
//!
//! fn main() {
//!     let derived_default: Flags = Default::default();
//!     assert_eq!(derived_default.bits(), 0);
//! }
//! ```
//!
//! If your default value is not equal to `0` you need to implement `Default` yourself:
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!     }
//! }
//!
//! // explicit `Default` implementation
//! impl Default for Flags {
//!     fn default() -> Flags {
//!         Flags::A | Flags::C
//!     }
//! }
//!
//! fn main() {
//!     let implemented_default: Flags = Default::default();
//!     assert_eq!(implemented_default, (Flags::A | Flags::C));
//! }
//! ```
//!
//! # Zero Flags
//!
//! Flags with a value equal to zero will have some strange behavior that one should be aware of.
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const NONE = 0b00000000;
//!         const SOME = 0b00000001;
//!     }
//! }
//!
//! fn main() {
//!     let empty = Flags::empty();
//!     let none = Flags::NONE;
//!     let some = Flags::SOME;
//!
//!     // Zero flags are treated as always present
//!     assert!(empty.contains(Flags::NONE));
//!     assert!(none.contains(Flags::NONE));
//!     assert!(some.contains(Flags::NONE));
//!
//!     // Zero flags will be ignored when testing for emptiness
//!     assert!(none.is_empty());
//! }
//! ```
//!
//! Users should generally avoid defining a flag with a value of zero.

#![cfg_attr(not(test), no_std)]
#![doc(html_root_url = "https://docs.rs/bitflags/1.3.2")]

#[doc(hidden)]
pub extern crate core as _core;

#[doc(inline)]
pub use bitflags_trait::BitFlags;

mod bitflags_trait;

#[doc(hidden)]
pub mod __private {
    pub use crate::bitflags_trait::ImplementedByBitFlagsMacro;
}

/// The macro used to generate the flag structure.
///
/// See the [crate level docs](../bitflags/index.html) for complete documentation.
///
/// # Example
///
/// ```
/// use bitflags::bitflags;
///
/// bitflags! {
///     struct Flags: u32 {
///         const A = 0b00000001;
///         const B = 0b00000010;
///         const C = 0b00000100;
///         const ABC = Self::A.bits | Self::B.bits | Self::C.bits;
///     }
/// }
///
/// fn main() {
///     let e1 = Flags::A | Flags::C;
///     let e2 = Flags::B | Flags::C;
///     assert_eq!((e1 | e2), Flags::ABC);   // union
///     assert_eq!((e1 & e2), Flags::C);     // intersection
///     assert_eq!((e1 - e2), Flags::A);     // set difference
///     assert_eq!(!e2, Flags::A);           // set complement
/// }
/// ```
///
/// The generated `struct`s can also be extended with type and trait
/// implementations:
///
/// ```
/// use std::fmt;
///
/// use bitflags::bitflags;
///
/// bitflags! {
///     struct Flags: u32 {
///         const A = 0b00000001;
///         const B = 0b00000010;
///     }
/// }
///
/// impl Flags {
///     pub fn clear(&mut self) {
///         self.bits = 0;  // The `bits` field can be accessed from within the
///                         // same module where the `bitflags!` macro was invoked.
///     }
/// }
///
/// impl fmt::Display for Flags {
///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
///         write!(f, "hi!")
///     }
/// }
///
/// fn main() {
///     let mut flags = Flags::A | Flags::B;
///     flags.clear();
///     assert!(flags.is_empty());
///     assert_eq!(format!("{}", flags), "hi!");
///     assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B");
///     assert_eq!(format!("{:?}", Flags::B), "B");
/// }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! bitflags {
    (
        $(#[$outer:meta])*
        $vis:vis struct $BitFlags:ident: $T:ty {
            $(
                $(#[$inner:ident $($args:tt)*])*
                const $Flag:ident = $value:expr;
            )*
        }

        $($t:tt)*
    ) => {
        $(#[$outer])*
        #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
        $vis struct $BitFlags {
            bits: $T,
        }

        __impl_bitflags! {
            $BitFlags: $T {
                $(
                    $(#[$inner $($args)*])*
                    $Flag = $value;
                )*
            }
        }

        bitflags! {
            $($t)*
        }
    };
    () => {};
}

// A helper macro to implement the `all` function.
#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __impl_all_bitflags {
    (
        $BitFlags:ident: $T:ty {
            $(
                $(#[$attr:ident $($args:tt)*])*
                $Flag:ident = $value:expr;
            )+
        }
    ) => {
        // See `Debug::fmt` for why this approach is taken.
        #[allow(non_snake_case)]
        trait __BitFlags {
            $(
                const $Flag: $T = 0;
            )+
        }
        #[allow(non_snake_case)]
        impl __BitFlags for $BitFlags {
            $(
                __impl_bitflags! {
                    #[allow(deprecated)]
                    $(? #[$attr $($args)*])*
                    const $Flag: $T = Self::$Flag.bits;
                }
            )+
        }
        Self { bits: $(<Self as __BitFlags>::$Flag)|+ }
    };
    (
        $BitFlags:ident: $T:ty { }
    ) => {
        Self { bits: 0 }
    };
}

#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __impl_bitflags {
    (
        $BitFlags:ident: $T:ty {
            $(
                $(#[$attr:ident $($args:tt)*])*
                $Flag:ident = $value:expr;
            )*
        }
    ) => {
        impl $crate::_core::fmt::Debug for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                // This convoluted approach is to handle #[cfg]-based flag
                // omission correctly. For example it needs to support:
                //
                //    #[cfg(unix)] const A: Flag = /* ... */;
                //    #[cfg(windows)] const B: Flag = /* ... */;

                // Unconditionally define a check for every flag, even disabled
                // ones.
                #[allow(non_snake_case)]
                trait __BitFlags {
                    $(
                        #[inline]
                        fn $Flag(&self) -> bool { false }
                    )*
                }

                // Conditionally override the check for just those flags that
                // are not #[cfg]ed away.
                #[allow(non_snake_case)]
                impl __BitFlags for $BitFlags {
                    $(
                        __impl_bitflags! {
                            #[allow(deprecated)]
                            #[inline]
                            $(? #[$attr $($args)*])*
                            fn $Flag(&self) -> bool {
                                if Self::$Flag.bits == 0 && self.bits != 0 {
                                    false
                                } else {
                                    self.bits & Self::$Flag.bits == Self::$Flag.bits
                                }
                            }
                        }
                    )*
                }

                let mut first = true;
                $(
                    if <Self as __BitFlags>::$Flag(self) {
                        if !first {
                            f.write_str(" | ")?;
                        }
                        first = false;
                        f.write_str($crate::_core::stringify!($Flag))?;
                    }
                )*
                let extra_bits = self.bits & !Self::all().bits();
                if extra_bits != 0 {
                    if !first {
                        f.write_str(" | ")?;
                    }
                    first = false;
                    $crate::_core::write!(f, "{:#x}", extra_bits)?;
                }
                if first {
                    f.write_str("(empty)")?;
                }
                $crate::_core::fmt::Result::Ok(())
            }
        }
        impl $crate::_core::fmt::Binary for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::Binary::fmt(&self.bits, f)
            }
        }
        impl $crate::_core::fmt::Octal for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::Octal::fmt(&self.bits, f)
            }
        }
        impl $crate::_core::fmt::LowerHex for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::LowerHex::fmt(&self.bits, f)
            }
        }
        impl $crate::_core::fmt::UpperHex for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::UpperHex::fmt(&self.bits, f)
            }
        }

        #[allow(dead_code)]
        impl $BitFlags {
            $(
                $(#[$attr $($args)*])*
                pub const $Flag: Self = Self { bits: $value };
            )*

            /// Returns an empty set of flags.
            #[inline]
            pub const fn empty() -> Self {
                Self { bits: 0 }
            }

            /// Returns the set containing all flags.
            #[inline]
            pub const fn all() -> Self {
                __impl_all_bitflags! {
                    $BitFlags: $T {
                        $(
                            $(#[$attr $($args)*])*
                            $Flag = $value;
                        )*
                    }
                }
            }

            /// Returns the raw value of the flags currently stored.
            #[inline]
            pub const fn bits(&self) -> $T {
                self.bits
            }

            /// Convert from underlying bit representation, unless that
            /// representation contains bits that do not correspond to a flag.
            #[inline]
            pub const fn from_bits(bits: $T) -> $crate::_core::option::Option<Self> {
                if (bits & !Self::all().bits()) == 0 {
                    $crate::_core::option::Option::Some(Self { bits })
                } else {
                    $crate::_core::option::Option::None
                }
            }

            /// Convert from underlying bit representation, dropping any bits
            /// that do not correspond to flags.
            #[inline]
            pub const fn from_bits_truncate(bits: $T) -> Self {
                Self { bits: bits & Self::all().bits }
            }

            /// Convert from underlying bit representation, preserving all
            /// bits (even those not corresponding to a defined flag).
            ///
            /// # Safety
            ///
            /// The caller of the `bitflags!` macro can choose to allow or
            /// disallow extra bits for their bitflags type.
            ///
            /// The caller of `from_bits_unchecked()` has to ensure that
            /// all bits correspond to a defined flag or that extra bits
            /// are valid for this bitflags type.
            #[inline]
            pub const unsafe fn from_bits_unchecked(bits: $T) -> Self {
                Self { bits }
            }

            /// Returns `true` if no flags are currently stored.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.bits() == Self::empty().bits()
            }

            /// Returns `true` if all flags are currently set.
            #[inline]
            pub const fn is_all(&self) -> bool {
                Self::all().bits | self.bits == self.bits
            }

            /// Returns `true` if there are flags common to both `self` and `other`.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                !(Self { bits: self.bits & other.bits}).is_empty()
            }

            /// Returns `true` if all of the flags in `other` are contained within `self`.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                (self.bits & other.bits) == other.bits
            }

            /// Inserts the specified flags in-place.
            #[inline]
            pub fn insert(&mut self, other: Self) {
                self.bits |= other.bits;
            }

            /// Removes the specified flags in-place.
            #[inline]
            pub fn remove(&mut self, other: Self) {
                self.bits &= !other.bits;
            }

            /// Toggles the specified flags in-place.
            #[inline]
            pub fn toggle(&mut self, other: Self) {
                self.bits ^= other.bits;
            }

            /// Inserts or removes the specified flags depending on the passed value.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                if value {
                    self.insert(other);
                } else {
                    self.remove(other);
                }
            }

            /// Returns the intersection between the flags in `self` and
            /// `other`.
            ///
            /// Specifically, the returned set contains only the flags which are
            /// present in *both* `self` *and* `other`.
            ///
            /// This is equivalent to using the `&` operator (e.g.
            /// [`ops::BitAnd`]), as in `flags & other`.
            ///
            /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self { bits: self.bits & other.bits }
            }

            /// Returns the union of between the flags in `self` and `other`.
            ///
            /// Specifically, the returned set contains all flags which are
            /// present in *either* `self` *or* `other`, including any which are
            /// present in both (see [`Self::symmetric_difference`] if that
            /// is undesirable).
            ///
            /// This is equivalent to using the `|` operator (e.g.
            /// [`ops::BitOr`]), as in `flags | other`.
            ///
            /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self { bits: self.bits | other.bits }
            }

            /// Returns the difference between the flags in `self` and `other`.
            ///
            /// Specifically, the returned set contains all flags present in
            /// `self`, except for the ones present in `other`.
            ///
            /// It is also conceptually equivalent to the "bit-clear" operation:
            /// `flags & !other` (and this syntax is also supported).
            ///
            /// This is equivalent to using the `-` operator (e.g.
            /// [`ops::Sub`]), as in `flags - other`.
            ///
            /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self { bits: self.bits & !other.bits }
            }

            /// Returns the [symmetric difference][sym-diff] between the flags
            /// in `self` and `other`.
            ///
            /// Specifically, the returned set contains the flags present which
            /// are present in `self` or `other`, but that are not present in
            /// both. Equivalently, it contains the flags present in *exactly
            /// one* of the sets `self` and `other`.
            ///
            /// This is equivalent to using the `^` operator (e.g.
            /// [`ops::BitXor`]), as in `flags ^ other`.
            ///
            /// [sym-diff]: https://en.wikipedia.org/wiki/Symmetric_difference
            /// [`ops::BitXor`]: https://doc.rust-lang.org/std/ops/trait.BitXor.html
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self { bits: self.bits ^ other.bits }
            }

            /// Returns the complement of this set of flags.
            ///
            /// Specifically, the returned set contains all the flags which are
            /// not set in `self`, but which are allowed for this type.
            ///
            /// Alternatively, it can be thought of as the set difference
            /// between [`Self::all()`] and `self` (e.g. `Self::all() - self`)
            ///
            /// This is equivalent to using the `!` operator (e.g.
            /// [`ops::Not`]), as in `!flags`.
            ///
            /// [`Self::all()`]: Self::all
            /// [`ops::Not`]: https://doc.rust-lang.org/std/ops/trait.Not.html
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self::from_bits_truncate(!self.bits)
            }

            /// Returns an iterator over all the flags in this set.
            pub fn iter(mut self) -> impl Iterator<Item = Self> {
                let mut options = [
                    $(
                        #[allow(unused_doc_comments, unused_attributes)]
                        $(#[$attr $($args)*])*
                        Self::$Flag,
                    )*
                ];
                const NUM_FLAGS: usize = {
                    #[allow(unused_mut)]
                    let mut num_flags = 0;

                    $(
                        #[allow(unused_doc_comments, unused_attributes)]
                        $(#[$attr $($args)*])*
                        {
                            num_flags += 1;
                        }
                    )*

                    num_flags
                };
                let mut start = 0;

                $crate::_core::iter::from_fn(move || {
                    if self.is_empty() || NUM_FLAGS == 0 || start == NUM_FLAGS {
                        None
                    }else{
                        for pos in start..NUM_FLAGS {
                            let flag = options[pos];
                            start += 1;<commit_msg>iterator: options array doesn't need to be mut<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A typesafe bitmask flag generator useful for sets of C-style bitmask flags.
//! It can be used for creating typesafe wrappers around C APIs.
//!
//! The `bitflags!` macro generates `struct`s that manage a set of flags. The
//! flags should only be defined for integer types, otherwise unexpected type
//! errors may occur at compile time.
//!
//! # Example
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!         const ABC = Self::A.bits | Self::B.bits | Self::C.bits;
//!     }
//! }
//!
//! fn main() {
//!     let e1 = Flags::A | Flags::C;
//!     let e2 = Flags::B | Flags::C;
//!     assert_eq!((e1 | e2), Flags::ABC);   // union
//!     assert_eq!((e1 & e2), Flags::C);     // intersection
//!     assert_eq!((e1 - e2), Flags::A);     // set difference
//!     assert_eq!(!e2, Flags::A);           // set complement
//! }
//! ```
//!
//! See [`example_generated::Flags`](./example_generated/struct.Flags.html) for documentation of code
//! generated by the above `bitflags!` expansion.
//!
//! The generated `struct`s can also be extended with type and trait
//! implementations:
//!
//! ```
//! use std::fmt;
//!
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!     }
//! }
//!
//! impl Flags {
//!     pub fn clear(&mut self) {
//!         self.bits = 0;  // The `bits` field can be accessed from within the
//!                         // same module where the `bitflags!` macro was invoked.
//!     }
//! }
//!
//! impl fmt::Display for Flags {
//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//!         write!(f, "hi!")
//!     }
//! }
//!
//! fn main() {
//!     let mut flags = Flags::A | Flags::B;
//!     flags.clear();
//!     assert!(flags.is_empty());
//!     assert_eq!(format!("{}", flags), "hi!");
//!     assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B");
//!     assert_eq!(format!("{:?}", Flags::B), "B");
//! }
//! ```
//!
//! # Visibility
//!
//! The generated structs and their associated flag constants are not exported
//! out of the current module by default. A definition can be exported out of
//! the current module by adding `pub` before `struct`:
//!
//! ```
//! mod example {
//!     use bitflags::bitflags;
//!
//!     bitflags! {
//!         pub struct Flags1: u32 {
//!             const A = 0b00000001;
//!         }
//!
//! #       pub
//!         struct Flags2: u32 {
//!             const B = 0b00000010;
//!         }
//!     }
//! }
//!
//! fn main() {
//!     let flag1 = example::Flags1::A;
//!     let flag2 = example::Flags2::B; // error: const `B` is private
//! }
//! ```
//!
//! # Attributes
//!
//! Attributes can be attached to the generated `struct`s by placing them
//! before the `struct` keyword.
//!
//! ## Representations
//!
//! It's valid to add a `#[repr(C)]` or `#[repr(transparent)]` attribute to a type
//! generated by `bitflags!`. In these cases, the type is guaranteed to be a newtype.
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     #[repr(transparent)]
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!     }
//! }
//! ```
//!
//! # Trait implementations
//!
//! The `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord` and `Hash`
//! traits are automatically derived for the `struct`s using the `derive` attribute.
//! Additional traits can be derived by providing an explicit `derive`
//! attribute on `struct`.
//!
//! The `Extend` and `FromIterator` traits are implemented for the `struct`s,
//! too: `Extend` adds the union of the instances of the `struct` iterated over,
//! while `FromIterator` calculates the union.
//!
//! The `Binary`, `Debug`, `LowerHex`, `Octal` and `UpperHex` traits are also
//! implemented by displaying the bits value of the internal struct.
//!
//! ## Operators
//!
//! The following operator traits are implemented for the generated `struct`s:
//!
//! - `BitOr` and `BitOrAssign`: union
//! - `BitAnd` and `BitAndAssign`: intersection
//! - `BitXor` and `BitXorAssign`: toggle
//! - `Sub` and `SubAssign`: set difference
//! - `Not`: set complement
//!
//! # Methods
//!
//! The following methods are defined for the generated `struct`s:
//!
//! - `empty`: an empty set of flags
//! - `all`: the set of all defined flags
//! - `bits`: the raw value of the flags currently stored
//! - `from_bits`: convert from underlying bit representation, unless that
//!                representation contains bits that do not correspond to a
//!                defined flag
//! - `from_bits_truncate`: convert from underlying bit representation, dropping
//!                         any bits that do not correspond to defined flags
//! - `from_bits_unchecked`: convert from underlying bit representation, keeping
//!                          all bits (even those not corresponding to defined
//!                          flags)
//! - `is_empty`: `true` if no flags are currently stored
//! - `is_all`: `true` if currently set flags exactly equal all defined flags
//! - `intersects`: `true` if there are flags common to both `self` and `other`
//! - `contains`: `true` if all of the flags in `other` are contained within `self`
//! - `insert`: inserts the specified flags in-place
//! - `remove`: removes the specified flags in-place
//! - `toggle`: the specified flags will be inserted if not present, and removed
//!             if they are.
//! - `set`: inserts or removes the specified flags depending on the passed value
//! - `intersection`: returns a new set of flags, containing only the flags present
//!                   in both `self` and `other` (the argument to the function).
//! - `union`: returns a new set of flags, containing any flags present in
//!            either `self` or `other` (the argument to the function).
//! - `difference`: returns a new set of flags, containing all flags present in
//!                 `self` without any of the flags present in `other` (the
//!                 argument to the function).
//! - `symmetric_difference`: returns a new set of flags, containing all flags
//!                           present in either `self` or `other` (the argument
//!                           to the function), but not both.
//! - `complement`: returns a new set of flags, containing all flags which are
//!                 not set in `self`, but which are allowed for this type.
//!
//! ## Default
//!
//! The `Default` trait is not automatically implemented for the generated structs.
//!
//! If your default value is equal to `0` (which is the same value as calling `empty()`
//! on the generated struct), you can simply derive `Default`:
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     // Results in default value with bits: 0
//!     #[derive(Default)]
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!     }
//! }
//!
//! fn main() {
//!     let derived_default: Flags = Default::default();
//!     assert_eq!(derived_default.bits(), 0);
//! }
//! ```
//!
//! If your default value is not equal to `0` you need to implement `Default` yourself:
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const A = 0b00000001;
//!         const B = 0b00000010;
//!         const C = 0b00000100;
//!     }
//! }
//!
//! // explicit `Default` implementation
//! impl Default for Flags {
//!     fn default() -> Flags {
//!         Flags::A | Flags::C
//!     }
//! }
//!
//! fn main() {
//!     let implemented_default: Flags = Default::default();
//!     assert_eq!(implemented_default, (Flags::A | Flags::C));
//! }
//! ```
//!
//! # Zero Flags
//!
//! Flags with a value equal to zero will have some strange behavior that one should be aware of.
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//!     struct Flags: u32 {
//!         const NONE = 0b00000000;
//!         const SOME = 0b00000001;
//!     }
//! }
//!
//! fn main() {
//!     let empty = Flags::empty();
//!     let none = Flags::NONE;
//!     let some = Flags::SOME;
//!
//!     // Zero flags are treated as always present
//!     assert!(empty.contains(Flags::NONE));
//!     assert!(none.contains(Flags::NONE));
//!     assert!(some.contains(Flags::NONE));
//!
//!     // Zero flags will be ignored when testing for emptiness
//!     assert!(none.is_empty());
//! }
//! ```
//!
//! Users should generally avoid defining a flag with a value of zero.

#![cfg_attr(not(test), no_std)]
#![doc(html_root_url = "https://docs.rs/bitflags/1.3.2")]

#[doc(hidden)]
pub extern crate core as _core;

#[doc(inline)]
pub use bitflags_trait::BitFlags;

mod bitflags_trait;

#[doc(hidden)]
pub mod __private {
    pub use crate::bitflags_trait::ImplementedByBitFlagsMacro;
}

/// The macro used to generate the flag structure.
///
/// See the [crate level docs](../bitflags/index.html) for complete documentation.
///
/// # Example
///
/// ```
/// use bitflags::bitflags;
///
/// bitflags! {
///     struct Flags: u32 {
///         const A = 0b00000001;
///         const B = 0b00000010;
///         const C = 0b00000100;
///         const ABC = Self::A.bits | Self::B.bits | Self::C.bits;
///     }
/// }
///
/// fn main() {
///     let e1 = Flags::A | Flags::C;
///     let e2 = Flags::B | Flags::C;
///     assert_eq!((e1 | e2), Flags::ABC);   // union
///     assert_eq!((e1 & e2), Flags::C);     // intersection
///     assert_eq!((e1 - e2), Flags::A);     // set difference
///     assert_eq!(!e2, Flags::A);           // set complement
/// }
/// ```
///
/// The generated `struct`s can also be extended with type and trait
/// implementations:
///
/// ```
/// use std::fmt;
///
/// use bitflags::bitflags;
///
/// bitflags! {
///     struct Flags: u32 {
///         const A = 0b00000001;
///         const B = 0b00000010;
///     }
/// }
///
/// impl Flags {
///     pub fn clear(&mut self) {
///         self.bits = 0;  // The `bits` field can be accessed from within the
///                         // same module where the `bitflags!` macro was invoked.
///     }
/// }
///
/// impl fmt::Display for Flags {
///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
///         write!(f, "hi!")
///     }
/// }
///
/// fn main() {
///     let mut flags = Flags::A | Flags::B;
///     flags.clear();
///     assert!(flags.is_empty());
///     assert_eq!(format!("{}", flags), "hi!");
///     assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B");
///     assert_eq!(format!("{:?}", Flags::B), "B");
/// }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! bitflags {
    (
        $(#[$outer:meta])*
        $vis:vis struct $BitFlags:ident: $T:ty {
            $(
                $(#[$inner:ident $($args:tt)*])*
                const $Flag:ident = $value:expr;
            )*
        }

        $($t:tt)*
    ) => {
        $(#[$outer])*
        #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
        $vis struct $BitFlags {
            bits: $T,
        }

        __impl_bitflags! {
            $BitFlags: $T {
                $(
                    $(#[$inner $($args)*])*
                    $Flag = $value;
                )*
            }
        }

        bitflags! {
            $($t)*
        }
    };
    () => {};
}

// A helper macro to implement the `all` function.
#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __impl_all_bitflags {
    (
        $BitFlags:ident: $T:ty {
            $(
                $(#[$attr:ident $($args:tt)*])*
                $Flag:ident = $value:expr;
            )+
        }
    ) => {
        // See `Debug::fmt` for why this approach is taken.
        #[allow(non_snake_case)]
        trait __BitFlags {
            $(
                const $Flag: $T = 0;
            )+
        }
        #[allow(non_snake_case)]
        impl __BitFlags for $BitFlags {
            $(
                __impl_bitflags! {
                    #[allow(deprecated)]
                    $(? #[$attr $($args)*])*
                    const $Flag: $T = Self::$Flag.bits;
                }
            )+
        }
        Self { bits: $(<Self as __BitFlags>::$Flag)|+ }
    };
    (
        $BitFlags:ident: $T:ty { }
    ) => {
        Self { bits: 0 }
    };
}

#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __impl_bitflags {
    (
        $BitFlags:ident: $T:ty {
            $(
                $(#[$attr:ident $($args:tt)*])*
                $Flag:ident = $value:expr;
            )*
        }
    ) => {
        impl $crate::_core::fmt::Debug for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                // This convoluted approach is to handle #[cfg]-based flag
                // omission correctly. For example it needs to support:
                //
                //    #[cfg(unix)] const A: Flag = /* ... */;
                //    #[cfg(windows)] const B: Flag = /* ... */;

                // Unconditionally define a check for every flag, even disabled
                // ones.
                #[allow(non_snake_case)]
                trait __BitFlags {
                    $(
                        #[inline]
                        fn $Flag(&self) -> bool { false }
                    )*
                }

                // Conditionally override the check for just those flags that
                // are not #[cfg]ed away.
                #[allow(non_snake_case)]
                impl __BitFlags for $BitFlags {
                    $(
                        __impl_bitflags! {
                            #[allow(deprecated)]
                            #[inline]
                            $(? #[$attr $($args)*])*
                            fn $Flag(&self) -> bool {
                                if Self::$Flag.bits == 0 && self.bits != 0 {
                                    false
                                } else {
                                    self.bits & Self::$Flag.bits == Self::$Flag.bits
                                }
                            }
                        }
                    )*
                }

                let mut first = true;
                $(
                    if <Self as __BitFlags>::$Flag(self) {
                        if !first {
                            f.write_str(" | ")?;
                        }
                        first = false;
                        f.write_str($crate::_core::stringify!($Flag))?;
                    }
                )*
                let extra_bits = self.bits & !Self::all().bits();
                if extra_bits != 0 {
                    if !first {
                        f.write_str(" | ")?;
                    }
                    first = false;
                    $crate::_core::write!(f, "{:#x}", extra_bits)?;
                }
                if first {
                    f.write_str("(empty)")?;
                }
                $crate::_core::fmt::Result::Ok(())
            }
        }
        impl $crate::_core::fmt::Binary for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::Binary::fmt(&self.bits, f)
            }
        }
        impl $crate::_core::fmt::Octal for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::Octal::fmt(&self.bits, f)
            }
        }
        impl $crate::_core::fmt::LowerHex for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::LowerHex::fmt(&self.bits, f)
            }
        }
        impl $crate::_core::fmt::UpperHex for $BitFlags {
            fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
                $crate::_core::fmt::UpperHex::fmt(&self.bits, f)
            }
        }

        #[allow(dead_code)]
        impl $BitFlags {
            $(
                $(#[$attr $($args)*])*
                pub const $Flag: Self = Self { bits: $value };
            )*

            /// Returns an empty set of flags.
            #[inline]
            pub const fn empty() -> Self {
                Self { bits: 0 }
            }

            /// Returns the set containing all flags.
            #[inline]
            pub const fn all() -> Self {
                __impl_all_bitflags! {
                    $BitFlags: $T {
                        $(
                            $(#[$attr $($args)*])*
                            $Flag = $value;
                        )*
                    }
                }
            }

            /// Returns the raw value of the flags currently stored.
            #[inline]
            pub const fn bits(&self) -> $T {
                self.bits
            }

            /// Convert from underlying bit representation, unless that
            /// representation contains bits that do not correspond to a flag.
            #[inline]
            pub const fn from_bits(bits: $T) -> $crate::_core::option::Option<Self> {
                if (bits & !Self::all().bits()) == 0 {
                    $crate::_core::option::Option::Some(Self { bits })
                } else {
                    $crate::_core::option::Option::None
                }
            }

            /// Convert from underlying bit representation, dropping any bits
            /// that do not correspond to flags.
            #[inline]
            pub const fn from_bits_truncate(bits: $T) -> Self {
                Self { bits: bits & Self::all().bits }
            }

            /// Convert from underlying bit representation, preserving all
            /// bits (even those not corresponding to a defined flag).
            ///
            /// # Safety
            ///
            /// The caller of the `bitflags!` macro can choose to allow or
            /// disallow extra bits for their bitflags type.
            ///
            /// The caller of `from_bits_unchecked()` has to ensure that
            /// all bits correspond to a defined flag or that extra bits
            /// are valid for this bitflags type.
            #[inline]
            pub const unsafe fn from_bits_unchecked(bits: $T) -> Self {
                Self { bits }
            }

            /// Returns `true` if no flags are currently stored.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.bits() == Self::empty().bits()
            }

            /// Returns `true` if all flags are currently set.
            #[inline]
            pub const fn is_all(&self) -> bool {
                Self::all().bits | self.bits == self.bits
            }

            /// Returns `true` if there are flags common to both `self` and `other`.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                !(Self { bits: self.bits & other.bits}).is_empty()
            }

            /// Returns `true` if all of the flags in `other` are contained within `self`.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                (self.bits & other.bits) == other.bits
            }

            /// Inserts the specified flags in-place.
            #[inline]
            pub fn insert(&mut self, other: Self) {
                self.bits |= other.bits;
            }

            /// Removes the specified flags in-place.
            #[inline]
            pub fn remove(&mut self, other: Self) {
                self.bits &= !other.bits;
            }

            /// Toggles the specified flags in-place.
            #[inline]
            pub fn toggle(&mut self, other: Self) {
                self.bits ^= other.bits;
            }

            /// Inserts or removes the specified flags depending on the passed value.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                if value {
                    self.insert(other);
                } else {
                    self.remove(other);
                }
            }

            /// Returns the intersection between the flags in `self` and
            /// `other`.
            ///
            /// Specifically, the returned set contains only the flags which are
            /// present in *both* `self` *and* `other`.
            ///
            /// This is equivalent to using the `&` operator (e.g.
            /// [`ops::BitAnd`]), as in `flags & other`.
            ///
            /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self { bits: self.bits & other.bits }
            }

            /// Returns the union of between the flags in `self` and `other`.
            ///
            /// Specifically, the returned set contains all flags which are
            /// present in *either* `self` *or* `other`, including any which are
            /// present in both (see [`Self::symmetric_difference`] if that
            /// is undesirable).
            ///
            /// This is equivalent to using the `|` operator (e.g.
            /// [`ops::BitOr`]), as in `flags | other`.
            ///
            /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self { bits: self.bits | other.bits }
            }

            /// Returns the difference between the flags in `self` and `other`.
            ///
            /// Specifically, the returned set contains all flags present in
            /// `self`, except for the ones present in `other`.
            ///
            /// It is also conceptually equivalent to the "bit-clear" operation:
            /// `flags & !other` (and this syntax is also supported).
            ///
            /// This is equivalent to using the `-` operator (e.g.
            /// [`ops::Sub`]), as in `flags - other`.
            ///
            /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self { bits: self.bits & !other.bits }
            }

            /// Returns the [symmetric difference][sym-diff] between the flags
            /// in `self` and `other`.
            ///
            /// Specifically, the returned set contains the flags present which
            /// are present in `self` or `other`, but that are not present in
            /// both. Equivalently, it contains the flags present in *exactly
            /// one* of the sets `self` and `other`.
            ///
            /// This is equivalent to using the `^` operator (e.g.
            /// [`ops::BitXor`]), as in `flags ^ other`.
            ///
            /// [sym-diff]: https://en.wikipedia.org/wiki/Symmetric_difference
            /// [`ops::BitXor`]: https://doc.rust-lang.org/std/ops/trait.BitXor.html
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self { bits: self.bits ^ other.bits }
            }

            /// Returns the complement of this set of flags.
            ///
            /// Specifically, the returned set contains all the flags which are
            /// not set in `self`, but which are allowed for this type.
            ///
            /// Alternatively, it can be thought of as the set difference
            /// between [`Self::all()`] and `self` (e.g. `Self::all() - self`)
            ///
            /// This is equivalent to using the `!` operator (e.g.
            /// [`ops::Not`]), as in `!flags`.
            ///
            /// [`Self::all()`]: Self::all
            /// [`ops::Not`]: https://doc.rust-lang.org/std/ops/trait.Not.html
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self::from_bits_truncate(!self.bits)
            }

            /// Returns an iterator over all the flags in this set.
            pub fn iter(mut self) -> impl Iterator<Item = Self> {
                let options = [
                    $(
                        #[allow(unused_doc_comments, unused_attributes)]
                        $(#[$attr $($args)*])*
                        Self::$Flag,
                    )*
                ];
                const NUM_FLAGS: usize = {
                    #[allow(unused_mut)]
                    let mut num_flags = 0;

                    $(
                        #[allow(unused_doc_comments, unused_attributes)]
                        $(#[$attr $($args)*])*
                        {
                            num_flags += 1;
                        }
                    )*

                    num_flags
                };
                let mut start = 0;

                $crate::_core::iter::from_fn(move || {
                    if self.is_empty() || NUM_FLAGS == 0 || start == NUM_FLAGS {
                        None
                    }else{
                        for pos in start..NUM_FLAGS {
                            let flag = options[pos];
                            start += 1;
{'fraction_non_alphanumeric': 0.1609353770786689, 'fraction_numerical': 0.01071626767705762, 'mean_word_length': 1.4662796734154515, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 77, 'https://': 14, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 20, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4569050', 'n_tokens_mistral': 15440, 'n_tokens_neox': 14291, 'n_words': 4299}