Dataset Viewer
Auto-converted to Parquet Duplicate
problem_statement
stringlengths
130
2.62k
test_patch
stringlengths
344
99.3k
hints_text
stringlengths
0
2.14k
base_commit
stringlengths
40
40
issue_numbers
sequencelengths
1
1
created_at
stringdate
2021-12-16 09:38:14
2024-06-24 23:17:40
pull_number
int64
266
411
instance_id
stringlengths
22
22
patch
stringlengths
251
105k
version
stringclasses
7 values
repo
stringclasses
1 value
environment_setup_commit
stringclasses
7 values
updated_at
stringdate
2022-01-08 01:07:10
2024-06-24 23:29:24
Allow specifying attributes in `impl` mode I'm considering `cfg`-gating the use of `bitflags!` in my libraries, and to that end it would be nice if it was possible to apply attributes to the generated `impl`s as well. The naive solution would be: ```rust pub struct Flags(u8); #[cfg(feature = "bitflags")] bitflags! { impl Flags: u8 { // ... } } ``` However, that works poorly with the `doc_cfg` (and `doc_auto_cfg`) feature, as the attribute is only applied to the macro, and isn't passed down to each output item. Instead, I would like to be able to do the following: ```rust #![feature(doc_cfg)] pub struct Flags(u8); #[cfg(feature = "bitflags")] bitflags! { #[doc(cfg(feature = "bitflags"))] impl Flags: u8 { // ... } } ```
diff --git /dev/null b/tests/compile-pass/bitflags_impl_attrs.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/bitflags_impl_attrs.rs @@ -0,0 +1,13 @@ +extern crate bitflags; + +struct Example(u64); + +bitflags::bitflags! { + /// Docs on the `impl` block. + #[allow(dead_code)] + impl Example: u64 { + const flag = 0b01; + } +} + +fn main() {}
Thanks for the report @madsmtm! Anywhere attributes are allowed to be specified we should support in the macros as much as possible. I think this is just a missing piece of functionality for the impl mode.
9c4b93c931e34a5104f50e20be1bdd15bc593b0e
[ "406" ]
2024-06-24T23:17:40Z
411
bitflags__bitflags-411
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -38,7 +38,7 @@ bitflags! { 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. +Also see the [`example_generated`](./example_generated/index.html) module for an example of what the `bitflags` macro generates for a flags type. ### Externally defined flags diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -530,6 +530,7 @@ macro_rules! bitflags { } }; ( + $(#[$outer:meta])* impl $BitFlags:ident: $T:ty { $( $(#[$inner:ident $($args:tt)*])* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -561,6 +562,7 @@ macro_rules! bitflags { )] const _: () = { $crate::__impl_public_bitflags! { + $(#[$outer])* $BitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -593,6 +595,7 @@ macro_rules! bitflags { #[doc(hidden)] macro_rules! __impl_bitflags { ( + $(#[$outer:meta])* $PublicBitFlags:ident: $T:ty { fn empty() $empty:block fn all() $all:block diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -617,6 +620,7 @@ macro_rules! __impl_bitflags { } ) => { #[allow(dead_code, deprecated, unused_attributes)] + $(#[$outer])* impl $PublicBitFlags { /// Get a flags value with all bits unset. #[inline] diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -26,9 +26,11 @@ macro_rules! __declare_public_bitflags { #[doc(hidden)] macro_rules! __impl_public_bitflags_forward { ( + $(#[$outer:meta])* $PublicBitFlags:ident: $T:ty, $InternalBitFlags:ident ) => { $crate::__impl_bitflags! { + $(#[$outer])* $PublicBitFlags: $T { fn empty() { Self($InternalBitFlags::empty()) diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -128,6 +130,7 @@ macro_rules! __impl_public_bitflags_forward { #[doc(hidden)] macro_rules! __impl_public_bitflags { ( + $(#[$outer:meta])* $BitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$inner:ident $($args:tt)*])* diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -136,6 +139,7 @@ macro_rules! __impl_public_bitflags { } ) => { $crate::__impl_bitflags! { + $(#[$outer])* $BitFlags: $T { fn empty() { Self(<$T as $crate::Bits>::EMPTY) diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -271,7 +275,11 @@ macro_rules! __impl_public_bitflags { #[macro_export] #[doc(hidden)] macro_rules! __impl_public_bitflags_iter { - ($BitFlags:ident: $T:ty, $PublicBitFlags:ident) => { + ( + $(#[$outer:meta])* + $BitFlags:ident: $T:ty, $PublicBitFlags:ident + ) => { + $(#[$outer])* impl $BitFlags { /// Yield a set of contained flags values. /// diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -300,6 +308,7 @@ macro_rules! __impl_public_bitflags_iter { } } + $(#[$outer:meta])* impl $crate::__private::core::iter::IntoIterator for $BitFlags { type Item = $PublicBitFlags; type IntoIter = $crate::iter::Iter<$PublicBitFlags>; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -315,7 +324,12 @@ macro_rules! __impl_public_bitflags_iter { #[macro_export] #[doc(hidden)] macro_rules! __impl_public_bitflags_ops { - ($PublicBitFlags:ident) => { + ( + $(#[$outer:meta])* + $PublicBitFlags:ident + ) => { + + $(#[$outer])* impl $crate::__private::core::fmt::Binary for $PublicBitFlags { fn fmt( &self, diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -326,6 +340,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::fmt::Octal for $PublicBitFlags { fn fmt( &self, diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -336,6 +351,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::fmt::LowerHex for $PublicBitFlags { fn fmt( &self, diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -346,6 +362,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::fmt::UpperHex for $PublicBitFlags { fn fmt( &self, diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -356,6 +373,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitOr for $PublicBitFlags { type Output = Self; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -366,6 +384,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitOrAssign for $PublicBitFlags { /// The bitwise or (`|`) of the bits in two flags values. #[inline] diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -374,6 +393,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitXor for $PublicBitFlags { type Output = Self; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -384,6 +404,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitXorAssign for $PublicBitFlags { /// The bitwise exclusive-or (`^`) of the bits in two flags values. #[inline] diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -392,6 +413,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitAnd for $PublicBitFlags { type Output = Self; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -402,6 +424,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitAndAssign for $PublicBitFlags { /// The bitwise and (`&`) of the bits in two flags values. #[inline] diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -410,6 +433,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::Sub for $PublicBitFlags { type Output = Self; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -423,6 +447,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::SubAssign for $PublicBitFlags { /// The intersection of a source flags value with the complement of a target flags value (`&!`). /// diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -434,6 +459,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::Not for $PublicBitFlags { type Output = Self; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -444,6 +470,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::iter::Extend<$PublicBitFlags> for $PublicBitFlags { /// The bitwise or (`|`) of the bits in each flags value. fn extend<T: $crate::__private::core::iter::IntoIterator<Item = Self>>( diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -456,6 +483,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::iter::FromIterator<$PublicBitFlags> for $PublicBitFlags { /// The bitwise or (`|`) of the bits in each flags value. fn from_iter<T: $crate::__private::core::iter::IntoIterator<Item = Self>>( diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -476,6 +504,7 @@ macro_rules! __impl_public_bitflags_ops { #[doc(hidden)] macro_rules! __impl_public_bitflags_consts { ( + $(#[$outer:meta])* $PublicBitFlags:ident: $T:ty { $( $(#[$inner:ident $($args:tt)*])* diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -483,6 +512,7 @@ macro_rules! __impl_public_bitflags_consts { )* } ) => { + $(#[$outer])* impl $PublicBitFlags { $( $crate::__bitflags_flag!({ diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -500,6 +530,7 @@ macro_rules! __impl_public_bitflags_consts { )* } + $(#[$outer])* impl $crate::Flags for $PublicBitFlags { const FLAGS: &'static [$crate::Flag<$PublicBitFlags>] = &[ $(
2.5
bitflags/bitflags
9c4b93c931e34a5104f50e20be1bdd15bc593b0e
2024-06-24T23:29:24Z
Documenting bitflags: how to get documentation for the generated bitflags Some code that I'm writing uses the `#![warn(missing_docs)]` macro to enforce a requirement that all public interfaces have documentation. I haven't been able to figure out how to generate documentation when using the `bitflags!` macro; I also haven't been able to turn off the linter warning using `#![allow(missing_docs)]`. Is there a convenient way to add doc comments to a set of flags? * If so, is there an example somewhere that I can reference? This would be a great thing to include in bitflags documentation. * If not, then take this as a feature request!
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -84,18 +84,19 @@ jobs: cd ./tests/smoke-test cargo +$msrv build - mips: - name: Tests / MIPS (Big Endian) + miri: + name: "Miri" runs-on: ubuntu-latest steps: - - name: Checkout sources - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - - - name: Install Cross - run: cargo install cross - + - uses: actions/checkout@v3 + - name: Install Miri + run: | + rustup toolchain install nightly --component miri + cargo +nightly miri setup - name: Default features - run: cross test --target mips-unknown-linux-gnu + run: cargo +nightly miri test + - name: BE + run: cargo +nightly miri test --target s390x-unknown-linux-gnu clippy: name: Clippy diff --git a/src/tests/iter.rs b/src/tests/iter.rs --- a/src/tests/iter.rs +++ b/src/tests/iter.rs @@ -3,6 +3,7 @@ use super::*; use crate::Flags; #[test] +#[cfg(not(miri))] // Very slow in miri fn roundtrip() { for a in 0u8..=255 { for b in 0u8..=255 { diff --git a/src/tests/parser.rs b/src/tests/parser.rs --- a/src/tests/parser.rs +++ b/src/tests/parser.rs @@ -6,6 +6,7 @@ use crate::{ }; #[test] +#[cfg(not(miri))] // Very slow in miri fn roundtrip() { let mut s = String::new(); diff --git a/tests/compile-pass/item_positions.rs b/tests/compile-pass/item_positions.rs --- a/tests/compile-pass/item_positions.rs +++ b/tests/compile-pass/item_positions.rs @@ -1,3 +1,5 @@ +#![allow(clippy::let_unit_value)] + #[macro_use] extern crate bitflags; diff --git /dev/null b/tests/compile-pass/missing_docs.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/missing_docs.rs @@ -0,0 +1,19 @@ +/*! +Crate-level doc +*/ + +#![deny(missing_docs)] + +use bitflags::bitflags; + +bitflags! { + #[allow(missing_docs)] + pub struct MyFlags: u32 { + #[allow(missing_docs)] + const A = 1; + #[allow(missing_docs)] + const B = 2; + } +} + +fn main() {} diff --git a/tests/compile.rs b/tests/compile.rs --- a/tests/compile.rs +++ b/tests/compile.rs @@ -2,6 +2,7 @@ // an impossible build between error messages emitted on various channels. // Since https://github.com/dtolnay/trybuild/pull/170 we always need to have a // `stderr` file for each test so we can't simply ignore the output on different channels. +#[cfg(not(miri))] #[rustversion::attr(beta, test)] #[allow(dead_code)] fn fail() { diff --git a/tests/compile.rs b/tests/compile.rs --- a/tests/compile.rs +++ b/tests/compile.rs @@ -9,6 +10,7 @@ fn fail() { t.compile_fail("tests/compile-fail/**/*.rs"); } +#[cfg(not(miri))] #[test] fn pass() { let t = trybuild::TestCases::new();
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=530756068e54aa56eb519dd66c9fdfc5 https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f782c74e49e8c4c4ae940125265eb7ed Thanks @rusty-snake! Those would actually make some great compile-pass tests 🤔
472e392c0d082c0894b18fb31f4e68e0b145e29c
[ "378" ]
2023-10-09T04:48:32Z
380
bitflags__bitflags-380
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -46,11 +46,17 @@ use bitflags::bitflags; // The `bitflags!` macro generates `struct`s that manage a set of flags. bitflags! { + /// Represents a set of flags. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] struct Flags: u32 { + /// The value `A`, at bit position `0`. const A = 0b00000001; + /// The value `B`, at bit position `1`. const B = 0b00000010; + /// The value `C`, at bit position `2`. const C = 0b00000100; + + /// The combination of `A`, `B`, and `C`. const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -481,7 +481,8 @@ macro_rules! bitflags { non_upper_case_globals, clippy::assign_op_pattern, clippy::indexing_slicing, - clippy::same_name_method + clippy::same_name_method, + clippy::iter_without_into_iter, )] const _: () = { // Declared in a "hidden" scope that can't be reached directly diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -553,7 +554,8 @@ macro_rules! bitflags { unused_mut, unused_imports, non_upper_case_globals, - clippy::assign_op_pattern + clippy::assign_op_pattern, + clippy::iter_without_into_iter, )] const _: () = { __impl_public_bitflags! {
2.4
bitflags/bitflags
472e392c0d082c0894b18fb31f4e68e0b145e29c
2023-10-15T22:17:01Z
Inconsistent debug output for flag with no bits In a bitflags type where one of the named value has the value 0, the debug output for the type sometimes includes that value by name, and sometimes doesn't, apparently depending on whether any unrecognized bits are present. For example, this: ```rust use bitflags::bitflags; bitflags! { #[derive(Debug)] pub struct Flags: u32 { const RDONLY = 0; const WRONLY = 1; } } fn main() { println!("{:?}", Flags::RDONLY); println!("{:?}", Flags::from_bits_retain(0x100)); } ``` prints ``` Flags(0x0) Flags(RDONLY | 0x100) ``` I don't have an opinion about whether it should print `RDONLY` in both or neither, but printing it in just one is confusing.
diff --git a/src/external/bytemuck.rs b/src/external/bytemuck.rs --- a/src/external/bytemuck.rs +++ b/src/external/bytemuck.rs @@ -1,7 +1,7 @@ #[cfg(test)] mod tests { use bytemuck::{Pod, Zeroable}; - + bitflags! { #[derive(Pod, Zeroable, Clone, Copy)] #[repr(transparent)] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -422,10 +422,11 @@ #![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.2")] #[doc(inline)] -pub use traits::{Flags, Flag, Bits}; +pub use traits::{Bits, Flag, Flags}; pub mod iter; pub mod parser; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1045,1105 +1024,4 @@ mod external; pub mod example_generated; #[cfg(test)] -mod tests { - use std::{ - collections::hash_map::DefaultHasher, - fmt, - hash::{Hash, Hasher}, - str, - }; - - #[derive(Debug, PartialEq, Eq)] - pub struct ManualFlags(u32); - - bitflags! { - #[doc = "> The first principle is that you must not fool yourself — and"] - #[doc = "> you are the easiest person to fool."] - #[doc = "> "] - #[doc = "> - Richard Feynman"] - #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] - struct Flags: u32 { - const A = 0b00000001; - #[doc = "<pcwalton> macros are way better at generating code than trans is"] - const B = 0b00000010; - const C = 0b00000100; - #[doc = "* cmr bed"] - #[doc = "* strcat table"] - #[doc = "<strcat> wait what?"] - const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); - } - - #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] - struct _CfgFlags: u32 { - #[cfg(unix)] - const _CFG_A = 0b01; - #[cfg(windows)] - const _CFG_B = 0b01; - #[cfg(unix)] - const _CFG_C = Self::_CFG_A.bits() | 0b10; - } - - #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] - struct AnotherSetOfFlags: i8 { - const ANOTHER_FLAG = -1_i8; - } - - #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] - struct LongFlags: u32 { - const LONG_A = 0b1111111111111111; - } - - impl ManualFlags: u32 { - const A = 0b00000001; - #[doc = "<pcwalton> macros are way better at generating code than trans is"] - const B = 0b00000010; - const C = 0b00000100; - #[doc = "* cmr bed"] - #[doc = "* strcat table"] - #[doc = "<strcat> wait what?"] - const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); - } - } - - bitflags! { - #[derive(Debug, PartialEq, Eq)] - struct FmtFlags: u16 { - const 고양이 = 0b0000_0001; - const 개 = 0b0000_0010; - const 물고기 = 0b0000_0100; - const 물고기_고양이 = Self::고양이.bits() | Self::물고기.bits(); - } - } - - impl str::FromStr for FmtFlags { - type Err = crate::parser::ParseError; - - fn from_str(flags: &str) -> Result<Self, Self::Err> { - Ok(Self(flags.parse()?)) - } - } - - impl fmt::Display for FmtFlags { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } - } - - bitflags! { - #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] - struct EmptyFlags: u32 { - } - } - - #[test] - fn test_bits() { - assert_eq!(Flags::empty().bits(), 0b00000000); - assert_eq!(Flags::A.bits(), 0b00000001); - assert_eq!(Flags::ABC.bits(), 0b00000111); - - assert_eq!(<Flags as crate::Flags>::bits(&Flags::ABC), 0b00000111); - - assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00); - assert_eq!(AnotherSetOfFlags::ANOTHER_FLAG.bits(), !0_i8); - - assert_eq!(EmptyFlags::empty().bits(), 0b00000000); - } - - #[test] - fn test_from_bits() { - assert_eq!(Flags::from_bits(0), Some(Flags::empty())); - assert_eq!(Flags::from_bits(0b1), Some(Flags::A)); - assert_eq!(Flags::from_bits(0b10), Some(Flags::B)); - assert_eq!(Flags::from_bits(0b11), Some(Flags::A | Flags::B)); - assert_eq!(Flags::from_bits(0b1000), None); - - assert_eq!(<Flags as crate::Flags>::from_bits(0b11), Some(Flags::A | Flags::B)); - - assert_eq!( - AnotherSetOfFlags::from_bits(!0_i8), - Some(AnotherSetOfFlags::ANOTHER_FLAG) - ); - - assert_eq!(EmptyFlags::from_bits(0), Some(EmptyFlags::empty())); - assert_eq!(EmptyFlags::from_bits(0b1), None); - } - - #[test] - fn test_from_bits_truncate() { - assert_eq!(Flags::from_bits_truncate(0), Flags::empty()); - assert_eq!(Flags::from_bits_truncate(0b1), Flags::A); - assert_eq!(Flags::from_bits_truncate(0b10), Flags::B); - assert_eq!(Flags::from_bits_truncate(0b11), (Flags::A | Flags::B)); - assert_eq!(Flags::from_bits_truncate(0b1000), Flags::empty()); - assert_eq!(Flags::from_bits_truncate(0b1001), Flags::A); - - assert_eq!(<Flags as crate::Flags>::from_bits_truncate(0b11), (Flags::A | Flags::B)); - - assert_eq!( - AnotherSetOfFlags::from_bits_truncate(0_i8), - AnotherSetOfFlags::empty() - ); - - assert_eq!(EmptyFlags::from_bits_truncate(0), EmptyFlags::empty()); - assert_eq!(EmptyFlags::from_bits_truncate(0b1), EmptyFlags::empty()); - } - - #[test] - fn test_from_bits_retain() { - let extra = Flags::from_bits_retain(0b1000); - assert_eq!(Flags::from_bits_retain(0), Flags::empty()); - assert_eq!(Flags::from_bits_retain(0b1), Flags::A); - assert_eq!(Flags::from_bits_retain(0b10), Flags::B); - - assert_eq!(Flags::from_bits_retain(0b11), (Flags::A | Flags::B)); - assert_eq!(Flags::from_bits_retain(0b1000), (extra | Flags::empty())); - assert_eq!(Flags::from_bits_retain(0b1001), (extra | Flags::A)); - - assert_eq!(<Flags as crate::Flags>::from_bits_retain(0b11), (Flags::A | Flags::B)); - - let extra = EmptyFlags::from_bits_retain(0b1000); - assert_eq!( - EmptyFlags::from_bits_retain(0b1000), - (extra | EmptyFlags::empty()) - ); - } - - #[test] - fn test_is_empty() { - assert!(Flags::empty().is_empty()); - assert!(!Flags::A.is_empty()); - assert!(!Flags::ABC.is_empty()); - - assert!(!<Flags as crate::Flags>::is_empty(&Flags::ABC)); - - assert!(!AnotherSetOfFlags::ANOTHER_FLAG.is_empty()); - - assert!(EmptyFlags::empty().is_empty()); - assert!(EmptyFlags::all().is_empty()); - } - - #[test] - fn test_is_all() { - assert!(Flags::all().is_all()); - assert!(!Flags::A.is_all()); - assert!(Flags::ABC.is_all()); - - let extra = Flags::from_bits_retain(0b1000); - assert!(!extra.is_all()); - assert!(!(Flags::A | extra).is_all()); - assert!((Flags::ABC | extra).is_all()); - - assert!(<Flags as crate::Flags>::is_all(&Flags::all())); - - assert!(AnotherSetOfFlags::ANOTHER_FLAG.is_all()); - - assert!(EmptyFlags::all().is_all()); - assert!(EmptyFlags::empty().is_all()); - } - - #[test] - fn test_two_empties_do_not_intersect() { - let e1 = Flags::empty(); - let e2 = Flags::empty(); - assert!(!e1.intersects(e2)); - - assert!(!<Flags as crate::Flags>::intersects(&e1, e2)); - - assert!(AnotherSetOfFlags::ANOTHER_FLAG.intersects(AnotherSetOfFlags::ANOTHER_FLAG)); - } - - #[test] - fn test_empty_does_not_intersect_with_full() { - let e1 = Flags::empty(); - let e2 = Flags::ABC; - assert!(!e1.intersects(e2)); - - assert!(!<Flags as crate::Flags>::intersects(&e1, e2)); - } - - #[test] - fn test_disjoint_intersects() { - let e1 = Flags::A; - let e2 = Flags::B; - assert!(!e1.intersects(e2)); - - assert!(!<Flags as crate::Flags>::intersects(&e1, e2)); - } - - #[test] - fn test_overlapping_intersects() { - let e1 = Flags::A; - let e2 = Flags::A | Flags::B; - assert!(e1.intersects(e2)); - - assert!(<Flags as crate::Flags>::intersects(&e1, e2)); - } - - #[test] - fn test_contains() { - let e1 = Flags::A; - let e2 = Flags::A | Flags::B; - assert!(!e1.contains(e2)); - assert!(e2.contains(e1)); - assert!(Flags::ABC.contains(e2)); - - assert!(<Flags as crate::Flags>::contains(&Flags::ABC, e2)); - - assert!(AnotherSetOfFlags::ANOTHER_FLAG.contains(AnotherSetOfFlags::ANOTHER_FLAG)); - - assert!(EmptyFlags::empty().contains(EmptyFlags::empty())); - } - - #[test] - fn test_insert() { - let mut e1 = Flags::A; - let e2 = Flags::A | Flags::B; - e1.insert(e2); - assert_eq!(e1, e2); - - let mut e1 = Flags::A; - let e2 = Flags::A | Flags::B; - <Flags as crate::Flags>::insert(&mut e1, e2); - assert_eq!(e1, e2); - - let mut e3 = AnotherSetOfFlags::empty(); - e3.insert(AnotherSetOfFlags::ANOTHER_FLAG); - assert_eq!(e3, AnotherSetOfFlags::ANOTHER_FLAG); - } - - #[test] - fn test_remove() { - let mut e1 = Flags::A | Flags::B; - let e2 = Flags::A | Flags::C; - e1.remove(e2); - assert_eq!(e1, Flags::B); - - let mut e1 = Flags::A | Flags::B; - let e2 = Flags::A | Flags::C; - <Flags as crate::Flags>::remove(&mut e1, e2); - assert_eq!(e1, Flags::B); - - let mut e3 = AnotherSetOfFlags::ANOTHER_FLAG; - e3.remove(AnotherSetOfFlags::ANOTHER_FLAG); - assert_eq!(e3, AnotherSetOfFlags::empty()); - } - - #[test] - fn test_operators() { - 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 - assert_eq!(e1 ^ e2, Flags::A | Flags::B); // toggle - let mut e3 = e1; - e3.toggle(e2); - assert_eq!(e3, Flags::A | Flags::B); - - let mut m4 = AnotherSetOfFlags::empty(); - m4.toggle(AnotherSetOfFlags::empty()); - assert_eq!(m4, AnotherSetOfFlags::empty()); - } - - #[test] - fn test_operators_unchecked() { - let extra = Flags::from_bits_retain(0b1000); - let e1 = Flags::A | Flags::C | extra; - let e2 = Flags::B | Flags::C; - assert_eq!((e1 | e2), (Flags::ABC | extra)); // union - assert_eq!((e1 & e2), Flags::C); // intersection - assert_eq!((e1 - e2), (Flags::A | extra)); // set difference - assert_eq!(!e2, Flags::A); // set complement - assert_eq!(!e1, Flags::B); // set complement - assert_eq!(e1 ^ e2, Flags::A | Flags::B | extra); // toggle - let mut e3 = e1; - e3.toggle(e2); - assert_eq!(e3, Flags::A | Flags::B | extra); - } - - #[test] - fn test_set_ops_basic() { - let ab = Flags::A.union(Flags::B); - let ac = Flags::A.union(Flags::C); - let bc = Flags::B.union(Flags::C); - assert_eq!(ab.bits(), 0b011); - assert_eq!(bc.bits(), 0b110); - assert_eq!(ac.bits(), 0b101); - - assert_eq!(ab, Flags::B.union(Flags::A)); - assert_eq!(ac, Flags::C.union(Flags::A)); - assert_eq!(bc, Flags::C.union(Flags::B)); - - assert_eq!(ac, <Flags as crate::Flags>::union(Flags::A, Flags::C)); - - assert_eq!(ac, Flags::A | Flags::C); - assert_eq!(bc, Flags::B | Flags::C); - assert_eq!(ab.union(bc), Flags::ABC); - - assert_eq!(ac, Flags::A | Flags::C); - assert_eq!(bc, Flags::B | Flags::C); - - assert_eq!(ac.union(bc), ac | bc); - assert_eq!(ac.union(bc), Flags::ABC); - assert_eq!(bc.union(ac), Flags::ABC); - - assert_eq!(ac.intersection(bc), ac & bc); - assert_eq!(ac.intersection(bc), Flags::C); - assert_eq!(bc.intersection(ac), Flags::C); - - assert_eq!(Flags::C, <Flags as crate::Flags>::intersection(ac, bc)); - - assert_eq!(ac.difference(bc), ac - bc); - assert_eq!(bc.difference(ac), bc - ac); - assert_eq!(ac.difference(bc), Flags::A); - assert_eq!(bc.difference(ac), Flags::B); - - assert_eq!(bc, <Flags as crate::Flags>::difference(bc, Flags::A)); - - assert_eq!(bc.complement(), !bc); - assert_eq!(bc.complement(), Flags::A); - - assert_eq!(Flags::A, <Flags as crate::Flags>::complement(bc)); - - assert_eq!(ac.symmetric_difference(bc), Flags::A.union(Flags::B)); - assert_eq!(bc.symmetric_difference(ac), Flags::A.union(Flags::B)); - - assert_eq!(ab, <Flags as crate::Flags>::symmetric_difference(ac, bc)); - } - - #[test] - fn test_set_ops_const() { - // These just test that these compile and don't cause use-site panics - // (would be possible if we had some sort of UB) - const INTERSECT: Flags = Flags::all().intersection(Flags::C); - const UNION: Flags = Flags::A.union(Flags::C); - const DIFFERENCE: Flags = Flags::all().difference(Flags::A); - const COMPLEMENT: Flags = Flags::C.complement(); - const SYM_DIFFERENCE: Flags = UNION.symmetric_difference(DIFFERENCE); - assert_eq!(INTERSECT, Flags::C); - assert_eq!(UNION, Flags::A | Flags::C); - assert_eq!(DIFFERENCE, Flags::all() - Flags::A); - assert_eq!(COMPLEMENT, !Flags::C); - assert_eq!( - SYM_DIFFERENCE, - (Flags::A | Flags::C) ^ (Flags::all() - Flags::A) - ); - } - - #[test] - fn test_set_ops_unchecked() { - let extra = Flags::from_bits_retain(0b1000); - let e1 = Flags::A.union(Flags::C).union(extra); - let e2 = Flags::B.union(Flags::C); - assert_eq!(e1.bits(), 0b1101); - assert_eq!(e1.union(e2), (Flags::ABC | extra)); - assert_eq!(e1.intersection(e2), Flags::C); - assert_eq!(e1.difference(e2), Flags::A | extra); - assert_eq!(e2.difference(e1), Flags::B); - assert_eq!(e2.complement(), Flags::A); - assert_eq!(e1.complement(), Flags::B); - assert_eq!(e1.symmetric_difference(e2), Flags::A | Flags::B | extra); // toggle - } - - #[test] - fn test_set_ops_exhaustive() { - // Define a flag that contains gaps to help exercise edge-cases, - // especially around "unknown" flags (e.g. ones outside of `all()` - // `from_bits_retain`). - // - when lhs and rhs both have different sets of unknown flags. - // - unknown flags at both ends, and in the middle - // - cases with "gaps". - bitflags! { - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - struct Test: u16 { - // Intentionally no `A` - const B = 0b000000010; - // Intentionally no `C` - const D = 0b000001000; - const E = 0b000010000; - const F = 0b000100000; - const G = 0b001000000; - // Intentionally no `H` - const I = 0b100000000; - } - } - let iter_test_flags = || (0..=0b111_1111_1111).map(|bits| Test::from_bits_retain(bits)); - - for a in iter_test_flags() { - assert_eq!( - a.complement(), - Test::from_bits_truncate(!a.bits()), - "wrong result: !({:?})", - a, - ); - assert_eq!(a.complement(), !a, "named != op: !({:?})", a); - for b in iter_test_flags() { - // Check that the named operations produce the expected bitwise - // values. - assert_eq!( - a.union(b).bits(), - a.bits() | b.bits(), - "wrong result: `{:?}` | `{:?}`", - a, - b, - ); - assert_eq!( - a.intersection(b).bits(), - a.bits() & b.bits(), - "wrong result: `{:?}` & `{:?}`", - a, - b, - ); - assert_eq!( - a.symmetric_difference(b).bits(), - a.bits() ^ b.bits(), - "wrong result: `{:?}` ^ `{:?}`", - a, - b, - ); - assert_eq!( - a.difference(b).bits(), - a.bits() & !b.bits(), - "wrong result: `{:?}` - `{:?}`", - a, - b, - ); - // Note: Difference is checked as both `a - b` and `b - a` - assert_eq!( - b.difference(a).bits(), - b.bits() & !a.bits(), - "wrong result: `{:?}` - `{:?}`", - b, - a, - ); - // Check that the named set operations are equivalent to the - // bitwise equivalents - assert_eq!(a.union(b), a | b, "named != op: `{:?}` | `{:?}`", a, b,); - assert_eq!( - a.intersection(b), - a & b, - "named != op: `{:?}` & `{:?}`", - a, - b, - ); - assert_eq!( - a.symmetric_difference(b), - a ^ b, - "named != op: `{:?}` ^ `{:?}`", - a, - b, - ); - assert_eq!(a.difference(b), a - b, "named != op: `{:?}` - `{:?}`", a, b,); - // Note: Difference is checked as both `a - b` and `b - a` - assert_eq!(b.difference(a), b - a, "named != op: `{:?}` - `{:?}`", b, a,); - // Verify that the operations which should be symmetric are - // actually symmetric. - assert_eq!(a.union(b), b.union(a), "asymmetry: `{:?}` | `{:?}`", a, b,); - assert_eq!( - a.intersection(b), - b.intersection(a), - "asymmetry: `{:?}` & `{:?}`", - a, - b, - ); - assert_eq!( - a.symmetric_difference(b), - b.symmetric_difference(a), - "asymmetry: `{:?}` ^ `{:?}`", - a, - b, - ); - } - } - } - - #[test] - fn test_set() { - let mut e1 = Flags::A | Flags::C; - e1.set(Flags::B, true); - e1.set(Flags::C, false); - - assert_eq!(e1, Flags::A | Flags::B); - } - - #[test] - fn test_assignment_operators() { - let mut m1 = Flags::empty(); - let e1 = Flags::A | Flags::C; - // union - m1 |= Flags::A; - assert_eq!(m1, Flags::A); - // intersection - m1 &= e1; - assert_eq!(m1, Flags::A); - // set difference - m1 -= m1; - assert_eq!(m1, Flags::empty()); - // toggle - m1 ^= e1; - assert_eq!(m1, e1); - } - - #[test] - fn test_const_fn() { - const _M1: Flags = Flags::empty(); - - const M2: Flags = Flags::A; - assert_eq!(M2, Flags::A); - - const M3: Flags = Flags::C; - assert_eq!(M3, Flags::C); - } - - #[test] - fn test_extend() { - let mut flags; - - flags = Flags::empty(); - flags.extend([].iter().cloned()); - assert_eq!(flags, Flags::empty()); - - flags = Flags::empty(); - flags.extend([Flags::A, Flags::B].iter().cloned()); - assert_eq!(flags, Flags::A | Flags::B); - - flags = Flags::A; - flags.extend([Flags::A, Flags::B].iter().cloned()); - assert_eq!(flags, Flags::A | Flags::B); - - flags = Flags::B; - flags.extend([Flags::A, Flags::ABC].iter().cloned()); - assert_eq!(flags, Flags::ABC); - } - - #[test] - fn test_from_iterator() { - assert_eq!([].iter().cloned().collect::<Flags>(), Flags::empty()); - assert_eq!( - [Flags::A, Flags::B].iter().cloned().collect::<Flags>(), - Flags::A | Flags::B - ); - assert_eq!( - [Flags::A, Flags::ABC].iter().cloned().collect::<Flags>(), - Flags::ABC - ); - } - - #[test] - fn test_lt() { - let mut a = Flags::empty(); - let mut b = Flags::empty(); - - assert!(!(a < b) && !(b < a)); - b = Flags::B; - assert!(a < b); - a = Flags::C; - assert!(!(a < b) && b < a); - b = Flags::C | Flags::B; - assert!(a < b); - } - - #[test] - fn test_ord() { - let mut a = Flags::empty(); - let mut b = Flags::empty(); - - assert!(a <= b && a >= b); - a = Flags::A; - assert!(a > b && a >= b); - assert!(b < a && b <= a); - b = Flags::B; - assert!(b > a && b >= a); - assert!(a < b && a <= b); - } - - fn hash<T: Hash>(t: &T) -> u64 { - let mut s = DefaultHasher::new(); - t.hash(&mut s); - s.finish() - } - - #[test] - fn test_hash() { - let mut x = Flags::empty(); - let mut y = Flags::empty(); - assert_eq!(hash(&x), hash(&y)); - x = Flags::all(); - y = Flags::ABC; - assert_eq!(hash(&x), hash(&y)); - } - - #[test] - fn test_default() { - assert_eq!(Flags::empty(), Flags::default()); - } - - #[test] - fn test_debug() { - assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)"); - assert_eq!(format!("{:?}", Flags::empty()), "Flags(0x0)"); - assert_eq!(format!("{:?}", Flags::ABC), "Flags(A | B | C)"); - - let extra = Flags::from_bits_retain(0xb8); - - assert_eq!(format!("{:?}", extra), "Flags(0xb8)"); - assert_eq!(format!("{:?}", Flags::A | extra), "Flags(A | 0xb8)"); - - assert_eq!( - format!("{:?}", Flags::ABC | extra), - "Flags(A | B | C | ABC | 0xb8)" - ); - - assert_eq!(format!("{:?}", EmptyFlags::empty()), "EmptyFlags(0x0)"); - } - - #[test] - fn test_display_from_str_roundtrip() { - fn format_parse_case<T: fmt::Debug + fmt::Display + str::FromStr + PartialEq>(flags: T) where <T as str::FromStr>::Err: fmt::Display { - assert_eq!(flags, { - match flags.to_string().parse::<T>() { - Ok(flags) => flags, - Err(e) => panic!("failed to parse `{}`: {}", flags, e), - } - }); - } - - fn parse_case<T: fmt::Debug + str::FromStr + PartialEq>(expected: T, flags: &str) where <T as str::FromStr>::Err: fmt::Display + fmt::Debug { - assert_eq!(expected, flags.parse::<T>().unwrap()); - } - - bitflags! { - #[derive(Debug, Eq, PartialEq)] - pub struct MultiBitFmtFlags: u8 { - const A = 0b0000_0001u8; - const B = 0b0001_1110u8; - } - } - - impl fmt::Display for MultiBitFmtFlags { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } - } - - impl str::FromStr for MultiBitFmtFlags { - type Err = crate::parser::ParseError; - - fn from_str(s: &str) -> Result<Self, Self::Err> { - Ok(MultiBitFmtFlags(s.parse()?)) - } - } - - format_parse_case(FmtFlags::empty()); - format_parse_case(FmtFlags::all()); - format_parse_case(FmtFlags::고양이); - format_parse_case(FmtFlags::고양이 | FmtFlags::개); - format_parse_case(FmtFlags::물고기_고양이); - format_parse_case(FmtFlags::from_bits_retain(0xb8)); - format_parse_case(FmtFlags::from_bits_retain(0x20)); - format_parse_case(MultiBitFmtFlags::from_bits_retain(3)); - - parse_case(FmtFlags::empty(), ""); - parse_case(FmtFlags::empty(), " \r\n\t"); - parse_case(FmtFlags::empty(), "0x0"); - - parse_case(FmtFlags::고양이, "고양이"); - parse_case(FmtFlags::고양이, " 고양이 "); - parse_case(FmtFlags::고양이, "고양이 | 고양이 | 고양이"); - parse_case(FmtFlags::고양이, "0x01"); - - parse_case(FmtFlags::고양이 | FmtFlags::개, "고양이 | 개"); - parse_case(FmtFlags::고양이 | FmtFlags::개, "고양이|개"); - parse_case(FmtFlags::고양이 | FmtFlags::개, "\n고양이|개 "); - - parse_case(FmtFlags::고양이 | FmtFlags::물고기, "물고기_고양이"); - } - - #[test] - fn test_from_str_err() { - fn parse_case(pat: &str, flags: &str) { - let err = flags.parse::<FmtFlags>().unwrap_err().to_string(); - assert!(err.contains(pat), "`{}` not found in error `{}`", pat, err); - } - - parse_case("empty flag", "|"); - parse_case("empty flag", "|||"); - parse_case("empty flag", "고양이 |"); - parse_case("unrecognized named flag", "NOT_A_FLAG"); - parse_case("unrecognized named flag", "고양이 개"); - parse_case("unrecognized named flag", "고양이 | NOT_A_FLAG"); - parse_case("invalid hex flag", "0xhi"); - parse_case("invalid hex flag", "고양이 | 0xhi"); - } - - #[test] - fn test_binary() { - assert_eq!(format!("{:b}", Flags::ABC), "111"); - assert_eq!(format!("{:#b}", Flags::ABC), "0b111"); - let extra = Flags::from_bits_retain(0b1010000); - assert_eq!(format!("{:b}", Flags::ABC | extra), "1010111"); - assert_eq!(format!("{:#b}", Flags::ABC | extra), "0b1010111"); - } - - #[test] - fn test_octal() { - assert_eq!(format!("{:o}", LongFlags::LONG_A), "177777"); - assert_eq!(format!("{:#o}", LongFlags::LONG_A), "0o177777"); - let extra = LongFlags::from_bits_retain(0o5000000); - assert_eq!(format!("{:o}", LongFlags::LONG_A | extra), "5177777"); - assert_eq!(format!("{:#o}", LongFlags::LONG_A | extra), "0o5177777"); - } - - #[test] - fn test_lowerhex() { - assert_eq!(format!("{:x}", LongFlags::LONG_A), "ffff"); - assert_eq!(format!("{:#x}", LongFlags::LONG_A), "0xffff"); - let extra = LongFlags::from_bits_retain(0xe00000); - assert_eq!(format!("{:x}", LongFlags::LONG_A | extra), "e0ffff"); - assert_eq!(format!("{:#x}", LongFlags::LONG_A | extra), "0xe0ffff"); - } - - #[test] - fn test_upperhex() { - assert_eq!(format!("{:X}", LongFlags::LONG_A), "FFFF"); - assert_eq!(format!("{:#X}", LongFlags::LONG_A), "0xFFFF"); - let extra = LongFlags::from_bits_retain(0xe00000); - assert_eq!(format!("{:X}", LongFlags::LONG_A | extra), "E0FFFF"); - assert_eq!(format!("{:#X}", LongFlags::LONG_A | extra), "0xE0FFFF"); - } - - mod submodule { - bitflags! { - #[derive(Clone, Copy)] - pub struct PublicFlags: i8 { - const X = 0; - } - - #[derive(Clone, Copy)] - struct PrivateFlags: i8 { - const Y = 0; - } - } - - #[test] - fn test_private() { - let _ = PrivateFlags::Y; - } - } - - #[test] - fn test_public() { - let _ = submodule::PublicFlags::X; - } - - mod t1 { - mod foo { - pub type Bar = i32; - } - - bitflags! { - /// baz - #[derive(Clone, Copy)] - struct Flags: foo::Bar { - const A = 0b00000001; - #[cfg(foo)] - const B = 0b00000010; - #[cfg(foo)] - const C = 0b00000010; - } - } - } - - #[test] - fn test_in_function() { - bitflags! { - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - struct Flags: u8 { - const A = 1; - #[cfg(any())] // false - const B = 2; - } - } - assert_eq!(Flags::all(), Flags::A); - assert_eq!(format!("{:?}", Flags::A), "Flags(A)"); - } - - #[test] - fn test_deprecated() { - bitflags! { - #[derive(Clone, Copy)] - pub struct TestFlags: u32 { - #[deprecated(note = "Use something else.")] - const ONE = 1; - } - } - } - - #[test] - fn test_pub_crate() { - mod module { - bitflags! { - #[derive(Clone, Copy)] - pub (crate) struct Test: u8 { - const FOO = 1; - } - } - } - - assert_eq!(module::Test::FOO.bits(), 1); - } - - #[test] - fn test_pub_in_module() { - mod module { - mod submodule { - bitflags! { - // `pub (in super)` means only the module `module` will - // be able to access this. - #[derive(Clone, Copy)] - pub (in super) struct Test: u8 { - const FOO = 1; - } - } - } - - mod test { - // Note: due to `pub (in super)`, - // this cannot be accessed directly by the testing code. - pub(super) fn value() -> u8 { - super::submodule::Test::FOO.bits() - } - } - - pub fn value() -> u8 { - test::value() - } - } - - assert_eq!(module::value(), 1) - } - - #[test] - fn test_zero_value_flags() { - bitflags! { - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - struct Flags: u32 { - const NONE = 0b0; - const SOME = 0b1; - } - } - - assert!(Flags::empty().contains(Flags::NONE)); - assert!(Flags::SOME.contains(Flags::NONE)); - assert!(Flags::NONE.is_empty()); - - assert_eq!(format!("{:?}", Flags::SOME), "Flags(NONE | SOME)"); - } - - #[test] - fn test_empty_bitflags() { - bitflags! {} - } - - #[test] - fn test_u128_bitflags() { - bitflags! { - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - struct Flags: u128 { - const A = 0x0000_0000_0000_0000_0000_0000_0000_0001; - const B = 0x0000_0000_0000_1000_0000_0000_0000_0000; - const C = 0x8000_0000_0000_0000_0000_0000_0000_0000; - const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); - } - } - - assert_eq!(Flags::ABC, Flags::A | Flags::B | Flags::C); - assert_eq!(Flags::A.bits(), 0x0000_0000_0000_0000_0000_0000_0000_0001); - assert_eq!(Flags::B.bits(), 0x0000_0000_0000_1000_0000_0000_0000_0000); - assert_eq!(Flags::C.bits(), 0x8000_0000_0000_0000_0000_0000_0000_0000); - assert_eq!(Flags::ABC.bits(), 0x8000_0000_0000_1000_0000_0000_0000_0001); - assert_eq!(format!("{:?}", Flags::A), "Flags(A)"); - assert_eq!(format!("{:?}", Flags::B), "Flags(B)"); - assert_eq!(format!("{:?}", Flags::C), "Flags(C)"); - assert_eq!(format!("{:?}", Flags::ABC), "Flags(A | B | C)"); - } - - #[test] - fn test_from_bits_edge_cases() { - bitflags! { - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - struct Flags: u8 { - const A = 0b00000001; - const BC = 0b00000110; - } - } - - let flags = Flags::from_bits(0b00000100); - assert_eq!(flags, None); - let flags = Flags::from_bits(0b00000101); - assert_eq!(flags, None); - } - - #[test] - fn test_from_bits_truncate_edge_cases() { - bitflags! { - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - struct Flags: u8 { - const A = 0b00000001; - const BC = 0b00000110; - } - } - - let flags = Flags::from_bits_truncate(0b00000100); - assert_eq!(flags, Flags::empty()); - let flags = Flags::from_bits_truncate(0b00000101); - assert_eq!(flags, Flags::A); - } - - #[test] - fn test_iter() { - bitflags! { - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - struct Flags: u32 { - const ONE = 0b001; - const TWO = 0b010; - const THREE = 0b100; - #[cfg(windows)] - const FOUR_WIN = 0b1000; - #[cfg(unix)] - const FOUR_UNIX = 0b10000; - const FIVE = 0b01000100; - } - } - - let count = { - #[cfg(any(unix, windows))] - { - 5 - } - - #[cfg(not(any(unix, windows)))] - { - 4 - } - }; - - let flags = Flags::all(); - assert_eq!(flags.into_iter().count(), count); - - for flag in flags.into_iter() { - assert!(flags.contains(flag)); - } - - let mut iter = flags.iter_names(); - - assert_eq!(iter.next().unwrap(), ("ONE", Flags::ONE)); - assert_eq!(iter.next().unwrap(), ("TWO", Flags::TWO)); - assert_eq!(iter.next().unwrap(), ("THREE", Flags::THREE)); - - #[cfg(unix)] - { - assert_eq!(iter.next().unwrap(), ("FOUR_UNIX", Flags::FOUR_UNIX)); - } - #[cfg(windows)] - { - assert_eq!(iter.next().unwrap(), ("FOUR_WIN", Flags::FOUR_WIN)); - } - - assert_eq!(iter.next().unwrap(), ("FIVE", Flags::FIVE)); - - assert_eq!(iter.next(), None); - - let flags = Flags::empty(); - assert_eq!(flags.into_iter().count(), 0); - - let flags = Flags::ONE | Flags::THREE; - assert_eq!(flags.into_iter().count(), 2); - - let mut iter = flags.iter_names(); - - assert_eq!(iter.next().unwrap(), ("ONE", Flags::ONE)); - assert_eq!(iter.next().unwrap(), ("THREE", Flags::THREE)); - assert_eq!(iter.next(), None); - - let flags = Flags::from_bits_retain(0b1000_0000); - assert_eq!(flags.into_iter().count(), 1); - assert_eq!(flags.iter_names().count(), 0); - } - - #[test] - fn into_iter_from_iter_roundtrip() { - let flags = Flags::ABC | Flags::from_bits_retain(0b1000_0000); - - assert_eq!(flags, flags.into_iter().collect::<Flags>()); - } - - #[test] - fn test_from_name() { - let flags = Flags::all(); - - let mut rebuilt = Flags::empty(); - - for (name, value) in flags.iter_names() { - assert_eq!(value, Flags::from_name(name).unwrap()); - - rebuilt |= Flags::from_name(name).unwrap(); - } - - assert_eq!(flags, rebuilt); - } - - #[test] - fn bits_types() { - bitflags! { - pub struct I8: i8 { - const A = 1; - } - - pub struct I16: i16 { - const A = 1; - } - - pub struct I32: i32 { - const A = 1; - } - - pub struct I64: i64 { - const A = 1; - } - - pub struct I128: i128 { - const A = 1; - } - - pub struct Isize: isize { - const A = 1; - } - - pub struct U8: u8 { - const A = 1; - } - - pub struct U16: u16 { - const A = 1; - } - - pub struct U32: u32 { - const A = 1; - } - - pub struct U64: u64 { - const A = 1; - } - - pub struct U128: u128 { - const A = 1; - } - - pub struct Usize: usize { - const A = 1; - } - } - } -} +mod tests; diff --git /dev/null b/src/tests.rs new file mode 100644 --- /dev/null +++ b/src/tests.rs @@ -0,0 +1,107 @@ +mod all; +mod bits; +mod complement; +mod contains; +mod difference; +mod empty; +mod eq; +mod extend; +mod flags; +mod fmt; +mod from_bits; +mod from_bits_retain; +mod from_bits_truncate; +mod from_name; +mod insert; +mod intersection; +mod intersects; +mod is_all; +mod is_empty; +mod iter; +mod parser; +mod remove; +mod symmetric_difference; +mod union; + +bitflags! { + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestFlags: 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(); + } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestFlagsInvert: u8 { + /// 1 | (1 << 1) | (1 << 2) + const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); + + /// 1 + const A = 1; + + /// 1 << 1 + const B = 1 << 1; + + /// 1 << 2 + const C = 1 << 2; + } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestZero: u8 { + /// 0 + const ZERO = 0; + } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestZeroOne: u8 { + /// 0 + const ZERO = 0; + + /// 1 + const ONE = 1; + } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestUnicode: u8 { + /// 1 + const 一 = 1; + + /// 2 + const 二 = 1 << 1; + } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestEmpty: u8 {} + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestOverlapping: u8 { + /// 1 | (1 << 1) + const AB = 1 | (1 << 1); + + /// (1 << 1) | (1 << 2) + const BC = (1 << 1) | (1 << 2); + } + + #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] + pub struct TestOverlappingFull: u8 { + /// 1 + const A = 1; + + /// 1 + const B = 1; + + /// 1 + const C = 1; + + /// 2 + const D = 1 << 1; + } +} diff --git /dev/null b/src/tests/all.rs new file mode 100644 --- /dev/null +++ b/src/tests/all.rs @@ -0,0 +1,21 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(1 | 1 << 1 | 1 << 2, TestFlags::all); + + case(0, TestZero::all); + + case(0, TestEmpty::all); +} + +#[track_caller] +fn case<T: Flags>(expected: T::Bits, inherent: impl FnOnce() -> T) +where + <T as Flags>::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!(expected, inherent().bits(), "T::all()"); + assert_eq!(expected, T::all().bits(), "Flags::all()"); +} diff --git /dev/null b/src/tests/bits.rs new file mode 100644 --- /dev/null +++ b/src/tests/bits.rs @@ -0,0 +1,30 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(0, TestFlags::empty(), TestFlags::bits); + + case(1, TestFlags::A, TestFlags::bits); + case(1 | 1 << 1 | 1 << 2, TestFlags::ABC, TestFlags::bits); + + case(!0, TestFlags::from_bits_retain(u8::MAX), TestFlags::bits); + case(1 << 3, TestFlags::from_bits_retain(1 << 3), TestFlags::bits); + + case(1 << 3, TestZero::from_bits_retain(1 << 3), TestZero::bits); + + case(1 << 3, TestEmpty::from_bits_retain(1 << 3), TestEmpty::bits); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug>( + expected: T::Bits, + value: T, + inherent: impl FnOnce(&T) -> T::Bits, +) where + T::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!(expected, inherent(&value), "{:?}.bits()", value); + assert_eq!(expected, Flags::bits(&value), "Flags::bits({:?})", value); +} diff --git /dev/null b/src/tests/complement.rs new file mode 100644 --- /dev/null +++ b/src/tests/complement.rs @@ -0,0 +1,52 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(0, TestFlags::all(), TestFlags::complement); + case(0, TestFlags::from_bits_retain(!0), TestFlags::complement); + + case(1 | 1 << 1, TestFlags::C, TestFlags::complement); + case( + 1 | 1 << 1, + TestFlags::C | TestFlags::from_bits_retain(1 << 3), + TestFlags::complement, + ); + + case( + 1 | 1 << 1 | 1 << 2, + TestFlags::empty(), + TestFlags::complement, + ); + case( + 1 | 1 << 1 | 1 << 2, + TestFlags::from_bits_retain(1 << 3), + TestFlags::complement, + ); + + case(0, TestZero::empty(), TestZero::complement); + + case(0, TestEmpty::empty(), TestEmpty::complement); + + // Complement doesn't detect overlapping bits in multi-bit flags + case(0, TestOverlapping::AB, TestOverlapping::complement); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + std::ops::Not<Output = T> + Copy>( + expected: T::Bits, + value: T, + inherent: impl FnOnce(T) -> T, +) where + T::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!(expected, inherent(value).bits(), "{:?}.complement()", value); + assert_eq!( + expected, + Flags::complement(value).bits(), + "Flags::complement({:?})", + value + ); + assert_eq!(expected, (!value).bits(), "!{:?}", value); +} diff --git /dev/null b/src/tests/contains.rs new file mode 100644 --- /dev/null +++ b/src/tests/contains.rs @@ -0,0 +1,97 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[ + (TestFlags::empty(), true), + (TestFlags::A, false), + (TestFlags::B, false), + (TestFlags::C, false), + (TestFlags::from_bits_retain(1 << 3), false), + ], + TestFlags::contains, + ); + + case( + TestFlags::A, + &[ + (TestFlags::empty(), true), + (TestFlags::A, true), + (TestFlags::B, false), + (TestFlags::C, false), + (TestFlags::ABC, false), + (TestFlags::from_bits_retain(1 << 3), false), + (TestFlags::from_bits_retain(1 | (1 << 3)), false), + ], + TestFlags::contains, + ); + + case( + TestFlags::ABC, + &[ + (TestFlags::empty(), true), + (TestFlags::A, true), + (TestFlags::B, true), + (TestFlags::C, true), + (TestFlags::ABC, true), + (TestFlags::from_bits_retain(1 << 3), false), + ], + TestFlags::contains, + ); + + case( + TestFlags::from_bits_retain(1 << 3), + &[ + (TestFlags::empty(), true), + (TestFlags::A, false), + (TestFlags::B, false), + (TestFlags::C, false), + (TestFlags::from_bits_retain(1 << 3), true), + ], + TestFlags::contains, + ); + + case( + TestZero::ZERO, + &[(TestZero::ZERO, true)], + TestZero::contains, + ); + + case( + TestOverlapping::AB, + &[ + (TestOverlapping::AB, true), + (TestOverlapping::BC, false), + (TestOverlapping::from_bits_retain(1 << 1), true), + ], + TestOverlapping::contains, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + Copy>( + value: T, + inputs: &[(T, bool)], + mut inherent: impl FnMut(&T, T) -> bool, +) { + for (input, expected) in inputs { + assert_eq!( + *expected, + inherent(&value, *input), + "{:?}.contains({:?})", + value, + input + ); + assert_eq!( + *expected, + Flags::contains(&value, *input), + "Flags::contains({:?}, {:?})", + value, + input + ); + } +} diff --git /dev/null b/src/tests/difference.rs new file mode 100644 --- /dev/null +++ b/src/tests/difference.rs @@ -0,0 +1,81 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::A | TestFlags::B, + &[ + (TestFlags::A, 1 << 1), + (TestFlags::B, 1), + (TestFlags::from_bits_retain(1 << 3), 1 | 1 << 1), + ], + TestFlags::difference, + ); + + case( + TestFlags::from_bits_retain(1 | 1 << 3), + &[ + (TestFlags::A, 1 << 3), + (TestFlags::from_bits_retain(1 << 3), 1), + ], + TestFlags::difference, + ); + + assert_eq!( + 0b1111_1110, + (TestFlags::from_bits_retain(!0).difference(TestFlags::A)).bits() + ); + + // The `!` operator unsets bits that don't correspond to known flags + assert_eq!( + 1 << 1 | 1 << 2, + (TestFlags::from_bits_retain(!0) & !TestFlags::A).bits() + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + std::ops::Sub<Output = T> + std::ops::SubAssign + Copy>( + value: T, + inputs: &[(T, T::Bits)], + mut inherent: impl FnMut(T, T) -> T, +) where + T::Bits: std::fmt::Debug + PartialEq + Copy, +{ + for (input, expected) in inputs { + assert_eq!( + *expected, + inherent(value, *input).bits(), + "{:?}.difference({:?})", + value, + input + ); + assert_eq!( + *expected, + Flags::difference(value, *input).bits(), + "Flags::difference({:?}, {:?})", + value, + input + ); + assert_eq!( + *expected, + (value - *input).bits(), + "{:?} - {:?}", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + value -= *input; + value + } + .bits(), + "{:?} -= {:?}", + value, + input, + ); + } +} diff --git /dev/null b/src/tests/empty.rs new file mode 100644 --- /dev/null +++ b/src/tests/empty.rs @@ -0,0 +1,21 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(0, TestFlags::empty); + + case(0, TestZero::empty); + + case(0, TestEmpty::empty); +} + +#[track_caller] +fn case<T: Flags>(expected: T::Bits, inherent: impl FnOnce() -> T) +where + <T as Flags>::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!(expected, inherent().bits(), "T::empty()"); + assert_eq!(expected, T::empty().bits(), "Flags::empty()"); +} diff --git /dev/null b/src/tests/eq.rs new file mode 100644 --- /dev/null +++ b/src/tests/eq.rs @@ -0,0 +1,10 @@ +use super::*; + +#[test] +fn cases() { + assert_eq!(TestFlags::empty(), TestFlags::empty()); + assert_eq!(TestFlags::all(), TestFlags::all()); + + assert!(TestFlags::from_bits_retain(1) < TestFlags::from_bits_retain(2)); + assert!(TestFlags::from_bits_retain(2) > TestFlags::from_bits_retain(1)); +} diff --git /dev/null b/src/tests/extend.rs new file mode 100644 --- /dev/null +++ b/src/tests/extend.rs @@ -0,0 +1,18 @@ +use super::*; + +#[test] +fn cases() { + let mut flags = TestFlags::empty(); + + flags.extend(TestFlags::A); + + assert_eq!(TestFlags::A, flags); + + flags.extend(TestFlags::A | TestFlags::B | TestFlags::C); + + assert_eq!(TestFlags::ABC, flags); + + flags.extend(TestFlags::from_bits_retain(1 << 5)); + + assert_eq!(TestFlags::ABC | TestFlags::from_bits_retain(1 << 5), flags); +} diff --git /dev/null b/src/tests/flags.rs new file mode 100644 --- /dev/null +++ b/src/tests/flags.rs @@ -0,0 +1,23 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + let flags = TestFlags::FLAGS + .iter() + .map(|flag| (flag.name(), flag.value().bits())) + .collect::<Vec<_>>(); + + assert_eq!( + vec![ + ("A", 1u8), + ("B", 1 << 1), + ("C", 1 << 2), + ("ABC", 1 | 1 << 1 | 1 << 2), + ], + flags, + ); + + assert_eq!(0, TestEmpty::FLAGS.iter().count()); +} diff --git /dev/null b/src/tests/fmt.rs new file mode 100644 --- /dev/null +++ b/src/tests/fmt.rs @@ -0,0 +1,70 @@ +use super::*; + +#[test] +fn cases() { + case(TestFlags::empty(), "TestFlags(0x0)", "0", "0", "0", "0"); + case(TestFlags::A, "TestFlags(A)", "1", "1", "1", "1"); + case( + TestFlags::all(), + "TestFlags(A | B | C)", + "7", + "7", + "7", + "111", + ); + case( + TestFlags::from_bits_retain(1 << 3), + "TestFlags(0x8)", + "8", + "8", + "10", + "1000", + ); + case( + TestFlags::A | TestFlags::from_bits_retain(1 << 3), + "TestFlags(A | 0x8)", + "9", + "9", + "11", + "1001", + ); + + case(TestZero::ZERO, "TestZero(0x0)", "0", "0", "0", "0"); + case( + TestZero::ZERO | TestZero::from_bits_retain(1), + "TestZero(0x1)", + "1", + "1", + "1", + "1", + ); + + case(TestZeroOne::ONE, "TestZeroOne(ONE)", "1", "1", "1", "1"); + + case( + TestOverlapping::from_bits_retain(1 << 1), + "TestOverlapping(0x2)", + "2", + "2", + "2", + "10", + ); +} + +#[track_caller] +fn case< + T: std::fmt::Debug + std::fmt::UpperHex + std::fmt::LowerHex + std::fmt::Octal + std::fmt::Binary, +>( + value: T, + debug: &str, + uhex: &str, + lhex: &str, + oct: &str, + bin: &str, +) { + assert_eq!(debug, format!("{:?}", value)); + assert_eq!(uhex, format!("{:X}", value)); + assert_eq!(lhex, format!("{:x}", value)); + assert_eq!(oct, format!("{:o}", value)); + assert_eq!(bin, format!("{:b}", value)); +} diff --git /dev/null b/src/tests/from_bits.rs new file mode 100644 --- /dev/null +++ b/src/tests/from_bits.rs @@ -0,0 +1,43 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(Some(0), 0, TestFlags::from_bits); + case(Some(1), 1, TestFlags::from_bits); + case( + Some(1 | 1 << 1 | 1 << 2), + 1 | 1 << 1 | 1 << 2, + TestFlags::from_bits, + ); + + case(None, 1 << 3, TestFlags::from_bits); + case(None, 1 | 1 << 3, TestFlags::from_bits); + + case(Some(1 | 1 << 1), 1 | 1 << 1, TestOverlapping::from_bits); + + case(None, 1 << 1, TestOverlapping::from_bits); +} + +#[track_caller] +fn case<T: Flags>( + expected: Option<T::Bits>, + input: T::Bits, + inherent: impl FnOnce(T::Bits) -> Option<T>, +) where + <T as Flags>::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!( + expected, + inherent(input).map(|f| f.bits()), + "T::from_bits({:?})", + input + ); + assert_eq!( + expected, + T::from_bits(input).map(|f| f.bits()), + "Flags::from_bits({:?})", + input + ); +} diff --git /dev/null b/src/tests/from_bits_retain.rs new file mode 100644 --- /dev/null +++ b/src/tests/from_bits_retain.rs @@ -0,0 +1,36 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(0, TestFlags::from_bits_retain); + case(1, TestFlags::from_bits_retain); + case(1 | 1 << 1 | 1 << 2, TestFlags::from_bits_retain); + + case(1 << 3, TestFlags::from_bits_retain); + case(1 | 1 << 3, TestFlags::from_bits_retain); + + case(1 | 1 << 1, TestOverlapping::from_bits_retain); + + case(1 << 1, TestOverlapping::from_bits_retain); +} + +#[track_caller] +fn case<T: Flags>(input: T::Bits, inherent: impl FnOnce(T::Bits) -> T) +where + <T as Flags>::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!( + input, + inherent(input).bits(), + "T::from_bits_retain({:?})", + input + ); + assert_eq!( + input, + T::from_bits_retain(input).bits(), + "Flags::from_bits_retain({:?})", + input + ); +} diff --git /dev/null b/src/tests/from_bits_truncate.rs new file mode 100644 --- /dev/null +++ b/src/tests/from_bits_truncate.rs @@ -0,0 +1,40 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(0, 0, TestFlags::from_bits_truncate); + case(1, 1, TestFlags::from_bits_truncate); + case( + 1 | 1 << 1 | 1 << 2, + 1 | 1 << 1 | 1 << 2, + TestFlags::from_bits_truncate, + ); + + case(0, 1 << 3, TestFlags::from_bits_truncate); + case(1, 1 | 1 << 3, TestFlags::from_bits_truncate); + + case(1 | 1 << 1, 1 | 1 << 1, TestOverlapping::from_bits_truncate); + + case(0, 1 << 1, TestOverlapping::from_bits_truncate); +} + +#[track_caller] +fn case<T: Flags>(expected: T::Bits, input: T::Bits, inherent: impl FnOnce(T::Bits) -> T) +where + <T as Flags>::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!( + expected, + inherent(input).bits(), + "T::from_bits_truncate({:?})", + input + ); + assert_eq!( + expected, + T::from_bits_truncate(input).bits(), + "Flags::from_bits_truncate({:?})", + input + ); +} diff --git /dev/null b/src/tests/from_name.rs new file mode 100644 --- /dev/null +++ b/src/tests/from_name.rs @@ -0,0 +1,38 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(Some(1), "A", TestFlags::from_name); + case(Some(1 << 1), "B", TestFlags::from_name); + case(Some(1 | 1 << 1 | 1 << 2), "ABC", TestFlags::from_name); + + case(None, "", TestFlags::from_name); + case(None, "a", TestFlags::from_name); + case(None, "0x1", TestFlags::from_name); + case(None, "A | B", TestFlags::from_name); + + case(Some(0), "ZERO", TestZero::from_name); + + case(Some(2), "二", TestUnicode::from_name); +} + +#[track_caller] +fn case<T: Flags>(expected: Option<T::Bits>, input: &str, inherent: impl FnOnce(&str) -> Option<T>) +where + <T as Flags>::Bits: std::fmt::Debug + PartialEq, +{ + assert_eq!( + expected, + inherent(input).map(|f| f.bits()), + "T::from_name({:?})", + input + ); + assert_eq!( + expected, + T::from_name(input).map(|f| f.bits()), + "Flags::from_name({:?})", + input + ); +} diff --git /dev/null b/src/tests/insert.rs new file mode 100644 --- /dev/null +++ b/src/tests/insert.rs @@ -0,0 +1,91 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[ + (TestFlags::A, 1), + (TestFlags::A | TestFlags::B, 1 | 1 << 1), + (TestFlags::empty(), 0), + (TestFlags::from_bits_retain(1 << 3), 1 << 3), + ], + TestFlags::insert, + TestFlags::set, + ); + + case( + TestFlags::A, + &[ + (TestFlags::A, 1), + (TestFlags::empty(), 1), + (TestFlags::B, 1 | 1 << 1), + ], + TestFlags::insert, + TestFlags::set, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + Copy>( + value: T, + inputs: &[(T, T::Bits)], + mut inherent_insert: impl FnMut(&mut T, T), + mut inherent_set: impl FnMut(&mut T, T, bool), +) where + T::Bits: std::fmt::Debug + PartialEq + Copy, +{ + for (input, expected) in inputs { + assert_eq!( + *expected, + { + let mut value = value; + inherent_insert(&mut value, *input); + value + } + .bits(), + "{:?}.insert({:?})", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + Flags::insert(&mut value, *input); + value + } + .bits(), + "Flags::insert({:?}, {:?})", + value, + input + ); + + assert_eq!( + *expected, + { + let mut value = value; + inherent_set(&mut value, *input, true); + value + } + .bits(), + "{:?}.set({:?}, true)", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + Flags::set(&mut value, *input, true); + value + } + .bits(), + "Flags::set({:?}, {:?}, true)", + value, + input + ); + } +} diff --git /dev/null b/src/tests/intersection.rs new file mode 100644 --- /dev/null +++ b/src/tests/intersection.rs @@ -0,0 +1,79 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[(TestFlags::empty(), 0), (TestFlags::all(), 0)], + TestFlags::intersection, + ); + + case( + TestFlags::all(), + &[ + (TestFlags::all(), 1 | 1 << 1 | 1 << 2), + (TestFlags::A, 1), + (TestFlags::from_bits_retain(1 << 3), 0), + ], + TestFlags::intersection, + ); + + case( + TestFlags::from_bits_retain(1 << 3), + &[(TestFlags::from_bits_retain(1 << 3), 1 << 3)], + TestFlags::intersection, + ); + + case( + TestOverlapping::AB, + &[(TestOverlapping::BC, 1 << 1)], + TestOverlapping::intersection, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + std::ops::BitAnd<Output = T> + std::ops::BitAndAssign + Copy>( + value: T, + inputs: &[(T, T::Bits)], + mut inherent: impl FnMut(T, T) -> T, +) where + T::Bits: std::fmt::Debug + PartialEq + Copy, +{ + for (input, expected) in inputs { + assert_eq!( + *expected, + inherent(value, *input).bits(), + "{:?}.intersection({:?})", + value, + input + ); + assert_eq!( + *expected, + Flags::intersection(value, *input).bits(), + "Flags::intersection({:?}, {:?})", + value, + input + ); + assert_eq!( + *expected, + (value & *input).bits(), + "{:?} & {:?}", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + value &= *input; + value + } + .bits(), + "{:?} &= {:?}", + value, + input, + ); + } +} diff --git /dev/null b/src/tests/intersects.rs new file mode 100644 --- /dev/null +++ b/src/tests/intersects.rs @@ -0,0 +1,91 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[ + (TestFlags::empty(), false), + (TestFlags::A, false), + (TestFlags::B, false), + (TestFlags::C, false), + (TestFlags::from_bits_retain(1 << 3), false), + ], + TestFlags::intersects, + ); + + case( + TestFlags::A, + &[ + (TestFlags::empty(), false), + (TestFlags::A, true), + (TestFlags::B, false), + (TestFlags::C, false), + (TestFlags::ABC, true), + (TestFlags::from_bits_retain(1 << 3), false), + (TestFlags::from_bits_retain(1 | (1 << 3)), true), + ], + TestFlags::intersects, + ); + + case( + TestFlags::ABC, + &[ + (TestFlags::empty(), false), + (TestFlags::A, true), + (TestFlags::B, true), + (TestFlags::C, true), + (TestFlags::ABC, true), + (TestFlags::from_bits_retain(1 << 3), false), + ], + TestFlags::intersects, + ); + + case( + TestFlags::from_bits_retain(1 << 3), + &[ + (TestFlags::empty(), false), + (TestFlags::A, false), + (TestFlags::B, false), + (TestFlags::C, false), + (TestFlags::from_bits_retain(1 << 3), true), + ], + TestFlags::intersects, + ); + + case( + TestOverlapping::AB, + &[ + (TestOverlapping::AB, true), + (TestOverlapping::BC, true), + (TestOverlapping::from_bits_retain(1 << 1), true), + ], + TestOverlapping::intersects, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + Copy>( + value: T, + inputs: &[(T, bool)], + mut inherent: impl FnMut(&T, T) -> bool, +) { + for (input, expected) in inputs { + assert_eq!( + *expected, + inherent(&value, *input), + "{:?}.intersects({:?})", + value, + input + ); + assert_eq!( + *expected, + Flags::intersects(&value, *input), + "Flags::intersects({:?}, {:?})", + value, + input + ); + } +} diff --git /dev/null b/src/tests/is_all.rs new file mode 100644 --- /dev/null +++ b/src/tests/is_all.rs @@ -0,0 +1,32 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(false, TestFlags::empty(), TestFlags::is_all); + case(false, TestFlags::A, TestFlags::is_all); + + case(true, TestFlags::ABC, TestFlags::is_all); + + case( + true, + TestFlags::ABC | TestFlags::from_bits_retain(1 << 3), + TestFlags::is_all, + ); + + case(true, TestZero::empty(), TestZero::is_all); + + case(true, TestEmpty::empty(), TestEmpty::is_all); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug>(expected: bool, value: T, inherent: impl FnOnce(&T) -> bool) { + assert_eq!(expected, inherent(&value), "{:?}.is_all()", value); + assert_eq!( + expected, + Flags::is_all(&value), + "Flags::is_all({:?})", + value + ); +} diff --git /dev/null b/src/tests/is_empty.rs new file mode 100644 --- /dev/null +++ b/src/tests/is_empty.rs @@ -0,0 +1,31 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case(true, TestFlags::empty(), TestFlags::is_empty); + + case(false, TestFlags::A, TestFlags::is_empty); + case(false, TestFlags::ABC, TestFlags::is_empty); + case( + false, + TestFlags::from_bits_retain(1 << 3), + TestFlags::is_empty, + ); + + case(true, TestZero::empty(), TestZero::is_empty); + + case(true, TestEmpty::empty(), TestEmpty::is_empty); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug>(expected: bool, value: T, inherent: impl FnOnce(&T) -> bool) { + assert_eq!(expected, inherent(&value), "{:?}.is_empty()", value); + assert_eq!( + expected, + Flags::is_empty(&value), + "Flags::is_empty({:?})", + value + ); +} diff --git /dev/null b/src/tests/iter.rs new file mode 100644 --- /dev/null +++ b/src/tests/iter.rs @@ -0,0 +1,186 @@ +use super::*; + +use crate::Flags; + +#[test] +fn roundtrip() { + for a in 0u8..=255 { + for b in 0u8..=255 { + let f = TestFlags::from_bits_retain(a | b); + + assert_eq!(f, f.iter().collect::<TestFlags>()); + assert_eq!( + TestFlags::from_bits_truncate(f.bits()), + f.iter_names().map(|(_, f)| f).collect::<TestFlags>() + ); + } + } +} + +mod collect { + use super::*; + + #[test] + fn cases() { + assert_eq!(0, [].into_iter().collect::<TestFlags>().bits()); + + assert_eq!(1, [TestFlags::A,].into_iter().collect::<TestFlags>().bits()); + + assert_eq!( + 1 | 1 << 1 | 1 << 2, + [TestFlags::A, TestFlags::B | TestFlags::C,] + .into_iter() + .collect::<TestFlags>() + .bits() + ); + + assert_eq!( + 1 | 1 << 3, + [ + TestFlags::from_bits_retain(1 << 3), + TestFlags::empty(), + TestFlags::A, + ] + .into_iter() + .collect::<TestFlags>() + .bits() + ); + } +} + +mod iter { + use super::*; + + #[test] + fn cases() { + case(&[], TestFlags::empty(), TestFlags::iter); + + case(&[1], TestFlags::A, TestFlags::iter); + case(&[1, 1 << 1], TestFlags::A | TestFlags::B, TestFlags::iter); + case( + &[1, 1 << 1, 1 << 3], + TestFlags::A | TestFlags::B | TestFlags::from_bits_retain(1 << 3), + TestFlags::iter, + ); + + case(&[1, 1 << 1, 1 << 2], TestFlags::ABC, TestFlags::iter); + case( + &[1, 1 << 1, 1 << 2, 1 << 3], + TestFlags::ABC | TestFlags::from_bits_retain(1 << 3), + TestFlags::iter, + ); + + case( + &[1 | 1 << 1 | 1 << 2], + TestFlagsInvert::ABC, + TestFlagsInvert::iter, + ); + + case(&[], TestZero::ZERO, TestZero::iter); + } + + #[track_caller] + fn case<T: Flags + std::fmt::Debug + IntoIterator<Item = T> + Copy>( + expected: &[T::Bits], + value: T, + inherent: impl FnOnce(&T) -> crate::iter::Iter<T>, + ) where + T::Bits: std::fmt::Debug + PartialEq, + { + assert_eq!( + expected, + inherent(&value).map(|f| f.bits()).collect::<Vec<_>>(), + "{:?}.iter()", + value + ); + assert_eq!( + expected, + Flags::iter(&value).map(|f| f.bits()).collect::<Vec<_>>(), + "Flags::iter({:?})", + value + ); + assert_eq!( + expected, + value.into_iter().map(|f| f.bits()).collect::<Vec<_>>(), + "{:?}.into_iter()", + value + ); + } +} + +mod iter_names { + use super::*; + + #[test] + fn cases() { + case(&[], TestFlags::empty(), TestFlags::iter_names); + + case(&[("A", 1)], TestFlags::A, TestFlags::iter_names); + case( + &[("A", 1), ("B", 1 << 1)], + TestFlags::A | TestFlags::B, + TestFlags::iter_names, + ); + case( + &[("A", 1), ("B", 1 << 1)], + TestFlags::A | TestFlags::B | TestFlags::from_bits_retain(1 << 3), + TestFlags::iter_names, + ); + + case( + &[("A", 1), ("B", 1 << 1), ("C", 1 << 2)], + TestFlags::ABC, + TestFlags::iter_names, + ); + case( + &[("A", 1), ("B", 1 << 1), ("C", 1 << 2)], + TestFlags::ABC | TestFlags::from_bits_retain(1 << 3), + TestFlags::iter_names, + ); + + case( + &[("ABC", 1 | 1 << 1 | 1 << 2)], + TestFlagsInvert::ABC, + TestFlagsInvert::iter_names, + ); + + case(&[], TestZero::ZERO, TestZero::iter_names); + + case( + &[("A", 1)], + TestOverlappingFull::A, + TestOverlappingFull::iter_names, + ); + case( + &[("A", 1), ("D", 1 << 1)], + TestOverlappingFull::A | TestOverlappingFull::D, + TestOverlappingFull::iter_names, + ); + } + + #[track_caller] + fn case<T: Flags + std::fmt::Debug>( + expected: &[(&'static str, T::Bits)], + value: T, + inherent: impl FnOnce(&T) -> crate::iter::IterNames<T>, + ) where + T::Bits: std::fmt::Debug + PartialEq, + { + assert_eq!( + expected, + inherent(&value) + .map(|(n, f)| (n, f.bits())) + .collect::<Vec<_>>(), + "{:?}.iter_names()", + value + ); + assert_eq!( + expected, + Flags::iter_names(&value) + .map(|(n, f)| (n, f.bits())) + .collect::<Vec<_>>(), + "Flags::iter_names({:?})", + value + ); + } +} diff --git /dev/null b/src/tests/parser.rs new file mode 100644 --- /dev/null +++ b/src/tests/parser.rs @@ -0,0 +1,115 @@ +use super::*; + +use crate::{ + parser::{from_str, to_writer}, + Flags, +}; + +#[test] +fn roundtrip() { + let mut s = String::new(); + + for a in 0u8..=255 { + for b in 0u8..=255 { + let f = TestFlags::from_bits_retain(a | b); + + s.clear(); + to_writer(&f, &mut s).unwrap(); + + assert_eq!(f, from_str::<TestFlags>(&s).unwrap()); + } + } +} + +mod from_str { + use super::*; + + #[test] + fn valid() { + assert_eq!(0, from_str::<TestFlags>("").unwrap().bits()); + + assert_eq!(1, from_str::<TestFlags>("A").unwrap().bits()); + assert_eq!(1, from_str::<TestFlags>(" A ").unwrap().bits()); + assert_eq!( + 1 | 1 << 1 | 1 << 2, + from_str::<TestFlags>("A | B | C").unwrap().bits() + ); + assert_eq!( + 1 | 1 << 1 | 1 << 2, + from_str::<TestFlags>("A\n|\tB\r\n| C ").unwrap().bits() + ); + assert_eq!( + 1 | 1 << 1 | 1 << 2, + from_str::<TestFlags>("A|B|C").unwrap().bits() + ); + + assert_eq!(1 << 3, from_str::<TestFlags>("0x8").unwrap().bits()); + assert_eq!(1 | 1 << 3, from_str::<TestFlags>("A | 0x8").unwrap().bits()); + assert_eq!( + 1 | 1 << 1 | 1 << 3, + from_str::<TestFlags>("0x1 | 0x8 | B").unwrap().bits() + ); + + assert_eq!( + 1 | 1 << 1, + from_str::<TestUnicode>("一 | 二").unwrap().bits() + ); + } + + #[test] + fn invalid() { + assert!(from_str::<TestFlags>("a") + .unwrap_err() + .to_string() + .starts_with("unrecognized named flag")); + assert!(from_str::<TestFlags>("A & B") + .unwrap_err() + .to_string() + .starts_with("unrecognized named flag")); + + assert!(from_str::<TestFlags>("0xg") + .unwrap_err() + .to_string() + .starts_with("invalid hex flag")); + assert!(from_str::<TestFlags>("0xffffffffffff") + .unwrap_err() + .to_string() + .starts_with("invalid hex flag")); + } +} + +mod to_writer { + use super::*; + + #[test] + fn cases() { + assert_eq!("", write(TestFlags::empty())); + assert_eq!("A", write(TestFlags::A)); + assert_eq!("A | B | C", write(TestFlags::all())); + assert_eq!("0x8", write(TestFlags::from_bits_retain(1 << 3))); + assert_eq!( + "A | 0x8", + write(TestFlags::A | TestFlags::from_bits_retain(1 << 3)) + ); + + assert_eq!("", write(TestZero::ZERO)); + + assert_eq!("ABC", write(TestFlagsInvert::all())); + + assert_eq!("A", write(TestOverlappingFull::C)); + assert_eq!( + "A | D", + write(TestOverlappingFull::C | TestOverlappingFull::D) + ); + } + + fn write<F: Flags>(value: F) -> String + where + F::Bits: crate::parser::WriteHex, + { + let mut s = String::new(); + + to_writer(&value, &mut s).unwrap(); + s + } +} diff --git /dev/null b/src/tests/remove.rs new file mode 100644 --- /dev/null +++ b/src/tests/remove.rs @@ -0,0 +1,100 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[ + (TestFlags::A, 0), + (TestFlags::empty(), 0), + (TestFlags::from_bits_retain(1 << 3), 0), + ], + TestFlags::remove, + TestFlags::set, + ); + + case( + TestFlags::A, + &[ + (TestFlags::A, 0), + (TestFlags::empty(), 1), + (TestFlags::B, 1), + ], + TestFlags::remove, + TestFlags::set, + ); + + case( + TestFlags::ABC, + &[ + (TestFlags::A, 1 << 1 | 1 << 2), + (TestFlags::A | TestFlags::C, 1 << 1), + ], + TestFlags::remove, + TestFlags::set, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + Copy>( + value: T, + inputs: &[(T, T::Bits)], + mut inherent_remove: impl FnMut(&mut T, T), + mut inherent_set: impl FnMut(&mut T, T, bool), +) where + T::Bits: std::fmt::Debug + PartialEq + Copy, +{ + for (input, expected) in inputs { + assert_eq!( + *expected, + { + let mut value = value; + inherent_remove(&mut value, *input); + value + } + .bits(), + "{:?}.remove({:?})", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + Flags::remove(&mut value, *input); + value + } + .bits(), + "Flags::remove({:?}, {:?})", + value, + input + ); + + assert_eq!( + *expected, + { + let mut value = value; + inherent_set(&mut value, *input, false); + value + } + .bits(), + "{:?}.set({:?}, false)", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + Flags::set(&mut value, *input, false); + value + } + .bits(), + "Flags::set({:?}, {:?}, false)", + value, + input + ); + } +} diff --git /dev/null b/src/tests/symmetric_difference.rs new file mode 100644 --- /dev/null +++ b/src/tests/symmetric_difference.rs @@ -0,0 +1,110 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[ + (TestFlags::empty(), 0), + (TestFlags::all(), 1 | 1 << 1 | 1 << 2), + (TestFlags::from_bits_retain(1 << 3), 1 << 3), + ], + TestFlags::symmetric_difference, + TestFlags::toggle, + ); + + case( + TestFlags::A, + &[ + (TestFlags::empty(), 1), + (TestFlags::A, 0), + (TestFlags::all(), 1 << 1 | 1 << 2), + ], + TestFlags::symmetric_difference, + TestFlags::toggle, + ); + + case( + TestFlags::A | TestFlags::B | TestFlags::from_bits_retain(1 << 3), + &[ + (TestFlags::ABC, 1 << 2 | 1 << 3), + (TestFlags::from_bits_retain(1 << 3), 1 | 1 << 1), + ], + TestFlags::symmetric_difference, + TestFlags::toggle, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + std::ops::BitXor<Output = T> + std::ops::BitXorAssign + Copy>( + value: T, + inputs: &[(T, T::Bits)], + mut inherent_sym_diff: impl FnMut(T, T) -> T, + mut inherent_toggle: impl FnMut(&mut T, T), +) where + T::Bits: std::fmt::Debug + PartialEq + Copy, +{ + for (input, expected) in inputs { + assert_eq!( + *expected, + inherent_sym_diff(value, *input).bits(), + "{:?}.symmetric_difference({:?})", + value, + input + ); + assert_eq!( + *expected, + Flags::symmetric_difference(value, *input).bits(), + "Flags::symmetric_difference({:?}, {:?})", + value, + input + ); + assert_eq!( + *expected, + (value ^ *input).bits(), + "{:?} ^ {:?}", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + value ^= *input; + value + } + .bits(), + "{:?} ^= {:?}", + value, + input, + ); + + assert_eq!( + *expected, + { + let mut value = value; + inherent_toggle(&mut value, *input); + value + } + .bits(), + "{:?}.toggle({:?})", + value, + input, + ); + + assert_eq!( + *expected, + { + let mut value = value; + Flags::toggle(&mut value, *input); + value + } + .bits(), + "{:?}.toggle({:?})", + value, + input, + ); + } +} diff --git /dev/null b/src/tests/union.rs new file mode 100644 --- /dev/null +++ b/src/tests/union.rs @@ -0,0 +1,71 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[ + (TestFlags::A, 1), + (TestFlags::all(), 1 | 1 << 1 | 1 << 2), + (TestFlags::empty(), 0), + (TestFlags::from_bits_retain(1 << 3), 1 << 3), + ], + TestFlags::union, + ); + + case( + TestFlags::A | TestFlags::C, + &[ + (TestFlags::A | TestFlags::B, 1 | 1 << 1 | 1 << 2), + (TestFlags::A, 1 | 1 << 2), + ], + TestFlags::union, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + std::ops::BitOr<Output = T> + std::ops::BitOrAssign + Copy>( + value: T, + inputs: &[(T, T::Bits)], + mut inherent: impl FnMut(T, T) -> T, +) where + T::Bits: std::fmt::Debug + PartialEq + Copy, +{ + for (input, expected) in inputs { + assert_eq!( + *expected, + inherent(value, *input).bits(), + "{:?}.union({:?})", + value, + input + ); + assert_eq!( + *expected, + Flags::union(value, *input).bits(), + "Flags::union({:?}, {:?})", + value, + input + ); + assert_eq!( + *expected, + (value | *input).bits(), + "{:?} | {:?}", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + value |= *input; + value + } + .bits(), + "{:?} |= {:?}", + value, + input, + ); + } +} diff --git a/tests/basic.rs b/tests/basic.rs --- a/tests/basic.rs +++ b/tests/basic.rs @@ -3,19 +3,77 @@ use bitflags::bitflags; bitflags! { - /// baz - #[derive(Debug, PartialEq, Eq)] - struct Flags: u32 { + pub struct I8: i8 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct I16: i16 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct I32: i32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct I64: i64 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct I128: i128 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct Isize: isize { const A = 0b00000001; - #[doc = "bar"] const B = 0b00000010; const C = 0b00000100; - #[doc = "foo"] - const ABC = Flags::A.bits() | Flags::B.bits() | Flags::C.bits(); } } -#[test] -fn basic() { - assert_eq!(Flags::ABC, Flags::A | Flags::B | Flags::C); +bitflags! { + pub struct U8: u8 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct U16: u16 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct U32: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct U64: u64 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct U128: u128 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } + + pub struct Usize: usize { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } } diff --git a/tests/compile-fail/bitflags_custom_bits.stderr b/tests/compile-fail/bitflags_custom_bits.stderr --- a/tests/compile-fail/bitflags_custom_bits.stderr +++ b/tests/compile-fail/bitflags_custom_bits.stderr @@ -34,443 +34,3 @@ error[E0308]: mismatched types found type parameter `W` note: method defined here --> $RUST/core/src/fmt/mod.rs - -error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt == _` - | - = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` -note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt == _` - | - = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` -note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt & MyInt` - | - = help: the trait `~const BitAnd` is not implemented for `MyInt` -note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt == _` - | - = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` -note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitOr` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt | MyInt` - | - = help: the trait `~const BitOr` is not implemented for `MyInt` -note: the trait `BitOr` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt == _` - | - = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` -note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitOr` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt | MyInt` - | - = help: the trait `~const BitOr` is not implemented for `MyInt` -note: the trait `BitOr` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt == _` - | - = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` -note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt & MyInt` - | - = help: the trait `~const BitAnd` is not implemented for `MyInt` -note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt & MyInt` - | - = help: the trait `~const BitAnd` is not implemented for `MyInt` -note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt == _` - | - = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` -note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt & MyInt` - | - = help: the trait `~const BitAnd` is not implemented for `MyInt` -note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitOr` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt | MyInt` - | - = help: the trait `~const BitOr` is not implemented for `MyInt` -note: the trait `BitOr` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt & MyInt` - | - = help: the trait `~const BitAnd` is not implemented for `MyInt` -note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: Not` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ the trait `~const Not` is not implemented for `MyInt` - | -note: the trait `Not` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: BitXor` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ no implementation for `MyInt ^ MyInt` - | - = help: the trait `~const BitXor` is not implemented for `MyInt` -note: the trait `BitXor` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `MyInt: Not` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ the trait `~const Not` is not implemented for `MyInt` - | -note: the trait `Not` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:132:1 - | -132 | / bitflags! { -133 | | struct Flags128: MyInt { -134 | | const A = MyInt(0b0000_0001u8); -135 | | const B = MyInt(0b0000_0010u8); -136 | | const C = MyInt(0b0000_0100u8); -137 | | } -138 | | } - | |_^ - = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info)
The value `0` isn’t recommended as a flag value because it behaves surprisingly with formatting, and with `is_any`. If you do want to define a zero-valued flag I’d suggest defining the constant outside of the `bitflags!` macro.
09f71f492d0f76d63cd286c3869c70676297e204
[ "364" ]
2023-06-26T07:21:41Z
366
bitflags__bitflags-366
diff --git a/examples/custom_bits_type.rs b/examples/custom_bits_type.rs --- a/examples/custom_bits_type.rs +++ b/examples/custom_bits_type.rs @@ -1,6 +1,6 @@ use std::ops::{BitAnd, BitOr, BitXor, Not}; -use bitflags::{Flags, Flag, Bits}; +use bitflags::{Bits, Flag, Flags}; // Define a custom container that can be used in flags types // Note custom bits types can't be used in `bitflags!` diff --git a/examples/custom_bits_type.rs b/examples/custom_bits_type.rs --- a/examples/custom_bits_type.rs +++ b/examples/custom_bits_type.rs @@ -25,7 +25,11 @@ impl BitAnd for CustomBits { type Output = Self; fn bitand(self, other: Self) -> Self { - CustomBits([self.0[0] & other.0[0], self.0[1] & other.0[1], self.0[2] & other.0[2]]) + CustomBits([ + self.0[0] & other.0[0], + self.0[1] & other.0[1], + self.0[2] & other.0[2], + ]) } } diff --git a/examples/custom_bits_type.rs b/examples/custom_bits_type.rs --- a/examples/custom_bits_type.rs +++ b/examples/custom_bits_type.rs @@ -33,7 +37,11 @@ impl BitOr for CustomBits { type Output = Self; fn bitor(self, other: Self) -> Self { - CustomBits([self.0[0] | other.0[0], self.0[1] | other.0[1], self.0[2] | other.0[2]]) + CustomBits([ + self.0[0] | other.0[0], + self.0[1] | other.0[1], + self.0[2] | other.0[2], + ]) } } diff --git a/examples/custom_bits_type.rs b/examples/custom_bits_type.rs --- a/examples/custom_bits_type.rs +++ b/examples/custom_bits_type.rs @@ -41,7 +49,11 @@ impl BitXor for CustomBits { type Output = Self; fn bitxor(self, other: Self) -> Self { - CustomBits([self.0[0] & other.0[0], self.0[1] & other.0[1], self.0[2] & other.0[2]]) + CustomBits([ + self.0[0] & other.0[0], + self.0[1] & other.0[1], + self.0[2] & other.0[2], + ]) } } diff --git a/examples/macro_free.rs b/examples/macro_free.rs --- a/examples/macro_free.rs +++ b/examples/macro_free.rs @@ -4,7 +4,7 @@ use std::{fmt, str}; -use bitflags::{Flags, Flag}; +use bitflags::{Flag, Flags}; // First: Define your flags type. It just needs to be `Sized + 'static`. pub struct ManualFlags(u32); diff --git a/examples/macro_free.rs b/examples/macro_free.rs --- a/examples/macro_free.rs +++ b/examples/macro_free.rs @@ -54,5 +54,8 @@ impl fmt::Display for ManualFlags { } fn main() { - println!("{}", ManualFlags::A.union(ManualFlags::B).union(ManualFlags::C)); + println!( + "{}", + ManualFlags::A.union(ManualFlags::B).union(ManualFlags::C) + ); } diff --git a/src/example_generated.rs b/src/example_generated.rs --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -38,6 +38,10 @@ __impl_public_bitflags_forward! { Flags: u32, Field0 } +__impl_public_bitflags_ops! { + Flags +} + __impl_public_bitflags_iter! { Flags: u32, Flags } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -153,9 +153,7 @@ macro_rules! __impl_external_bitflags_serde { fn deserialize<D: $crate::__private::serde::Deserializer<'de>>( deserializer: D, ) -> $crate::__private::core::result::Result<Self, D::Error> { - let flags: $PublicBitFlags = $crate::serde::deserialize( - deserializer, - )?; + let flags: $PublicBitFlags = $crate::serde::deserialize(deserializer)?; Ok(flags.0) } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -235,20 +233,16 @@ macro_rules! __impl_external_bitflags_bytemuck { ) => { // SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T, // and $T implements Pod - unsafe impl $crate::__private::bytemuck::Pod for $InternalBitFlags - where - $T: $crate::__private::bytemuck::Pod, + unsafe impl $crate::__private::bytemuck::Pod for $InternalBitFlags where + $T: $crate::__private::bytemuck::Pod { - } // SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T, // and $T implements Zeroable - unsafe impl $crate::__private::bytemuck::Zeroable for $InternalBitFlags - where - $T: $crate::__private::bytemuck::Zeroable, + unsafe impl $crate::__private::bytemuck::Zeroable for $InternalBitFlags where + $T: $crate::__private::bytemuck::Zeroable { - } }; } diff --git a/src/external/arbitrary.rs b/src/external/arbitrary.rs --- a/src/external/arbitrary.rs +++ b/src/external/arbitrary.rs @@ -3,11 +3,9 @@ use crate::Flags; /// Get a random known flags value. -pub fn arbitrary<'a, B: Flags>( - u: &mut arbitrary::Unstructured<'a>, -) -> arbitrary::Result<B> +pub fn arbitrary<'a, B: Flags>(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<B> where - B::Bits: arbitrary::Arbitrary<'a> + B::Bits: arbitrary::Arbitrary<'a>, { B::from_bits(u.arbitrary()?).ok_or_else(|| arbitrary::Error::IncorrectFormat) } diff --git a/src/external/serde.rs b/src/external/serde.rs --- a/src/external/serde.rs +++ b/src/external/serde.rs @@ -1,17 +1,17 @@ //! Specialized serialization for flags types using `serde`. +use crate::{ + parser::{self, ParseHex, WriteHex}, + Flags, +}; use core::{fmt, str}; -use crate::{Flags, parser::{self, ParseHex, WriteHex}}; use serde::{ de::{Error, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }; /// Serialize a set of flags as a human-readable string or their underlying bits. -pub fn serialize<B: Flags, S: Serializer>( - flags: &B, - serializer: S, -) -> Result<S::Ok, S::Error> +pub fn serialize<B: Flags, S: Serializer>(flags: &B, serializer: S) -> Result<S::Ok, S::Error> where B::Bits: WriteHex + Serialize, { diff --git a/src/external/serde.rs b/src/external/serde.rs --- a/src/external/serde.rs +++ b/src/external/serde.rs @@ -26,13 +26,7 @@ where } /// Deserialize a set of flags from a human-readable string or their underlying bits. -pub fn deserialize< - 'de, - B: Flags, - D: Deserializer<'de>, ->( - deserializer: D, -) -> Result<B, D::Error> +pub fn deserialize<'de, B: Flags, D: Deserializer<'de>>(deserializer: D) -> Result<B, D::Error> where B::Bits: ParseHex + Deserialize<'de>, { diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -56,7 +56,7 @@ macro_rules! __impl_internal_bitflags { if self.is_empty() { // If no flags are set then write an empty hex flag to avoid // writing an empty string. In some contexts, like serialization, - // an empty string is preferrable, but it may be unexpected in + // an empty string is preferable, but it may be unexpected in // others for a format not to produce any output. // // We can remove this `0x0` and remain compatible with `FromStr`, diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -106,6 +106,10 @@ macro_rules! __impl_internal_bitflags { } } + __impl_public_bitflags_ops! { + $InternalBitFlags + } + __impl_public_bitflags_iter! { $InternalBitFlags: $T, $PublicBitFlags } diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -1,6 +1,6 @@ //! Iterating over set flag values. -use crate::{Flags, Flag}; +use crate::{Flag, Flags}; /// An iterator over a set of flags. /// diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -23,9 +23,9 @@ impl<B: Flags> Iter<B> { impl<B: 'static> Iter<B> { #[doc(hidden)] - pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, state: B) -> Self { + pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, remaining: B) -> Self { Iter { - inner: IterNames::__private_const_new(flags, source, state), + inner: IterNames::__private_const_new(flags, source, remaining), done: false, } } diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -33,18 +33,18 @@ impl<B: 'static> Iter<B> { impl<B: Flags> Iterator for Iter<B> { type Item = B; - + fn next(&mut self) -> Option<Self::Item> { match self.inner.next() { Some((_, flag)) => Some(flag), None if !self.done => { self.done = true; - + // After iterating through valid names, if there are any bits left over // then return one final value that includes them. This makes `into_iter` // and `from_iter` roundtrip if !self.inner.remaining().is_empty() { - Some(B::from_bits_retain(self.inner.state.bits())) + Some(B::from_bits_retain(self.inner.remaining.bits())) } else { None } diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -61,7 +61,7 @@ pub struct IterNames<B: 'static> { flags: &'static [Flag<B>], idx: usize, source: B, - state: B, + remaining: B, } impl<B: Flags> IterNames<B> { diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -70,7 +70,7 @@ impl<B: Flags> IterNames<B> { IterNames { flags: B::FLAGS, idx: 0, - state: B::from_bits_retain(flags.bits()), + remaining: B::from_bits_retain(flags.bits()), source: B::from_bits_retain(flags.bits()), } } diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -78,11 +78,11 @@ impl<B: Flags> IterNames<B> { impl<B: 'static> IterNames<B> { #[doc(hidden)] - pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, state: B) -> Self { + pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, remaining: B) -> Self { IterNames { flags, idx: 0, - state, + remaining, source, } } diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -93,17 +93,17 @@ impl<B: 'static> IterNames<B> { /// check whether or not there are any bits that didn't correspond /// to a valid flag remaining. pub fn remaining(&self) -> &B { - &self.state + &self.remaining } } impl<B: Flags> Iterator for IterNames<B> { type Item = (&'static str, B); - + fn next(&mut self) -> Option<Self::Item> { while let Some(flag) = self.flags.get(self.idx) { // Short-circuit if our state is empty - if self.state.is_empty() { + if self.remaining.is_empty() { return None; } diff --git a/src/iter.rs b/src/iter.rs --- a/src/iter.rs +++ b/src/iter.rs @@ -111,23 +111,23 @@ impl<B: Flags> Iterator for IterNames<B> { let bits = flag.value().bits(); - // NOTE: We check whether the flag exists in self, but remove it from - // a different value. This ensure that overlapping flags are handled - // properly. Take the following example: + // If the flag is set in the original source _and_ it has bits that haven't + // been covered by a previous flag yet then yield it. These conditions cover + // two cases for multi-bit flags: // - // const A: 0b00000001; - // const B: 0b00000101; - // - // Given the bits 0b00000101, both A and B are set. But if we removed A - // as we encountered it we'd be left with 0b00000100, which doesn't - // correspond to a valid flag on its own. - if self.source.contains(B::from_bits_retain(bits)) { - self.state.remove(B::from_bits_retain(bits)); + // 1. When flags partially overlap, such as `0b00000001` and `0b00000101`, we'll + // yield both flags. + // 2. When flags fully overlap, such as in convenience flags that are a shorthand for others, + // we won't yield both flags. + if self.source.contains(B::from_bits_retain(bits)) + && self.remaining.intersects(B::from_bits_retain(bits)) + { + self.remaining.remove(B::from_bits_retain(bits)); return Some((flag.name(), B::from_bits_retain(bits))); } } - + None } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -623,6 +624,10 @@ macro_rules! bitflags { $BitFlags: $T, InternalBitFlags } + __impl_public_bitflags_ops! { + $BitFlags + } + __impl_public_bitflags_iter! { $BitFlags: $T, $BitFlags } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -671,6 +676,10 @@ macro_rules! bitflags { } } + __impl_public_bitflags_ops! { + $BitFlags + } + __impl_public_bitflags_iter! { $BitFlags: $T, $BitFlags } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -714,11 +723,7 @@ macro_rules! __impl_bitflags { fn complement($complement0:ident) $complement:block } ) => { - #[allow( - dead_code, - deprecated, - unused_attributes - )] + #[allow(dead_code, deprecated, unused_attributes)] impl $PublicBitFlags { /// Returns an empty set of flags. #[inline] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -804,6 +809,8 @@ macro_rules! __impl_bitflags { } /// Inserts the specified flags in-place. + /// + /// This method is equivalent to `union`. #[inline] pub fn insert(&mut self, other: Self) { let $insert0 = self; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -812,6 +819,8 @@ macro_rules! __impl_bitflags { } /// Removes the specified flags in-place. + /// + /// This method is equivalent to `difference`. #[inline] pub fn remove(&mut self, other: Self) { let $remove0 = self; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -820,6 +829,8 @@ macro_rules! __impl_bitflags { } /// Toggles the specified flags in-place. + /// + /// This method is equivalent to `symmetric_difference`. #[inline] pub fn toggle(&mut self, other: Self) { let $toggle0 = self; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -839,13 +850,8 @@ macro_rules! __impl_bitflags { /// 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 + /// Calculating `self` bitwise and (`&`) other, including + /// any bits that don't correspond to a defined flag. #[inline] #[must_use] pub const fn intersection(self, other: Self) -> Self { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -856,15 +862,8 @@ macro_rules! __impl_bitflags { /// 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 + /// Calculates `self` bitwise or (`|`) `other`, including + /// any bits that don't correspond to a defined flag. #[inline] #[must_use] pub const fn union(self, other: Self) -> Self { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -875,16 +874,13 @@ macro_rules! __impl_bitflags { /// 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`. + /// Calculates `self` bitwise and (`&!`) the bitwise negation of `other`, + /// including any bits that don't correspond to a defined flag. /// - /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html + /// 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)`. #[inline] #[must_use] pub const fn difference(self, other: Self) -> Self { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -893,19 +889,11 @@ macro_rules! __impl_bitflags { $difference } - /// Returns the [symmetric difference][sym-diff] between the flags + /// Returns the symmetric difference 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 + /// Calculates `self` bitwise exclusive or (`^`) `other`, + /// including any bits that don't correspond to a defined flag. #[inline] #[must_use] pub const fn symmetric_difference(self, other: Self) -> Self { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -916,17 +904,8 @@ macro_rules! __impl_bitflags { /// 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 + /// Calculates the bitwise negation (`!`) of `self`, + /// **unsetting** any bits that don't correspond to a defined flag. #[inline] #[must_use] pub const fn complement(self) -> Self { diff --git a/src/parser.rs b/src/parser.rs --- a/src/parser.rs +++ b/src/parser.rs @@ -30,7 +30,7 @@ use core::fmt::{self, Write}; -use crate::{Flags, Bits}; +use crate::{Bits, Flags}; /// Write a set of flags to a writer. /// diff --git a/src/parser.rs b/src/parser.rs --- a/src/parser.rs +++ b/src/parser.rs @@ -48,7 +48,7 @@ where // followed by a hex number of any remaining bits that are set // but don't correspond to any flags. - // Iterate over the valid flags + // Iterate over known flag values let mut first = true; let mut iter = flags.iter_names(); for (name, _) in &mut iter { diff --git a/src/parser.rs b/src/parser.rs --- a/src/parser.rs +++ b/src/parser.rs @@ -110,7 +110,8 @@ where // If the flag starts with `0x` then it's a hex number // Parse it directly to the underlying bits type let parsed_flag = if let Some(flag) = flag.strip_prefix("0x") { - let bits = <B::Bits>::parse_hex(flag).map_err(|_| ParseError::invalid_hex_flag(flag))?; + let bits = + <B::Bits>::parse_hex(flag).map_err(|_| ParseError::invalid_hex_flag(flag))?; B::from_bits_retain(bits) } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -117,8 +117,6 @@ macro_rules! __impl_public_bitflags_forward { } } } - - __impl_public_bitflags_ops!($PublicBitFlags); }; } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -203,31 +201,33 @@ macro_rules! __impl_public_bitflags { } fn is_empty(f) { - f.0 == Self::empty().0 + f.bits() == <$T as $crate::Bits>::EMPTY } fn is_all(f) { - Self::all().0 | f.0 == f.0 + // 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() | f.bits() == f.bits() } fn intersects(f, other) { - !(Self(f.0 & other.0)).is_empty() + f.bits() & other.bits() != <$T as $crate::Bits>::EMPTY } fn contains(f, other) { - (f.0 & other.0) == other.0 + f.bits() & other.bits() == other.bits() } fn insert(f, other) { - f.0 = f.0 | other.0; + *f = Self::from_bits_retain(f.bits() | other.bits()); } fn remove(f, other) { - f.0 = f.0 & !other.0; + *f = Self::from_bits_retain(f.bits() & !other.bits()); } fn toggle(f, other) { - f.0 = f.0 ^ other.0; + *f = Self::from_bits_retain(f.bits() ^ other.bits()); } fn set(f, other, value) { diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -239,28 +239,26 @@ macro_rules! __impl_public_bitflags { } fn intersection(f, other) { - Self(f.0 & other.0) + Self::from_bits_retain(f.bits() & other.bits()) } fn union(f, other) { - Self(f.0 | other.0) + Self::from_bits_retain(f.bits() | other.bits()) } fn difference(f, other) { - Self(f.0 & !other.0) + Self::from_bits_retain(f.bits() & !other.bits()) } fn symmetric_difference(f, other) { - Self(f.0 ^ other.0) + Self::from_bits_retain(f.bits() ^ other.bits()) } fn complement(f) { - Self::from_bits_truncate(!f.0) + Self::from_bits_truncate(!f.bits()) } } } - - __impl_public_bitflags_ops!($BitFlags); }; } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -273,13 +271,21 @@ macro_rules! __impl_public_bitflags_iter { /// Iterate over enabled flag values. #[inline] pub const fn iter(&self) -> $crate::iter::Iter<$PublicBitFlags> { - $crate::iter::Iter::__private_const_new(<$PublicBitFlags as $crate::Flags>::FLAGS, $PublicBitFlags::from_bits_retain(self.bits()), $PublicBitFlags::from_bits_retain(self.bits())) + $crate::iter::Iter::__private_const_new( + <$PublicBitFlags as $crate::Flags>::FLAGS, + $PublicBitFlags::from_bits_retain(self.bits()), + $PublicBitFlags::from_bits_retain(self.bits()), + ) } /// Iterate over enabled flag values with their stringified names. #[inline] pub const fn iter_names(&self) -> $crate::iter::IterNames<$PublicBitFlags> { - $crate::iter::IterNames::__private_const_new(<$PublicBitFlags as $crate::Flags>::FLAGS, $PublicBitFlags::from_bits_retain(self.bits()), $PublicBitFlags::from_bits_retain(self.bits())) + $crate::iter::IterNames::__private_const_new( + <$PublicBitFlags as $crate::Flags>::FLAGS, + $PublicBitFlags::from_bits_retain(self.bits()), + $PublicBitFlags::from_bits_retain(self.bits()), + ) } } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -300,25 +306,37 @@ macro_rules! __impl_public_bitflags_iter { macro_rules! __impl_public_bitflags_ops { ($PublicBitFlags:ident) => { impl $crate::__private::core::fmt::Binary for $PublicBitFlags { - fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + fn fmt( + &self, + f: &mut $crate::__private::core::fmt::Formatter, + ) -> $crate::__private::core::fmt::Result { $crate::__private::core::fmt::Binary::fmt(&self.0, f) } } impl $crate::__private::core::fmt::Octal for $PublicBitFlags { - fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + fn fmt( + &self, + f: &mut $crate::__private::core::fmt::Formatter, + ) -> $crate::__private::core::fmt::Result { $crate::__private::core::fmt::Octal::fmt(&self.0, f) } } impl $crate::__private::core::fmt::LowerHex for $PublicBitFlags { - fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + fn fmt( + &self, + f: &mut $crate::__private::core::fmt::Formatter, + ) -> $crate::__private::core::fmt::Result { $crate::__private::core::fmt::LowerHex::fmt(&self.0, f) } } impl $crate::__private::core::fmt::UpperHex for $PublicBitFlags { - fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + fn fmt( + &self, + f: &mut $crate::__private::core::fmt::Formatter, + ) -> $crate::__private::core::fmt::Result { $crate::__private::core::fmt::UpperHex::fmt(&self.0, f) } } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -337,7 +355,7 @@ macro_rules! __impl_public_bitflags_ops { /// Adds the set of flags. #[inline] fn bitor_assign(&mut self, other: Self) { - self.0 = self.0 | other.0; + *self = Self::from_bits_retain(self.bits()).union(other); } } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -355,7 +373,7 @@ macro_rules! __impl_public_bitflags_ops { /// Toggles the set of flags. #[inline] fn bitxor_assign(&mut self, other: Self) { - self.0 = self.0 ^ other.0 + *self = Self::from_bits_retain(self.bits()).symmetric_difference(other); } } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -373,7 +391,7 @@ macro_rules! __impl_public_bitflags_ops { /// Disables all flags disabled in the set. #[inline] fn bitand_assign(&mut self, other: Self) { - self.0 = self.0 & other.0; + *self = Self::from_bits_retain(self.bits()).intersection(other); } } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -391,7 +409,7 @@ macro_rules! __impl_public_bitflags_ops { /// Disables all flags enabled in the set. #[inline] fn sub_assign(&mut self, other: Self) { - self.0 = self.0 & !other.0; + *self = Self::from_bits_retain(self.bits()).difference(other); } } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -406,7 +424,10 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::iter::Extend<$PublicBitFlags> for $PublicBitFlags { - fn extend<T: $crate::__private::core::iter::IntoIterator<Item=Self>>(&mut self, iterator: T) { + fn extend<T: $crate::__private::core::iter::IntoIterator<Item = Self>>( + &mut self, + iterator: T, + ) { for item in iterator { self.insert(item) } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -414,7 +435,9 @@ macro_rules! __impl_public_bitflags_ops { } impl $crate::__private::core::iter::FromIterator<$PublicBitFlags> for $PublicBitFlags { - fn from_iter<T: $crate::__private::core::iter::IntoIterator<Item=Self>>(iterator: T) -> Self { + fn from_iter<T: $crate::__private::core::iter::IntoIterator<Item = Self>>( + iterator: T, + ) -> Self { use $crate::__private::core::iter::Extend; let mut result = Self::empty(); diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -1,6 +1,12 @@ -use core::{fmt, ops::{BitAnd, BitOr, BitXor, Not}}; +use core::{ + fmt, + ops::{BitAnd, BitOr, BitXor, Not}, +}; -use crate::{parser::{ParseError, ParseHex, WriteHex}, iter}; +use crate::{ + iter, + parser::{ParseError, ParseHex, WriteHex}, +}; /// Metadata for an individual flag. pub struct Flag<B> { diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -97,7 +103,7 @@ pub trait Flags: Sized + 'static { fn from_name(name: &str) -> Option<Self> { for flag in Self::FLAGS { if flag.name() == name { - return Some(Self::from_bits_retain(flag.value().bits())) + return Some(Self::from_bits_retain(flag.value().bits())); } } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -143,6 +149,8 @@ pub trait Flags: Sized + 'static { } /// Inserts the specified flags in-place. + /// + /// This method is equivalent to `union`. fn insert(&mut self, other: Self) where Self: Sized, diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -151,6 +159,8 @@ pub trait Flags: Sized + 'static { } /// Removes the specified flags in-place. + /// + /// This method is equivalent to `difference`. fn remove(&mut self, other: Self) where Self: Sized, diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -159,6 +169,8 @@ pub trait Flags: Sized + 'static { } /// Toggles the specified flags in-place. + /// + /// This method is equivalent to `symmetric_difference`. fn toggle(&mut self, other: Self) where Self: Sized, diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -178,57 +190,32 @@ pub trait Flags: Sized + 'static { } } - /// 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`. + /// Returns the intersection between the flags in `self` and `other`. #[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`. - /// - /// 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). #[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`. - /// - /// 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). #[must_use] fn difference(self, other: Self) -> Self { Self::from_bits_retain(self.bits() & !other.bits()) } - /// Returns the [symmetric difference][sym-diff] between the flags + /// Returns the symmetric difference 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`. - /// - /// [sym-diff]: https://en.wikipedia.org/wiki/Symmetric_difference #[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. - /// - /// Specifically, the returned set contains all the flags which are - /// not set in `self`, but which are allowed for this type. #[must_use] fn complement(self) -> Self { Self::from_bits_truncate(!self.bits())
2.3
bitflags/bitflags
09f71f492d0f76d63cd286c3869c70676297e204
2023-06-27T04:12:28Z
"Clippy warnings around \"manual implementation of an assign operation\"\nHi.\r\n\r\nI've run into a(...TRUNCATED)
"diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml\n--- a/.github/workflows/rust.(...TRUNCATED)
31d3e4afefc964045156d7fe3622733f48511353
[ "357" ]
2023-05-17T11:22:15Z
355
bitflags__bitflags-355
"diff --git a/src/example_generated.rs b/src/example_generated.rs\n--- a/src/example_generated.rs\n+(...TRUNCATED)
2.3
bitflags/bitflags
09f71f492d0f76d63cd286c3869c70676297e204
2023-05-17T14:15:19Z
"Allow external impls of Bits and BitFlags\nThe `BitFlags` trait is currently sealed, and is only su(...TRUNCATED)
"diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml\n--- a/.github/workflows/rust.(...TRUNCATED)
"As for `Bits`, it can be reasonably reduced to:\r\n\r\n```rust\r\npub trait Bits:\r\n Clone\r\n (...TRUNCATED)
1d8388bf4ce18afde846d220ad8b6e0dc40aae94
[ "348" ]
2023-05-04T06:16:51Z
351
bitflags__bitflags-351
"diff --git /dev/null b/examples/custom_bits_type.rs\nnew file mode 100644\n--- /dev/null\n+++ b/exa(...TRUNCATED)
2.2
bitflags/bitflags
1d8388bf4ce18afde846d220ad8b6e0dc40aae94
2023-05-17T02:17:15Z
"Debug formatting leads to less desireable output\n[Link to rust playground](https://play.rust-lang.(...TRUNCATED)
"diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1353,7 +1321,10 @@ mo(...TRUNCATED)
"I think the current algorithm used for debug output is to loop over all flags and append identifier(...TRUNCATED)
f38ce72d11ef3e264d4b62f360bd8a5597b916d9
[ "215" ]
2022-05-03T06:59:46Z
281
bitflags__bitflags-281
"diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs\n--- a/src/bitflags_trait.rs\n+++ b/src/(...TRUNCATED)
1.3
bitflags/bitflags
b14fd2f6e65ff43eabf754680570e4951903d7b2
2022-08-18T07:52:21Z
"from_bits accepts non existing flags\n```rs\r\n #[test]\r\n fn test_from_bits_edge_cases() {\(...TRUNCATED)
"diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1891,6 +1907,37 @@ mo(...TRUNCATED)
0141a07e55184304857384b0093d00959f0acfa6
[ "275" ]
2022-04-19T09:54:30Z
276
bitflags__bitflags-276
"diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -559,10 +559,11 @@ mac(...TRUNCATED)
1.3
bitflags/bitflags
b14fd2f6e65ff43eabf754680570e4951903d7b2
2022-04-28T22:56:11Z
"Bug: debug pretty-printing unknown flags display 0x0x\nmain.rs\r\n```rust\r\nuse bitflags::bitflags(...TRUNCATED)
"diff --git a/tests/compile-fail/trait/custom_impl.rs b/tests/compile-fail/trait/custom_impl.rs\n---(...TRUNCATED)
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
[ "267" ]
2022-01-02T17:22:14Z
268
bitflags__bitflags-268
"diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -494,8 +494,7 @@ macro(...TRUNCATED)
1.3
bitflags/bitflags
b14fd2f6e65ff43eabf754680570e4951903d7b2
2022-01-08T01:08:04Z
"The bitflags macro is not sanitary wrt. standard library types and enumerations\nThe `bitflags` mac(...TRUNCATED)
"diff --git /dev/null b/tests/compile-pass/redefinition/result.rs\nnew file mode 100644\n--- /dev/nu(...TRUNCATED)
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
[ "265" ]
2021-12-16T09:38:14Z
266
bitflags__bitflags-266
"diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -500,7 +500,7 @@ macro(...TRUNCATED)
1.3
bitflags/bitflags
b14fd2f6e65ff43eabf754680570e4951903d7b2
2022-01-08T01:07:10Z
"`usize` / `isize` aren't supported anymore in `v2.0`\nThis doesn't seem intentional at least and is(...TRUNCATED)
"diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1548,4 +1548,57 @@ mo(...TRUNCATED)
"In what way are they not supported? What error message do they give? Or is there some other problem(...TRUNCATED)
8b43d2bb7efbd3d4189fdac92e411ad20c5140b5
[ "319" ]
2023-03-19T08:31:22Z
321
bitflags__bitflags-321
"diff --git a/src/traits.rs b/src/traits.rs\n--- a/src/traits.rs\n+++ b/src/traits.rs\n@@ -138,6 +13(...TRUNCATED)
2.0
bitflags/bitflags
11640f19a7644f3967631733f33ec87b9f911951
2023-03-19T10:34:04Z
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5