From c23a457e72abe608715ac76f076f47dc42af07a5 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Thu, 30 May 2024 20:31:44 +0200 Subject: Merging upstream version 1.74.1+dfsg1. Signed-off-by: Daniel Baumann --- vendor/bitflags/src/example_generated.rs | 16 +- vendor/bitflags/src/external.rs | 52 +- vendor/bitflags/src/external/arbitrary.rs | 4 +- vendor/bitflags/src/external/serde.rs | 12 +- vendor/bitflags/src/internal.rs | 8 +- vendor/bitflags/src/iter.rs | 36 +- vendor/bitflags/src/lib.rs | 948 +++++++++++++----------------- vendor/bitflags/src/parser.rs | 84 +-- vendor/bitflags/src/public.rs | 170 ++++-- vendor/bitflags/src/tests.rs | 24 + vendor/bitflags/src/traits.rs | 234 +++++--- 11 files changed, 837 insertions(+), 751 deletions(-) (limited to 'vendor/bitflags/src') diff --git a/vendor/bitflags/src/example_generated.rs b/vendor/bitflags/src/example_generated.rs index 3586e3f04..abb1118fa 100644 --- a/vendor/bitflags/src/example_generated.rs +++ b/vendor/bitflags/src/example_generated.rs @@ -21,16 +21,16 @@ __impl_internal_bitflags! { // Field `A`. /// /// This flag has the value `0b00000001`. - A = 0b00000001; + const A = 0b00000001; /// Field `B`. /// /// This flag has the value `0b00000010`. - B = 0b00000010; + const B = 0b00000010; /// Field `C`. /// /// This flag has the value `0b00000100`. - C = 0b00000100; - ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); + const C = 0b00000100; + const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } } @@ -51,15 +51,15 @@ __impl_public_bitflags_consts! { /// Field `A`. /// /// This flag has the value `0b00000001`. - A = 0b00000001; + const A = 0b00000001; /// Field `B`. /// /// This flag has the value `0b00000010`. - B = 0b00000010; + const B = 0b00000010; /// Field `C`. /// /// This flag has the value `0b00000100`. - C = 0b00000100; - ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); + const C = 0b00000100; + const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } } diff --git a/vendor/bitflags/src/external.rs b/vendor/bitflags/src/external.rs index 94bd20004..efeaa8279 100644 --- a/vendor/bitflags/src/external.rs +++ b/vendor/bitflags/src/external.rs @@ -21,8 +21,8 @@ macro_rules! __impl_external_bitflags_my_library { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => { @@ -37,8 +37,8 @@ macro_rules! __impl_external_bitflags_my_library { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => {}; @@ -57,8 +57,8 @@ Now, we add our macro call to the `__impl_external_bitflags` macro body: __impl_external_bitflags_my_library! { $InternalBitFlags: $T, $PublicBitFlags { $( - $(#[$attr $($args)*])* - $Flag; + $(#[$inner $($args)*])* + const $Flag; )* } } @@ -83,8 +83,8 @@ macro_rules! __impl_external_bitflags { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => { @@ -95,8 +95,8 @@ macro_rules! __impl_external_bitflags { __impl_external_bitflags_serde! { $InternalBitFlags: $T, $PublicBitFlags { $( - $(#[$attr $($args)*])* - $Flag; + $(#[$inner $($args)*])* + const $Flag; )* } } @@ -104,8 +104,8 @@ macro_rules! __impl_external_bitflags { __impl_external_bitflags_arbitrary! { $InternalBitFlags: $T, $PublicBitFlags { $( - $(#[$attr $($args)*])* - $Flag; + $(#[$inner $($args)*])* + const $Flag; )* } } @@ -113,8 +113,8 @@ macro_rules! __impl_external_bitflags { __impl_external_bitflags_bytemuck! { $InternalBitFlags: $T, $PublicBitFlags { $( - $(#[$attr $($args)*])* - $Flag; + $(#[$inner $($args)*])* + const $Flag; )* } } @@ -132,8 +132,8 @@ macro_rules! __impl_external_bitflags_serde { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => { @@ -168,8 +168,8 @@ macro_rules! __impl_external_bitflags_serde { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => {}; @@ -189,8 +189,8 @@ macro_rules! __impl_external_bitflags_arbitrary { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => { @@ -211,8 +211,8 @@ macro_rules! __impl_external_bitflags_arbitrary { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => {}; @@ -226,8 +226,8 @@ macro_rules! __impl_external_bitflags_bytemuck { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => { @@ -254,8 +254,8 @@ macro_rules! __impl_external_bitflags_bytemuck { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt; )* } ) => {}; diff --git a/vendor/bitflags/src/external/arbitrary.rs b/vendor/bitflags/src/external/arbitrary.rs index 715ba251a..ea76f0a25 100644 --- a/vendor/bitflags/src/external/arbitrary.rs +++ b/vendor/bitflags/src/external/arbitrary.rs @@ -2,7 +2,9 @@ use crate::Flags; -/// Get a random known flags value. +/** +Generate some arbitrary flags value with only known bits set. +*/ pub fn arbitrary<'a, B: Flags>(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result where B::Bits: arbitrary::Arbitrary<'a>, diff --git a/vendor/bitflags/src/external/serde.rs b/vendor/bitflags/src/external/serde.rs index 1d501db82..be4f2edbf 100644 --- a/vendor/bitflags/src/external/serde.rs +++ b/vendor/bitflags/src/external/serde.rs @@ -10,7 +10,11 @@ use serde::{ Deserialize, Deserializer, Serialize, Serializer, }; -/// Serialize a set of flags as a human-readable string or their underlying bits. +/** +Serialize a set of flags as a human-readable string or their underlying bits. + +Any unknown bits will be retained. +*/ pub fn serialize(flags: &B, serializer: S) -> Result where B::Bits: WriteHex + Serialize, @@ -25,7 +29,11 @@ where } } -/// Deserialize a set of flags from a human-readable string or their underlying bits. +/** +Deserialize a set of flags from a human-readable string or their underlying bits. + +Any unknown bits will be retained. +*/ pub fn deserialize<'de, B: Flags, D: Deserializer<'de>>(deserializer: D) -> Result where B::Bits: ParseHex + Deserialize<'de>, diff --git a/vendor/bitflags/src/internal.rs b/vendor/bitflags/src/internal.rs index 824cdde45..aca1ac4db 100644 --- a/vendor/bitflags/src/internal.rs +++ b/vendor/bitflags/src/internal.rs @@ -31,8 +31,8 @@ macro_rules! __impl_internal_bitflags { ( $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident = $value:expr; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt = $value:expr; )* } ) => { @@ -100,8 +100,8 @@ macro_rules! __impl_internal_bitflags { __impl_public_bitflags! { $InternalBitFlags: $T, $PublicBitFlags { $( - $(#[$attr $($args)*])* - $Flag; + $(#[$inner $($args)*])* + const $Flag = $value; )* } } diff --git a/vendor/bitflags/src/iter.rs b/vendor/bitflags/src/iter.rs index 761124f10..7f7ce554c 100644 --- a/vendor/bitflags/src/iter.rs +++ b/vendor/bitflags/src/iter.rs @@ -1,18 +1,21 @@ -//! Iterating over set flag values. +/*! +Yield the bits of a source flags value in a set of contained flags values. +*/ use crate::{Flag, Flags}; -/// An iterator over a set of flags. -/// -/// Any bits that don't correspond to a valid flag will be yielded -/// as a final item from the iterator. +/** +An iterator over flags values. + +This iterator will yield flags values for contained, defined flags first, with any remaining bits yielded +as a final flags value. +*/ pub struct Iter { inner: IterNames, done: bool, } impl Iter { - /// Create a new iterator over the given set of flags. pub(crate) fn new(flags: &B) -> Self { Iter { inner: IterNames::new(flags), @@ -22,6 +25,7 @@ impl Iter { } impl Iter { + // Used by the `bitflags` macro #[doc(hidden)] pub const fn __private_const_new(flags: &'static [Flag], source: B, remaining: B) -> Self { Iter { @@ -54,9 +58,12 @@ impl Iterator for Iter { } } -/// An iterator over a set of flags and their names. -/// -/// Any bits that don't correspond to a valid flag will be ignored. +/** +An iterator over flags values. + +This iterator only yields flags values for contained, defined, named flags. Any remaining bits +won't be yielded, but can be found with the [`IterNames::remaining`] method. +*/ pub struct IterNames { flags: &'static [Flag], idx: usize, @@ -65,7 +72,6 @@ pub struct IterNames { } impl IterNames { - /// Create a new iterator over the given set of flags. pub(crate) fn new(flags: &B) -> Self { IterNames { flags: B::FLAGS, @@ -77,6 +83,7 @@ impl IterNames { } impl IterNames { + // Used by the bitflags macro #[doc(hidden)] pub const fn __private_const_new(flags: &'static [Flag], source: B, remaining: B) -> Self { IterNames { @@ -87,11 +94,11 @@ impl IterNames { } } - /// Get the remaining (unyielded) flags. + /// Get a flags value of any remaining bits that haven't been yielded yet. /// /// Once the iterator has finished, this method can be used to /// check whether or not there are any bits that didn't correspond - /// to a valid flag remaining. + /// to a contained, defined, named flag remaining. pub fn remaining(&self) -> &B { &self.remaining } @@ -109,6 +116,11 @@ impl Iterator for IterNames { self.idx += 1; + // Skip unnamed flags + if flag.name().is_empty() { + continue; + } + let bits = flag.value().bits(); // If the flag is set in the original source _and_ it has bits that haven't diff --git a/vendor/bitflags/src/lib.rs b/vendor/bitflags/src/lib.rs index bac1d1968..3d5377b8d 100644 --- a/vendor/bitflags/src/lib.rs +++ b/vendor/bitflags/src/lib.rs @@ -8,422 +8,239 @@ // 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 flags. -//! It can be used for creating ergonomic wrappers around C APIs. -//! -//! The `bitflags!` macro generates `struct`s that manage a set of flags. The -//! type of those flags must be some primitive integer. -//! -//! # Examples -//! -//! ``` -//! use bitflags::bitflags; -//! -//! bitflags! { -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! 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. -//! -//! # Visibility -//! -//! The `bitflags!` macro supports visibility, just like you'd expect when writing a normal -//! Rust `struct`: -//! -//! ``` -//! mod example { -//! use bitflags::bitflags; -//! -//! bitflags! { -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! pub struct Flags1: u32 { -//! const A = 0b00000001; -//! } -//! -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! # 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 flags types and their constants as normal. -//! -//! # Representation -//! -//! It's valid to add a `#[repr(C)]` or `#[repr(transparent)]` attribute to a generated flags type. -//! The generated flags type is always guaranteed to be a newtype where its only field has the same -//! ABI as the underlying integer type. -//! -//! In this example, `Flags` has the same ABI as `u32`: -//! -//! ``` -//! use bitflags::bitflags; -//! -//! bitflags! { -//! #[repr(transparent)] -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! struct Flags: u32 { -//! const A = 0b00000001; -//! const B = 0b00000010; -//! const C = 0b00000100; -//! } -//! } -//! ``` -//! -//! # Extending -//! -//! Generated flags types belong to you, so you can add trait implementations to them outside -//! of what the `bitflags!` macro gives: -//! -//! ``` -//! use std::fmt; -//! -//! use bitflags::bitflags; -//! -//! bitflags! { -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! struct Flags: u32 { -//! const A = 0b00000001; -//! const B = 0b00000010; -//! } -//! } -//! -//! impl Flags { -//! pub fn clear(&mut self) { -//! *self.0.bits_mut() = 0; -//! } -//! } -//! -//! fn main() { -//! let mut flags = Flags::A | Flags::B; -//! -//! flags.clear(); -//! assert!(flags.is_empty()); -//! -//! assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)"); -//! assert_eq!(format!("{:?}", Flags::B), "Flags(B)"); -//! } -//! ``` -//! -//! # What's implemented by `bitflags!` -//! -//! The `bitflags!` macro adds some trait implementations and inherent methods -//! to generated flags types, but leaves room for you to choose the semantics -//! of others. -//! -//! ## Iterators -//! -//! The following iterator traits are implemented for generated flags types: -//! -//! - `Extend`: adds the union of the instances iterated over. -//! - `FromIterator`: calculates the union. -//! - `IntoIterator`: iterates over set flag values. -//! -//! ## Formatting -//! -//! The following formatting traits are implemented for generated flags types: -//! -//! - `Binary`. -//! - `LowerHex` and `UpperHex`. -//! - `Octal`. -//! -//! Also see the _Debug and Display_ section for details about standard text -//! representations for flags types. -//! -//! ## 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_retain`: 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. -//! -//! # What's not implemented by `bitflags!` -//! -//! Some functionality is not automatically implemented for generated flags types -//! by the `bitflags!` macro, even when it reasonably could be. This is so callers -//! have more freedom to decide on the semantics of their flags types. -//! -//! ## `Clone` and `Copy` -//! -//! Generated flags types are not automatically copyable, even though they can always -//! derive both `Clone` and `Copy`. -//! -//! ## `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, Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! 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! { -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! 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)); -//! } -//! ``` -//! -//! ## `Debug` and `Display` -//! -//! The `Debug` trait can be derived for a reasonable implementation. This library defines a standard -//! text-based representation for flags that generated flags types can use. For details on the exact -//! grammar, see the [`parser`] module. -//! -//! To support formatting and parsing your generated flags types using that representation, you can implement -//! the standard `Display` and `FromStr` traits in this fashion: -//! -//! ``` -//! use bitflags::bitflags; -//! use std::{fmt, str}; -//! -//! bitflags! { -//! pub struct Flags: u32 { -//! const A = 1; -//! const B = 2; -//! const C = 4; -//! const D = 8; -//! } -//! } -//! -//! impl fmt::Debug for Flags { -//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -//! fmt::Debug::fmt(&self.0, f) -//! } -//! } -//! -//! impl fmt::Display for Flags { -//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -//! fmt::Display::fmt(&self.0, f) -//! } -//! } -//! -//! impl str::FromStr for Flags { -//! type Err = bitflags::parser::ParseError; -//! -//! fn from_str(flags: &str) -> Result { -//! Ok(Self(flags.parse()?)) -//! } -//! } -//! ``` -//! -//! ## `PartialEq` and `PartialOrd` -//! -//! Equality and ordering can be derived for a reasonable implementation, or implemented manually -//! for different semantics. -//! -//! # Edge cases -//! -//! ## Zero Flags -//! -//! Flags with a value equal to zero will have some strange behavior that one should be aware of. -//! -//! ``` -//! use bitflags::bitflags; -//! -//! bitflags! { -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! 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. -//! -//! ## Multi-bit Flags -//! -//! It is allowed to define a flag with multiple bits set, however such -//! flags are _not_ treated as a set where any of those bits is a valid -//! flag. Instead, each flag is treated as a unit when converting from -//! bits with [`from_bits`] or [`from_bits_truncate`]. -//! -//! ``` -//! use bitflags::bitflags; -//! -//! bitflags! { -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! struct Flags: u8 { -//! const F3 = 0b00000011; -//! } -//! } -//! -//! fn main() { -//! // This bit pattern does not set all the bits in `F3`, so it is rejected. -//! assert!(Flags::from_bits(0b00000001).is_none()); -//! assert!(Flags::from_bits_truncate(0b00000001).is_empty()); -//! } -//! ``` -//! -//! [`from_bits`]: Flags::from_bits -//! [`from_bits_truncate`]: Flags::from_bits_truncate -//! -//! # The `Flags` trait -//! -//! This library defines a `Flags` trait that's implemented by all generated flags types. -//! The trait makes it possible to work with flags types generically: -//! -//! ``` -//! fn count_unset_flags(flags: &F) -> usize { -//! // Find out how many flags there are in total -//! let total = F::all().iter().count(); -//! -//! // Find out how many flags are set -//! let set = flags.iter().count(); -//! -//! total - set -//! } -//! -//! use bitflags::bitflags; -//! -//! bitflags! { -//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -//! struct Flags: u32 { -//! const A = 0b00000001; -//! const B = 0b00000010; -//! const C = 0b00000100; -//! } -//! } -//! -//! assert_eq!(2, count_unset_flags(&Flags::B)); -//! ``` -//! -//! # The internal field -//! -//! This library generates newtypes like: -//! -//! ``` -//! # pub struct Field0; -//! pub struct Flags(Field0); -//! ``` -//! -//! You can freely use methods and trait implementations on this internal field as `.0`. -//! For details on exactly what's generated for it, see the [`Field0`](example_generated/struct.Field0.html) -//! example docs. +/*! +Generate types for C-style flags with ergonomic APIs. + +# Getting started + +Add `bitflags` to your `Cargo.toml`: + +```toml +[dependencies.bitflags] +version = "2.4.0" +``` + +## Generating flags types + +Use the [`bitflags`] macro to generate flags types: + +```rust +use bitflags::bitflags; + +bitflags! { + pub struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } +} +``` + +See the docs for the `bitflags` macro for the full syntax. + +Also see the [`example_generated`] module for an example of what the `bitflags` macro generates for a flags type. + +### Externally defined flags + +If you're generating flags types for an external source, such as a C API, you can define +an extra unnamed flag as a mask of all bits the external source may ever set. Usually this would be all bits (`!0`): + +```rust +# use bitflags::bitflags; +bitflags! { + pub struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + + // The source may set any bits + const _ = !0; + } +} +``` + +Why should you do this? Generated methods like `all` and truncating operators like `!` only consider +bits in defined flags. Adding an unnamed flag makes those methods consider additional bits, +without generating additional constants for them. It helps compatibility when the external source +may start setting additional bits at any time. The [known and unknown bits](#known-and-unknown-bits) +section has more details on this behavior. + +### Custom derives + +You can derive some traits on generated flags types if you enable Cargo features. The following +libraries are currently supported: + +- `serde`: Support `#[derive(Serialize, Deserialize)]`, using text for human-readable formats, +and a raw number for binary formats. +- `arbitrary`: Support `#[derive(Arbitrary)]`, only generating flags values with known bits. +- `bytemuck`: Support `#[derive(Pod, Zeroable)]`, for casting between flags values and their +underlying bits values. + +You can also define your own flags type outside of the [`bitflags`] macro and then use it to generate methods. +This can be useful if you need a custom `#[derive]` attribute for a library that `bitflags` doesn't +natively support: + +```rust +# use std::fmt::Debug as SomeTrait; +# use bitflags::bitflags; +#[derive(SomeTrait)] +pub struct Flags(u32); + +bitflags! { + impl Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } +} +``` + +### Adding custom methods + +The [`bitflags`] macro supports attributes on generated flags types within the macro itself, while +`impl` blocks can be added outside of it: + +```rust +# use bitflags::bitflags; +bitflags! { + // Attributes can be applied to flags types + #[repr(transparent)] + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } +} + +// Impl blocks can be added to flags types +impl Flags { + pub fn as_u64(&self) -> u64 { + self.bits() as u64 + } +} +``` + +## Working with flags values + +Use generated constants and standard bitwise operators to interact with flags values: + +```rust +# use bitflags::bitflags; +# bitflags! { +# #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +# pub struct Flags: u32 { +# const A = 0b00000001; +# const B = 0b00000010; +# const C = 0b00000100; +# } +# } +// union +let ab = Flags::A | Flags::B; + +// intersection +let a = ab & Flags::A; + +// difference +let b = ab - Flags::A; + +// complement +let c = !ab; +``` + +See the docs for the [`Flags`] trait for more details on operators and how they behave. + +# Formatting and parsing + +`bitflags` defines a text format that can be used to convert any flags value to and from strings. + +See the [`parser`] module for more details. + +# Specification + +The terminology and behavior of generated flags types is +[specified in the source repository](https://github.com/bitflags/bitflags/blob/main/spec.md). +Details are repeated in these docs where appropriate, but is exhaustively listed in the spec. Some +things are worth calling out explicitly here. + +## Flags types, flags values, flags + +The spec and these docs use consistent terminology to refer to things in the bitflags domain: + +- **Bits type**: A type that defines a fixed number of bits at specific locations. +- **Flag**: A set of bits in a bits type that may have a unique name. +- **Flags type**: A set of defined flags over a specific bits type. +- **Flags value**: An instance of a flags type using its specific bits value for storage. + +``` +# use bitflags::bitflags; +bitflags! { + struct FlagsType: u8 { +// -- Bits type +// --------- Flags type + const A = 1; +// ----- Flag + } +} + +let flag = FlagsType::A; +// ---- Flags value +``` + +## Known and unknown bits + +Any bits in a flag you define are called _known bits_. Any other bits are _unknown bits_. +In the following flags type: + +``` +# use bitflags::bitflags; +bitflags! { + struct Flags: u8 { + const A = 1; + const B = 1 << 1; + const C = 1 << 2; + } +} +``` + +The known bits are `0b0000_0111` and the unknown bits are `0b1111_1000`. + +`bitflags` doesn't guarantee that a flags value will only ever have known bits set, but some operators +will unset any unknown bits they encounter. In a future version of `bitflags`, all operators will +unset unknown bits. + +If you're using `bitflags` for flags types defined externally, such as from C, you probably want all +bits to be considered known, in case that external source changes. You can do this using an unnamed +flag, as described in [externally defined flags](#externally-defined-flags). + +## Zero-bit flags + +Flags with no bits set should be avoided because they interact strangely with [`Flags::contains`] +and [`Flags::intersects`]. A zero-bit flag is always contained, but is never intersected. The +names of zero-bit flags can be parsed, but are never formatted. + +## Multi-bit flags + +Flags that set multiple bits should be avoided unless each bit is also in a single-bit flag. +Take the following flags type as an example: + +``` +# use bitflags::bitflags; +bitflags! { + struct Flags: u8 { + const A = 1; + const B = 1 | 1 << 1; + } +} +``` + +The result of `Flags::A ^ Flags::B` is `0b0000_0010`, which doesn't correspond to either +`Flags::A` or `Flags::B` even though it's still a known bit. +*/ #![cfg_attr(not(any(feature = "std", test)), no_std)] #![cfg_attr(not(test), forbid(unsafe_code))] #![cfg_attr(test, allow(mixed_script_confusables))] -#![doc(html_root_url = "https://docs.rs/bitflags/2.3.3")] #[doc(inline)] pub use traits::{Bits, Flag, Flags}; @@ -497,63 +314,133 @@ The macros are split into 3 modules: - `external`: where external library traits are implemented conditionally. */ -/// The macro used to generate the flag structure. -/// -/// See the [crate level docs](../bitflags/index.html) for complete documentation. -/// -/// # Example -/// -/// ``` -/// use bitflags::bitflags; -/// -/// bitflags! { -/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -/// struct Flags: u32 { -/// const A = 0b00000001; -/// const B = 0b00000010; -/// const C = 0b00000100; -/// const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); -/// } -/// } -/// -/// 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! { -/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -/// struct Flags: u32 { -/// const A = 0b00000001; -/// const B = 0b00000010; -/// } -/// } -/// -/// impl Flags { -/// pub fn clear(&mut self) { -/// *self.0.bits_mut() = 0; -/// } -/// } -/// -/// let mut flags = Flags::A | Flags::B; -/// -/// flags.clear(); -/// assert!(flags.is_empty()); -/// -/// assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)"); -/// assert_eq!(format!("{:?}", Flags::B), "Flags(B)"); -/// ``` +/** +Generate a flags type. + +# `struct` mode + +A declaration that begins with `$vis struct` will generate a `struct` for a flags type, along with +methods and trait implementations for it. The body of the declaration defines flags as constants, +where each constant is a flags value of the generated flags type. + +## Examples + +Generate a flags type using `u8` as the bits type: + +``` +# use bitflags::bitflags; +bitflags! { + struct Flags: u8 { + const A = 1; + const B = 1 << 1; + const C = 0b0000_0100; + } +} +``` + +Flags types are private by default and accept standard visibility modifiers. Flags themselves +are always public: + +``` +# use bitflags::bitflags; +bitflags! { + pub struct Flags: u8 { + // Constants are always `pub` + const A = 1; + } +} +``` + +Flags may refer to other flags using their [`Flags::bits`] value: + +``` +# use bitflags::bitflags; +bitflags! { + struct Flags: u8 { + const A = 1; + const B = 1 << 1; + const AB = Flags::A.bits() | Flags::B.bits(); + } +} +``` + +A single `bitflags` invocation may include zero or more flags type declarations: + +``` +# use bitflags::bitflags; +bitflags! {} + +bitflags! { + struct Flags1: u8 { + const A = 1; + } + + struct Flags2: u8 { + const A = 1; + } +} +``` + +# `impl` mode + +A declaration that begins with `impl` will only generate methods and trait implementations for the +`struct` defined outside of the `bitflags` macro. + +The struct itself must be a newtype using the bits type as its field. + +The syntax for `impl` mode is identical to `struct` mode besides the starting token. + +## Examples + +Implement flags methods and traits for a custom flags type using `u8` as its underlying bits type: + +``` +# use bitflags::bitflags; +struct Flags(u8); + +bitflags! { + impl Flags: u8 { + const A = 1; + const B = 1 << 1; + const C = 0b0000_0100; + } +} +``` + +# Named and unnamed flags + +Constants in the body of a declaration are flags. The identifier of the constant is the name of +the flag. If the identifier is `_`, then the flag is unnamed. Unnamed flags don't appear in the +generated API, but affect how bits are truncated. + +## Examples + +Adding an unnamed flag that makes all bits known: + +``` +# use bitflags::bitflags; +bitflags! { + struct Flags: u8 { + const A = 1; + const B = 1 << 1; + + const _ = !0; + } +} +``` + +Flags types may define multiple unnamed flags: + +``` +# use bitflags::bitflags; +bitflags! { + struct Flags: u8 { + const _ = 1; + const _ = 1 << 1; + } +} +``` +*/ #[macro_export(local_inner_macros)] macro_rules! bitflags { ( @@ -561,7 +448,7 @@ macro_rules! bitflags { $vis:vis struct $BitFlags:ident: $T:ty { $( $(#[$inner:ident $($args:tt)*])* - const $Flag:ident = $value:expr; + const $Flag:tt = $value:expr; )* } @@ -579,7 +466,7 @@ macro_rules! bitflags { $BitFlags: $T { $( $(#[$inner $($args)*])* - $Flag = $value; + const $Flag = $value; )* } } @@ -592,7 +479,9 @@ macro_rules! bitflags { unused_mut, unused_imports, non_upper_case_globals, - clippy::assign_op_pattern + clippy::assign_op_pattern, + clippy::indexing_slicing, + clippy::same_name_method )] const _: () = { // Declared in a "hidden" scope that can't be reached directly @@ -605,7 +494,7 @@ macro_rules! bitflags { InternalBitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* - $Flag = $value; + const $Flag = $value; )* } } @@ -615,7 +504,7 @@ macro_rules! bitflags { InternalBitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* - $Flag; + const $Flag; )* } } @@ -641,7 +530,7 @@ macro_rules! bitflags { impl $BitFlags:ident: $T:ty { $( $(#[$inner:ident $($args:tt)*])* - const $Flag:ident = $value:expr; + const $Flag:tt = $value:expr; )* } @@ -651,7 +540,7 @@ macro_rules! bitflags { $BitFlags: $T { $( $(#[$inner $($args)*])* - $Flag = $value; + const $Flag = $value; )* } } @@ -671,7 +560,7 @@ macro_rules! bitflags { $BitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* - $Flag; + const $Flag = $value; )* } } @@ -725,74 +614,75 @@ macro_rules! __impl_bitflags { ) => { #[allow(dead_code, deprecated, unused_attributes)] impl $PublicBitFlags { - /// Returns an empty set of flags. + /// Get a flags value with all bits unset. #[inline] pub const fn empty() -> Self { $empty } - /// Returns the set containing all flags. + /// Get a flags value with all known bits set. #[inline] pub const fn all() -> Self { $all } - /// Returns the raw value of the flags currently stored. + /// Get the underlying bits value. + /// + /// The returned value is exactly the bits set in this flags value. #[inline] pub const fn bits(&self) -> $T { let $bits0 = self; $bits } - /// Convert from underlying bit representation, unless that - /// representation contains bits that do not correspond to a flag. + /// Convert from a bits value. + /// + /// This method will return `None` if any unknown bits are set. #[inline] pub const fn from_bits(bits: $T) -> $crate::__private::core::option::Option { let $from_bits0 = bits; $from_bits } - /// Convert from underlying bit representation, dropping any bits - /// that do not correspond to flags. + /// Convert from a bits value, unsetting any unknown bits. #[inline] pub const fn from_bits_truncate(bits: $T) -> Self { let $from_bits_truncate0 = bits; $from_bits_truncate } - /// Convert from underlying bit representation, preserving all - /// bits (even those not corresponding to a defined flag). + /// Convert from a bits value exactly. #[inline] pub const fn from_bits_retain(bits: $T) -> Self { let $from_bits_retain0 = bits; $from_bits_retain } - /// Get the value for a flag from its stringified name. + /// Get a flags value with the bits of a flag with the given name set. /// - /// Names are _case-sensitive_, so must correspond exactly to - /// the identifier given to the flag. + /// This method will return `None` if `name` is empty or doesn't + /// correspond to any named flag. #[inline] pub fn from_name(name: &str) -> $crate::__private::core::option::Option { let $from_name0 = name; $from_name } - /// Returns `true` if no flags are currently stored. + /// Whether all bits in this flags value are unset. #[inline] pub const fn is_empty(&self) -> bool { let $is_empty0 = self; $is_empty } - /// Returns `true` if all flags are currently set. + /// Whether all known bits in this flags value are set. #[inline] pub const fn is_all(&self) -> bool { let $is_all0 = self; $is_all } - /// Returns `true` if there are flags common to both `self` and `other`. + /// Whether any set bits in a source flags value are also set in a target flags value. #[inline] pub const fn intersects(&self, other: Self) -> bool { let $intersects0 = self; @@ -800,7 +690,7 @@ macro_rules! __impl_bitflags { $intersects } - /// Returns `true` if all of the flags in `other` are contained within `self`. + /// Whether all set bits in a source flags value are also set in a target flags value. #[inline] pub const fn contains(&self, other: Self) -> bool { let $contains0 = self; @@ -808,9 +698,7 @@ macro_rules! __impl_bitflags { $contains } - /// Inserts the specified flags in-place. - /// - /// This method is equivalent to `union`. + /// The bitwise or (`|`) of the bits in two flags values. #[inline] pub fn insert(&mut self, other: Self) { let $insert0 = self; @@ -818,9 +706,10 @@ macro_rules! __impl_bitflags { $insert } - /// Removes the specified flags in-place. + /// The intersection of a source flags value with the complement of a target flags value (`&!`). /// - /// This method is equivalent to `difference`. + /// This method is not equivalent to `self & !other` when `other` has unknown bits set. + /// `remove` won't truncate `other`, but the `!` operator will. #[inline] pub fn remove(&mut self, other: Self) { let $remove0 = self; @@ -828,9 +717,7 @@ macro_rules! __impl_bitflags { $remove } - /// Toggles the specified flags in-place. - /// - /// This method is equivalent to `symmetric_difference`. + /// The bitwise exclusive-or (`^`) of the bits in two flags values. #[inline] pub fn toggle(&mut self, other: Self) { let $toggle0 = self; @@ -838,7 +725,7 @@ macro_rules! __impl_bitflags { $toggle } - /// Inserts or removes the specified flags depending on the passed value. + /// Call `insert` when `value` is `true` or `remove` when `value` is `false`. #[inline] pub fn set(&mut self, other: Self, value: bool) { let $set0 = self; @@ -847,11 +734,7 @@ macro_rules! __impl_bitflags { $set } - /// Returns the intersection between the flags in `self` and - /// `other`. - /// - /// Calculating `self` bitwise and (`&`) other, including - /// any bits that don't correspond to a defined flag. + /// The bitwise and (`&`) of the bits in two flags values. #[inline] #[must_use] pub const fn intersection(self, other: Self) -> Self { @@ -860,10 +743,7 @@ macro_rules! __impl_bitflags { $intersection } - /// Returns the union of between the flags in `self` and `other`. - /// - /// Calculates `self` bitwise or (`|`) `other`, including - /// any bits that don't correspond to a defined flag. + /// The bitwise or (`|`) of the bits in two flags values. #[inline] #[must_use] pub const fn union(self, other: Self) -> Self { @@ -872,15 +752,10 @@ macro_rules! __impl_bitflags { $union } - /// Returns the difference between the flags in `self` and `other`. + /// The intersection of a source flags value with the complement of a target flags value (`&!`). /// - /// Calculates `self` bitwise and (`&!`) the bitwise negation of `other`, - /// including any bits that don't correspond to a defined flag. - /// - /// This method is _not_ equivalent to `a & !b` when there are bits set that - /// don't correspond to a defined flag. The `!` operator will unset any - /// bits that don't correspond to a flag, so they'll always be unset by `a &! b`, - /// but respected by `a.difference(b)`. + /// This method is not equivalent to `self & !other` when `other` has unknown bits set. + /// `difference` won't truncate `other`, but the `!` operator will. #[inline] #[must_use] pub const fn difference(self, other: Self) -> Self { @@ -889,11 +764,7 @@ macro_rules! __impl_bitflags { $difference } - /// Returns the symmetric difference between the flags - /// in `self` and `other`. - /// - /// Calculates `self` bitwise exclusive or (`^`) `other`, - /// including any bits that don't correspond to a defined flag. + /// The bitwise exclusive-or (`^`) of the bits in two flags values. #[inline] #[must_use] pub const fn symmetric_difference(self, other: Self) -> Self { @@ -902,10 +773,7 @@ macro_rules! __impl_bitflags { $symmetric_difference } - /// Returns the complement of this set of flags. - /// - /// Calculates the bitwise negation (`!`) of `self`, - /// **unsetting** any bits that don't correspond to a defined flag. + /// The bitwise negation (`!`) of the bits in a flags value, truncating the result. #[inline] #[must_use] pub const fn complement(self) -> Self { @@ -1013,6 +881,30 @@ macro_rules! __bitflags_expr_safe_attrs { } } +/// Implement a flag, which may be a wildcard `_`. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __bitflags_flag { + ( + { + name: _, + named: { $($named:tt)* }, + unnamed: { $($unnamed:tt)* }, + } + ) => { + $($unnamed)* + }; + ( + { + name: $Flag:ident, + named: { $($named:tt)* }, + unnamed: { $($unnamed:tt)* }, + } + ) => { + $($named)* + }; +} + #[macro_use] mod public; #[macro_use] diff --git a/vendor/bitflags/src/parser.rs b/vendor/bitflags/src/parser.rs index 1f5a42fdd..130dc2e1f 100644 --- a/vendor/bitflags/src/parser.rs +++ b/vendor/bitflags/src/parser.rs @@ -1,30 +1,32 @@ -//! Parsing flags from text. -//! -//! `bitflags` defines the following *whitespace-insensitive*, *case-sensitive* grammar for flags formatted -//! as text: -//! -//! - _Flags:_ (_Flag_)`|`* -//! - _Flag:_ _Identifier_ | _HexNumber_ -//! - _Identifier:_ Any Rust identifier -//! - _HexNumber_: `0x`([0-9a-fA-F])* -//! -//! As an example, this is how `Flags::A | Flags::B | 0x0c` can be represented as text: -//! -//! ```text -//! A | B | 0x0c -//! ``` -//! -//! Alternatively, it could be represented without whitespace: -//! -//! ```text -//! A|B|0x0C -//! ``` -//! -//! Note that identifiers are *case-sensitive*, so the following is *not equivalent*: -//! -//! ```text -//! a | b | 0x0c -//! ``` +/*! +Parsing flags from text. + +Format and parse a flags value as text using the following grammar: + +- _Flags:_ (_Whitespace_ _Flag_ _Whitespace_)`|`* +- _Flag:_ _Name_ | _Hex Number_ +- _Name:_ The name of any defined flag +- _Hex Number_: `0x`([0-9a-fA-F])* +- _Whitespace_: (\s)* + +As an example, this is how `Flags::A | Flags::B | 0x0c` can be represented as text: + +```text +A | B | 0x0c +``` + +Alternatively, it could be represented without whitespace: + +```text +A|B|0x0C +``` + +Note that identifiers are *case-sensitive*, so the following is *not equivalent*: + +```text +a|b|0x0C +``` +*/ #![allow(clippy::let_unit_value)] @@ -32,10 +34,11 @@ use core::fmt::{self, Write}; use crate::{Bits, Flags}; -/// Write a set of flags to a writer. -/// -/// Any bits that don't correspond to a valid flag will be formatted -/// as a hex number. +/** +Write a flags value as text. + +Any bits that aren't part of a contained flag will be formatted as a hex number. +*/ pub fn to_writer(flags: &B, mut writer: impl Write) -> Result<(), fmt::Error> where B::Bits: WriteHex, @@ -85,9 +88,12 @@ where } } -/// Parse a set of flags from text. -/// -/// This function will fail on unknown flags rather than ignore them. +/** +Parse a flags value from text. + +This function will fail on any names that don't correspond to defined flags. +Unknown bits will be retained. +*/ pub fn from_str(input: &str) -> Result where B::Bits: ParseHex, @@ -128,13 +134,19 @@ where Ok(parsed_flags) } -/// Encode a value as a hex number. +/** +Encode a value as a hex string. + +Implementors of this trait should not write the `0x` prefix. +*/ pub trait WriteHex { /// Write the value as hex. fn write_hex(&self, writer: W) -> fmt::Result; } -/// Parse a value from a number encoded as a hex string. +/** +Parse a value from a hex string. +*/ pub trait ParseHex { /// Parse the value from hex. fn parse_hex(input: &str) -> Result diff --git a/vendor/bitflags/src/public.rs b/vendor/bitflags/src/public.rs index eb8e4c5d5..967e0dacb 100644 --- a/vendor/bitflags/src/public.rs +++ b/vendor/bitflags/src/public.rs @@ -130,8 +130,8 @@ macro_rules! __impl_public_bitflags { ( $BitFlags:ident: $T:ty, $PublicBitFlags:ident { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt = $value:expr; )* } ) => { @@ -142,7 +142,23 @@ macro_rules! __impl_public_bitflags { } fn all() { - Self::from_bits_truncate(<$T as $crate::Bits>::ALL) + let mut truncated = <$T as $crate::Bits>::EMPTY; + let mut i = 0; + + $( + __bitflags_expr_safe_attrs!( + $(#[$inner $($args)*])* + {{ + let flag = <$PublicBitFlags as $crate::Flags>::FLAGS[i].value().bits(); + + truncated = truncated | flag; + i += 1; + }} + ); + )* + + let _ = i; + Self::from_bits_retain(truncated) } fn bits(f) { @@ -160,24 +176,7 @@ macro_rules! __impl_public_bitflags { } fn from_bits_truncate(bits) { - if bits == <$T as $crate::Bits>::EMPTY { - return Self(bits) - } - - let mut truncated = <$T as $crate::Bits>::EMPTY; - - $( - __bitflags_expr_safe_attrs!( - $(#[$attr $($args)*])* - { - if bits & $PublicBitFlags::$Flag.bits() == $PublicBitFlags::$Flag.bits() { - truncated = truncated | $PublicBitFlags::$Flag.bits() - } - } - ); - )* - - Self(truncated) + Self(bits & Self::all().bits()) } fn from_bits_retain(bits) { @@ -186,14 +185,20 @@ macro_rules! __impl_public_bitflags { fn from_name(name) { $( - __bitflags_expr_safe_attrs!( - $(#[$attr $($args)*])* - { - if name == $crate::__private::core::stringify!($Flag) { - return $crate::__private::core::option::Option::Some(Self($PublicBitFlags::$Flag.bits())); - } - } - ); + __bitflags_flag!({ + name: $Flag, + named: { + __bitflags_expr_safe_attrs!( + $(#[$inner $($args)*])* + { + if name == $crate::__private::core::stringify!($Flag) { + return $crate::__private::core::option::Option::Some(Self($PublicBitFlags::$Flag.bits())); + } + } + ); + }, + unnamed: {}, + }); )* let _ = name; @@ -219,15 +224,15 @@ macro_rules! __impl_public_bitflags { } fn insert(f, other) { - *f = Self::from_bits_retain(f.bits() | other.bits()); + *f = Self::from_bits_retain(f.bits()).union(other); } fn remove(f, other) { - *f = Self::from_bits_retain(f.bits() & !other.bits()); + *f = Self::from_bits_retain(f.bits()).difference(other); } fn toggle(f, other) { - *f = Self::from_bits_retain(f.bits() ^ other.bits()); + *f = Self::from_bits_retain(f.bits()).symmetric_difference(other); } fn set(f, other, value) { @@ -268,7 +273,10 @@ macro_rules! __impl_public_bitflags { macro_rules! __impl_public_bitflags_iter { ($BitFlags:ident: $T:ty, $PublicBitFlags:ident) => { impl $BitFlags { - /// Iterate over enabled flag values. + /// Yield a set of contained flags values. + /// + /// Each yielded flags value will correspond to a defined named flag. Any unknown bits + /// will be yielded together as a final flags value. #[inline] pub const fn iter(&self) -> $crate::iter::Iter<$PublicBitFlags> { $crate::iter::Iter::__private_const_new( @@ -278,7 +286,10 @@ macro_rules! __impl_public_bitflags_iter { ) } - /// Iterate over enabled flag values with their stringified names. + /// Yield a set of contained named flags values. + /// + /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags. + /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded. #[inline] pub const fn iter_names(&self) -> $crate::iter::IterNames<$PublicBitFlags> { $crate::iter::IterNames::__private_const_new( @@ -344,7 +355,7 @@ macro_rules! __impl_public_bitflags_ops { impl $crate::__private::core::ops::BitOr for $PublicBitFlags { type Output = Self; - /// Returns the union of the two sets of flags. + /// The bitwise or (`|`) of the bits in two flags values. #[inline] fn bitor(self, other: $PublicBitFlags) -> Self { self.union(other) @@ -352,17 +363,17 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::ops::BitOrAssign for $PublicBitFlags { - /// Adds the set of flags. + /// The bitwise or (`|`) of the bits in two flags values. #[inline] fn bitor_assign(&mut self, other: Self) { - *self = Self::from_bits_retain(self.bits()).union(other); + self.insert(other); } } impl $crate::__private::core::ops::BitXor for $PublicBitFlags { type Output = Self; - /// Returns the left flags, but with all the right flags toggled. + /// The bitwise exclusive-or (`^`) of the bits in two flags values. #[inline] fn bitxor(self, other: Self) -> Self { self.symmetric_difference(other) @@ -370,17 +381,17 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::ops::BitXorAssign for $PublicBitFlags { - /// Toggles the set of flags. + /// The bitwise exclusive-or (`^`) of the bits in two flags values. #[inline] fn bitxor_assign(&mut self, other: Self) { - *self = Self::from_bits_retain(self.bits()).symmetric_difference(other); + self.toggle(other); } } impl $crate::__private::core::ops::BitAnd for $PublicBitFlags { type Output = Self; - /// Returns the intersection between the two sets of flags. + /// The bitwise and (`&`) of the bits in two flags values. #[inline] fn bitand(self, other: Self) -> Self { self.intersection(other) @@ -388,7 +399,7 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::ops::BitAndAssign for $PublicBitFlags { - /// Disables all flags disabled in the set. + /// The bitwise and (`&`) of the bits in two flags values. #[inline] fn bitand_assign(&mut self, other: Self) { *self = Self::from_bits_retain(self.bits()).intersection(other); @@ -398,7 +409,10 @@ macro_rules! __impl_public_bitflags_ops { impl $crate::__private::core::ops::Sub for $PublicBitFlags { type Output = Self; - /// Returns the set difference of the two sets of flags. + /// The intersection of a source flags value with the complement of a target flags value (`&!`). + /// + /// This method is not equivalent to `self & !other` when `other` has unknown bits set. + /// `difference` won't truncate `other`, but the `!` operator will. #[inline] fn sub(self, other: Self) -> Self { self.difference(other) @@ -406,17 +420,20 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::ops::SubAssign for $PublicBitFlags { - /// Disables all flags enabled in the set. + /// The intersection of a source flags value with the complement of a target flags value (`&!`). + /// + /// This method is not equivalent to `self & !other` when `other` has unknown bits set. + /// `difference` won't truncate `other`, but the `!` operator will. #[inline] fn sub_assign(&mut self, other: Self) { - *self = Self::from_bits_retain(self.bits()).difference(other); + self.remove(other); } } impl $crate::__private::core::ops::Not for $PublicBitFlags { type Output = Self; - /// Returns the complement of this set of flags. + /// The bitwise negation (`!`) of the bits in a flags value, truncating the result. #[inline] fn not(self) -> Self { self.complement() @@ -424,6 +441,7 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::iter::Extend<$PublicBitFlags> for $PublicBitFlags { + /// The bitwise or (`|`) of the bits in each flags value. fn extend>( &mut self, iterator: T, @@ -435,6 +453,7 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::iter::FromIterator<$PublicBitFlags> for $PublicBitFlags { + /// The bitwise or (`|`) of the bits in each flags value. fn from_iter>( iterator: T, ) -> Self { @@ -455,35 +474,58 @@ macro_rules! __impl_public_bitflags_consts { ( $PublicBitFlags:ident: $T:ty { $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident = $value:expr; + $(#[$inner:ident $($args:tt)*])* + const $Flag:tt = $value:expr; )* } ) => { impl $PublicBitFlags { $( - $(#[$attr $($args)*])* - #[allow( - deprecated, - non_upper_case_globals, - )] - pub const $Flag: Self = Self::from_bits_retain($value); + __bitflags_flag!({ + name: $Flag, + named: { + $(#[$inner $($args)*])* + #[allow( + deprecated, + non_upper_case_globals, + )] + pub const $Flag: Self = Self::from_bits_retain($value); + }, + unnamed: {}, + }); )* } impl $crate::Flags for $PublicBitFlags { const FLAGS: &'static [$crate::Flag<$PublicBitFlags>] = &[ $( - __bitflags_expr_safe_attrs!( - $(#[$attr $($args)*])* - { - #[allow( - deprecated, - non_upper_case_globals, - )] - $crate::Flag::new($crate::__private::core::stringify!($Flag), $PublicBitFlags::$Flag) - } - ), + __bitflags_flag!({ + name: $Flag, + named: { + __bitflags_expr_safe_attrs!( + $(#[$inner $($args)*])* + { + #[allow( + deprecated, + non_upper_case_globals, + )] + $crate::Flag::new($crate::__private::core::stringify!($Flag), $PublicBitFlags::$Flag) + } + ) + }, + unnamed: { + __bitflags_expr_safe_attrs!( + $(#[$inner $($args)*])* + { + #[allow( + deprecated, + non_upper_case_globals, + )] + $crate::Flag::new("", $PublicBitFlags::from_bits_retain($value)) + } + ) + }, + }), )* ]; diff --git a/vendor/bitflags/src/tests.rs b/vendor/bitflags/src/tests.rs index cb41f75a3..ed52ad404 100644 --- a/vendor/bitflags/src/tests.rs +++ b/vendor/bitflags/src/tests.rs @@ -104,4 +104,28 @@ bitflags! { /// 2 const D = 1 << 1; } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestExternal: u8 { + /// 1 + const A = 1; + + /// 1 << 1 + const B = 1 << 1; + + /// 1 << 2 + const C = 1 << 2; + + /// 1 | (1 << 1) | (1 << 2) + const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); + + /// External + const _ = !0; + } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestExternalFull: u8 { + /// External + const _ = !0; + } } diff --git a/vendor/bitflags/src/traits.rs b/vendor/bitflags/src/traits.rs index 1e44645c8..28235142d 100644 --- a/vendor/bitflags/src/traits.rs +++ b/vendor/bitflags/src/traits.rs @@ -8,59 +8,157 @@ use crate::{ parser::{ParseError, ParseHex, WriteHex}, }; -/// Metadata for an individual flag. +/** +A defined flags value that may be named or unnamed. +*/ pub struct Flag { name: &'static str, value: B, } impl Flag { - /// Create a new flag with the given name and value. + /** + Define a flag. + + If `name` is non-empty then the flag is named, otherwise it's unnamed. + */ pub const fn new(name: &'static str, value: B) -> Self { Flag { name, value } } - /// Get the name of this flag. + /** + Get the name of this flag. + + If the flag is unnamed then the returned string will be empty. + */ pub const fn name(&self) -> &'static str { self.name } - /// Get the value of this flag. + /** + Get the flags value of this flag. + */ pub const fn value(&self) -> &B { &self.value } + + /** + Whether the flag is named. + + If [`Flag::name`] returns a non-empty string then this method will return `true`. + */ + pub const fn is_named(&self) -> bool { + !self.name.is_empty() + } + + /** + Whether the flag is unnamed. + + If [`Flag::name`] returns a non-empty string then this method will return `false`. + */ + pub const fn is_unnamed(&self) -> bool { + self.name.is_empty() + } } -/// A set of flags. -/// -/// This trait is automatically implemented for flags types defined using the `bitflags!` macro. -/// It can also be implemented manually for custom flags types. +/** +A set of defined flags using a bits type as storage. + +## Implementing `Flags` + +This trait is implemented by the [`bitflags`](macro.bitflags.html) macro: + +``` +use bitflags::bitflags; + +bitflags! { + struct MyFlags: u8 { + const A = 1; + const B = 1 << 1; + } +} +``` + +It can also be implemented manually: + +``` +use bitflags::{Flag, Flags}; + +struct MyFlags(u8); + +impl Flags for MyFlags { + const FLAGS: &'static [Flag] = &[ + Flag::new("A", MyFlags(1)), + Flag::new("B", MyFlags(1 << 1)), + ]; + + type Bits = u8; + + fn from_bits_retain(bits: Self::Bits) -> Self { + MyFlags(bits) + } + + fn bits(&self) -> Self::Bits { + self.0 + } +} +``` + +## Using `Flags` + +The `Flags` trait can be used generically to work with any flags types. In this example, +we can count the number of defined named flags: + +``` +# use bitflags::{bitflags, Flags}; +fn defined_flags() -> usize { + F::FLAGS.iter().filter(|f| f.is_named()).count() +} + +bitflags! { + struct MyFlags: u8 { + const A = 1; + const B = 1 << 1; + const C = 1 << 2; + + const _ = !0; + } +} + +assert_eq!(3, defined_flags::()); +``` +*/ pub trait Flags: Sized + 'static { - /// The set of available flags and their names. + /// The set of defined flags. const FLAGS: &'static [Flag]; - /// The underlying storage type. + /// The underlying bits type. type Bits: Bits; - /// Returns an empty set of flags. + /// Get a flags value with all bits unset. fn empty() -> Self { Self::from_bits_retain(Self::Bits::EMPTY) } - /// Returns the set containing all flags. + /// Get a flags value with all known bits set. fn all() -> Self { - Self::from_bits_truncate(Self::Bits::ALL) + let mut truncated = Self::Bits::EMPTY; + + for flag in Self::FLAGS.iter() { + truncated = truncated | flag.value().bits(); + } + + Self::from_bits_retain(truncated) } - /// Returns the raw value of the flags currently stored. + /// Get the underlying bits value. + /// + /// The returned value is exactly the bits set in this flags value. fn bits(&self) -> Self::Bits; - /// Convert from underlying bit representation, unless that - /// representation contains bits that do not correspond to a flag. - /// - /// Note that each [multi-bit flag] is treated as a unit for this comparison. + /// Convert from a bits value. /// - /// [multi-bit flag]: index.html#multi-bit-flags + /// This method will return `None` if any unknown bits are set. fn from_bits(bits: Self::Bits) -> Option { let truncated = Self::from_bits_truncate(bits); @@ -71,36 +169,24 @@ pub trait Flags: Sized + 'static { } } - /// Convert from underlying bit representation, dropping any bits - /// that do not correspond to flags. - /// - /// Note that each [multi-bit flag] is treated as a unit for this comparison. - /// - /// [multi-bit flag]: index.html#multi-bit-flags + /// Convert from a bits value, unsetting any unknown bits. fn from_bits_truncate(bits: Self::Bits) -> Self { - if bits == Self::Bits::EMPTY { - return Self::empty(); - } - - let mut truncated = Self::Bits::EMPTY; - - for flag in Self::FLAGS.iter() { - let flag = flag.value(); - - if bits & flag.bits() == flag.bits() { - truncated = truncated | flag.bits(); - } - } - - Self::from_bits_retain(truncated) + Self::from_bits_retain(bits & Self::all().bits()) } - /// Convert from underlying bit representation, preserving all - /// bits (even those not corresponding to a defined flag). + /// Convert from a bits value exactly. fn from_bits_retain(bits: Self::Bits) -> Self; - /// Get the flag for a particular name. + /// Get a flags value with the bits of a flag with the given name set. + /// + /// This method will return `None` if `name` is empty or doesn't + /// correspond to any named flag. fn from_name(name: &str) -> Option { + // Don't parse empty names as empty flags + if name.is_empty() { + return None; + } + for flag in Self::FLAGS { if flag.name() == name { return Some(Self::from_bits_retain(flag.value().bits())); @@ -110,29 +196,35 @@ pub trait Flags: Sized + 'static { None } - /// Iterate over enabled flag values. + /// Yield a set of contained flags values. + /// + /// Each yielded flags value will correspond to a defined named flag. Any unknown bits + /// will be yielded together as a final flags value. fn iter(&self) -> iter::Iter { iter::Iter::new(self) } - /// Iterate over the raw names and bits for enabled flag values. + /// Yield a set of contained named flags values. + /// + /// This method is like [`Flags::iter`], except only yields bits in contained named flags. + /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded. fn iter_names(&self) -> iter::IterNames { iter::IterNames::new(self) } - /// Returns `true` if no flags are currently stored. + /// Whether all bits in this flags value are unset. fn is_empty(&self) -> bool { self.bits() == Self::Bits::EMPTY } - /// Returns `true` if all flags are currently set. + /// Whether all known bits in this flags value are set. fn is_all(&self) -> bool { // NOTE: We check against `Self::all` here, not `Self::Bits::ALL` // because the set of all flags may not use all bits Self::all().bits() | self.bits() == self.bits() } - /// Returns `true` if there are flags common to both `self` and `other`. + /// Whether any set bits in a source flags value are also set in a target flags value. fn intersects(&self, other: Self) -> bool where Self: Sized, @@ -140,7 +232,7 @@ pub trait Flags: Sized + 'static { self.bits() & other.bits() != Self::Bits::EMPTY } - /// Returns `true` if all of the flags in `other` are contained within `self`. + /// Whether all set bits in a source flags value are also set in a target flags value. fn contains(&self, other: Self) -> bool where Self: Sized, @@ -148,37 +240,34 @@ pub trait Flags: Sized + 'static { self.bits() & other.bits() == other.bits() } - /// Inserts the specified flags in-place. - /// - /// This method is equivalent to `union`. + /// The bitwise or (`|`) of the bits in two flags values. fn insert(&mut self, other: Self) where Self: Sized, { - *self = Self::from_bits_retain(self.bits() | other.bits()); + *self = Self::from_bits_retain(self.bits()).union(other); } - /// Removes the specified flags in-place. + /// The intersection of a source flags value with the complement of a target flags value (`&!`). /// - /// This method is equivalent to `difference`. + /// This method is not equivalent to `self & !other` when `other` has unknown bits set. + /// `remove` won't truncate `other`, but the `!` operator will. fn remove(&mut self, other: Self) where Self: Sized, { - *self = Self::from_bits_retain(self.bits() & !other.bits()); + *self = Self::from_bits_retain(self.bits()).difference(other); } - /// Toggles the specified flags in-place. - /// - /// This method is equivalent to `symmetric_difference`. + /// The bitwise exclusive-or (`^`) of the bits in two flags values. fn toggle(&mut self, other: Self) where Self: Sized, { - *self = Self::from_bits_retain(self.bits() ^ other.bits()); + *self = Self::from_bits_retain(self.bits()).symmetric_difference(other); } - /// Inserts or removes the specified flags depending on the passed value. + /// Call [`Flags::insert`] when `value` is `true` or [`Flags::remove`] when `value` is `false`. fn set(&mut self, other: Self, value: bool) where Self: Sized, @@ -190,39 +279,43 @@ pub trait Flags: Sized + 'static { } } - /// Returns the intersection between the flags in `self` and `other`. + /// The bitwise and (`&`) of the bits in two flags values. #[must_use] fn intersection(self, other: Self) -> Self { Self::from_bits_retain(self.bits() & other.bits()) } - /// Returns the union of between the flags in `self` and `other`. + /// The bitwise or (`|`) of the bits in two flags values. #[must_use] fn union(self, other: Self) -> Self { Self::from_bits_retain(self.bits() | other.bits()) } - /// Returns the difference between the flags in `self` and `other`. + /// The intersection of a source flags value with the complement of a target flags value (`&!`). + /// + /// This method is not equivalent to `self & !other` when `other` has unknown bits set. + /// `difference` won't truncate `other`, but the `!` operator will. #[must_use] fn difference(self, other: Self) -> Self { Self::from_bits_retain(self.bits() & !other.bits()) } - /// Returns the symmetric difference between the flags - /// in `self` and `other`. + /// The bitwise exclusive-or (`^`) of the bits in two flags values. #[must_use] fn symmetric_difference(self, other: Self) -> Self { Self::from_bits_retain(self.bits() ^ other.bits()) } - /// Returns the complement of this set of flags. + /// The bitwise negation (`!`) of the bits in a flags value, truncating the result. #[must_use] fn complement(self) -> Self { Self::from_bits_truncate(!self.bits()) } } -/// Underlying storage for a flags type. +/** +A bits type that can be used as storage for a flags type. +*/ pub trait Bits: Clone + Copy @@ -234,10 +327,10 @@ pub trait Bits: + Sized + 'static { - /// The value of `Self` where no bits are set. + /// A value with all bits unset. const EMPTY: Self; - /// The value of `Self` where all bits are set. + /// A value with all bits set. const ALL: Self; } @@ -307,6 +400,7 @@ pub trait PublicFlags { type Internal; } +#[doc(hidden)] #[deprecated(note = "use the `Flags` trait instead")] pub trait BitFlags: ImplementedByBitFlagsMacro + Flags { /// An iterator over enabled flags in an instance of the type. -- cgit v1.2.3