repo
stringclasses
1 value
problem_statement
stringlengths
79
2.53k
hints_text
stringlengths
0
2.82k
instance_id
stringlengths
21
22
issue_numbers
listlengths
1
2
base_commit
stringlengths
40
40
test_patch
stringlengths
336
78k
version
stringlengths
3
3
pull_number
int64
24
380
created_at
stringlengths
20
20
patch
stringlengths
251
103k
environment_setup_commit
stringlengths
40
40
bitflags/bitflags
Implement Arbitrary for bitflags? Would it be worth it to have an optional implementation of [`Arbitrary`](https://docs.rs/arbitrary/1.0.1/arbitrary/trait.Arbitrary.html) (in the [arbitrary crate](https://crates.io/crates/arbitrary)) for bitflags types, to make it easier to use them in fuzzing? I'm imagining something along the lines of this, added to the macro expansion when `cfg(feature = "arbitrary")` or so: ```rust impl arbitrary::Arbitrary for $BitFlags { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { Self::from_bits(u.arbitrary()).ok_or_else(|| arbitrary::Error::IncorrectFormat) } } ```
Can we think of any other implementation for `Arbitrary` that a consumer might want to add themselves? If not then this seems like a reasonable addition to me, since as I understand it, `Arbitrary` is meant to be a general API that different fuzzer implementations can lean on. Anything that makes fuzzing easier to get started with is worth doing! 😁 I've now submitted #260 implementing this. We've recently published `2.0.0` that reworks the library internals to support new external trait implementations without breaking consumers. We should now be able to add an implementation for `arbitrary` following the support for `serde` as an example.
bitflags__bitflags-324
[ "248" ]
11640f19a7644f3967631733f33ec87b9f911951
diff --git /dev/null b/src/external/arbitrary_support.rs new file mode 100644 --- /dev/null +++ b/src/external/arbitrary_support.rs @@ -0,0 +1,19 @@ +#[cfg(test)] +mod tests { + use arbitrary::Arbitrary; + + bitflags! { + #[derive(Arbitrary)] + struct Color: u32 { + const RED = 0x1; + const GREEN = 0x2; + const BLUE = 0x4; + } + } + + #[test] + fn test_arbitrary() { + let mut unstructured = arbitrary::Unstructured::new(&[0_u8; 256]); + let _color = Color::arbitrary(&mut unstructured); + } +}
2.0
324
2023-03-25T01:34:21Z
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -49,7 +49,7 @@ jobs: run: cargo install cargo-hack - name: Powerset - run: cargo hack test --feature-powerset --lib --optional-deps "std serde" --depth 3 --skip rustc-dep-of-std + run: cargo hack test --feature-powerset --lib --optional-deps --depth 3 --skip "compiler_builtins core rustc-dep-of-std" - name: Docs run: cargo doc --features example_generated diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ exclude = ["tests", ".github"] [dependencies] serde = { version = "1.0", optional = true, default-features = false } +arbitrary = { version = "1.0", optional = true } core = { version = "1.0.0", optional = true, package = "rustc-std-workspace-core" } compiler_builtins = { version = "0.1.2", optional = true } diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +31,7 @@ rustversion = "1.0" serde_derive = "1.0" serde_json = "1.0" serde_test = "1.0" +arbitrary = { version = "1.0", features = ["derive"] } [features] std = [] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -3,6 +3,9 @@ #[cfg(feature = "serde")] pub mod serde_support; +#[cfg(feature = "arbitrary")] +pub mod arbitrary_support; + /// Implements traits from external libraries for the internal bitflags type. #[macro_export(local_inner_macros)] #[doc(hidden)] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -27,6 +30,15 @@ macro_rules! __impl_external_bitflags { )* } } + + __impl_external_bitflags_arbitrary! { + $InternalBitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } }; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -80,3 +92,40 @@ macro_rules! __impl_external_bitflags_serde { } ) => {}; } + +/// Implement `Arbitrary` for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(feature = "arbitrary")] +macro_rules! __impl_external_bitflags_arbitrary { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + impl<'a> $crate::__private::arbitrary::Arbitrary<'a> for $InternalBitFlags { + fn arbitrary( + u: &mut $crate::__private::arbitrary::Unstructured<'a>, + ) -> $crate::__private::arbitrary::Result<Self> { + Self::from_bits(u.arbitrary()?).ok_or_else(|| $crate::__private::arbitrary::Error::IncorrectFormat) + } + } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "arbitrary"))] +macro_rules! __impl_external_bitflags_arbitrary { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => {}; +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -361,6 +361,9 @@ pub mod __private { #[cfg(feature = "serde")] pub use serde; + + #[cfg(feature = "arbitrary")] + pub use arbitrary; } /*
11640f19a7644f3967631733f33ec87b9f911951
bitflags/bitflags
Support bytemuck From #310 Add a `bytemuck` Cargo feature that derives `bytemuck` traits on the generated inner flags type so end-users can then `#[derive(bytemuck::*)]` traits on their own flags types.
bitflags__bitflags-336
[ "311" ]
597d40749224d3eee125a6ea9d6ac4c92b898ee8
diff --git /dev/null b/src/external/bytemuck_support.rs new file mode 100644 --- /dev/null +++ b/src/external/bytemuck_support.rs @@ -0,0 +1,19 @@ +#[cfg(test)] +mod tests { + use bytemuck::{Pod, Zeroable}; + + bitflags! { + #[derive(Pod, Zeroable, Clone, Copy)] + #[repr(transparent)] + struct Color: u32 { + const RED = 0x1; + const GREEN = 0x2; + const BLUE = 0x4; + } + } + + #[test] + fn test_bytemuck() { + assert_eq!(0x1, bytemuck::cast::<Color, u32>(Color::RED)); + } +}
2.1
336
2023-04-11T01:30:12Z
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ exclude = ["tests", ".github"] [dependencies] serde = { version = "1.0", optional = true, default-features = false } arbitrary = { version = "1.0", optional = true } +bytemuck = { version = "1.0", optional = true } core = { version = "1.0.0", optional = true, package = "rustc-std-workspace-core" } compiler_builtins = { version = "0.1.2", optional = true } diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +33,7 @@ serde_derive = "1.0" serde_json = "1.0" serde_test = "1.0" arbitrary = { version = "1.0", features = ["derive"] } +bytemuck = { version = "1.0", features = ["derive"] } [features] std = [] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -1,10 +1,83 @@ //! Conditional trait implementations for external libraries. +/* +How do I support a new external library? + +Let's say we want to add support for `my_library`. + +First, we define a macro like so: + +```rust +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(feature = "serde")] +macro_rules! __impl_external_bitflags_my_library { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + // Implementation goes here + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "my_library"))] +macro_rules! __impl_external_bitflags_my_library { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => {}; +} +``` + +Note that the macro is actually defined twice; once for when the `my_library` feature +is available, and once for when it's not. This is because the `__impl_external_bitflags_my_library` +macro is called in an end-user's library, not in `bitflags`. In an end-user's library we don't +know whether or not a particular feature of `bitflags` is enabled, so we unconditionally call +the macro, where the body of that macro depends on the feature flag. + +Now, we add our macro call to the `__impl_external_bitflags` macro body: + +```rust +__impl_external_bitflags_my_library! { + $InternalBitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } +} +``` + +What about libraries that _must_ be supported through `#[derive]`? + +In these cases, the attributes will need to be added to the `__declare_internal_bitflags` macro when +the internal type is declared. +*/ + #[cfg(feature = "serde")] pub mod serde_support; +#[cfg(feature = "serde")] +pub use serde; #[cfg(feature = "arbitrary")] pub mod arbitrary_support; +#[cfg(feature = "arbitrary")] +pub use arbitrary; + +#[cfg(feature = "bytemuck")] +pub mod bytemuck_support; +#[cfg(feature = "bytemuck")] +pub use bytemuck; /// Implements traits from external libraries for the internal bitflags type. #[macro_export(local_inner_macros)] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -39,6 +112,15 @@ macro_rules! __impl_external_bitflags { )* } } + + __impl_external_bitflags_bytemuck! { + $InternalBitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } }; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -129,3 +211,50 @@ macro_rules! __impl_external_bitflags_arbitrary { } ) => {}; } + +/// Implement `Pod` and `Zeroable` for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(feature = "bytemuck")] +macro_rules! __impl_external_bitflags_bytemuck { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + // 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, + { + + } + + // 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, + { + + } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "bytemuck"))] +macro_rules! __impl_external_bitflags_bytemuck { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => {}; +} diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -14,6 +14,9 @@ macro_rules! __declare_internal_bitflags { $iter_vis:vis struct $Iter:ident; $iter_names_vis:vis struct $IterNames:ident; ) => { + // NOTE: The ABI of this type is _guaranteed_ to be the same as `T` + // This is relied on by some external libraries like `bytemuck` to make + // its `unsafe` trait impls sound. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] $vis struct $InternalBitFlags { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -394,8 +394,9 @@ //! example docs. #![cfg_attr(not(any(feature = "std", test)), no_std)] +#![cfg_attr(not(test), forbid(unsafe_code))] + #![doc(html_root_url = "https://docs.rs/bitflags/2.1.0")] -#![forbid(unsafe_code)] #[doc(inline)] pub use traits::BitFlags; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -408,12 +409,6 @@ pub mod __private { pub use crate::{external::*, traits::*}; pub use core; - - #[cfg(feature = "serde")] - pub use serde; - - #[cfg(feature = "arbitrary")] - pub use arbitrary; } /* diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -14,7 +14,7 @@ macro_rules! __declare_public_bitflags { $vis:vis struct $BitFlags:ident; ) => { $(#[$outer])* - $vis struct $BitFlags(<Self as $crate::__private::PublicFlags>::Internal); + $vis struct $BitFlags(<$BitFlags as $crate::__private::PublicFlags>::Internal); }; }
dc971042c8132a5381ab3e2165983ee7f9d44c63
bitflags/bitflags
`usize` / `isize` aren't supported anymore in `v2.0` This doesn't seem intentional at least and isn't mentioned in the changelog.
In what way are they not supported? What error message do they give? Or is there some other problem with them? They don't implement the new `Bits` trait, which is required to use bitflags: https://github.com/bitflags/bitflags/blob/main/src/traits.rs#L135-L141 Thanks for pointing this out @CryZe. This is a total oversight, they should implement the `Bits` trait.
bitflags__bitflags-321
[ "319" ]
8b43d2bb7efbd3d4189fdac92e411ad20c5140b5
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1548,4 +1548,57 @@ mod tests { 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; + } + } + } }
2.0
321
2023-03-19T08:31:22Z
diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -138,6 +138,7 @@ impl_bits! { u32, i32, u64, i64, u128, i128, + usize, isize, } /// A trait for referencing the `bitflags`-owned internal type
11640f19a7644f3967631733f33ec87b9f911951
bitflags/bitflags
Display missing extra bits for multi-bit flags See: https://github.com/bitflags/bitflags/issues/310#issuecomment-1470122112 Given a flags type with two flags, `BIT = 0b0000_0001` and `MASK = 0b0001_1110`, formatting the value `3` should result in `BIT | 0x2`, but instead it gives `BIT`. That extra bit gets lost, so doesn't roundtrip. The problem seems to be in the generated `iter_names` method.
bitflags__bitflags-316
[ "315" ]
ad0271116e28a79ea880334dd3d06212a224ec09
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1154,17 +1154,39 @@ mod tests { #[test] fn test_display_from_str_roundtrip() { - fn format_parse_case(flags: FmtFlags) { + 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::<FmtFlags>() { + match flags.to_string().parse::<T>() { Ok(flags) => flags, Err(e) => panic!("failed to parse `{}`: {}", flags, e), } }); } - fn parse_case(expected: FmtFlags, flags: &str) { - assert_eq!(expected, flags.parse::<FmtFlags>().unwrap()); + 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()); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1174,6 +1196,7 @@ mod tests { 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");
2.0
316
2023-03-16T00:19:13Z
diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -89,7 +89,8 @@ macro_rules! __impl_internal_bitflags { // Iterate over the valid flags let mut first = true; - for (name, _) in self.iter_names() { + let mut iter = self.iter_names(); + for (name, _) in &mut iter { if !first { f.write_str(" | ")?; } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -99,8 +100,7 @@ macro_rules! __impl_internal_bitflags { } // Append any extra bits that correspond to flags to the end of the format - let extra_bits = self.bits & !Self::all().bits; - + let extra_bits = iter.state.bits(); if extra_bits != <$T as $crate::__private::Bits>::EMPTY { if !first { f.write_str(" | ")?;
11640f19a7644f3967631733f33ec87b9f911951
bitflags/bitflags
Cannot use `#[doc(alias)]` The following code: ```rs bitflags::bitflags! { #[doc(alias = "SYMBOLIC_LINK_FLAGS")] pub struct SymbolicLinkFlags:u32 { #[doc(alias = "SYMBOLIC_LINK_FLAG_DIRECTORY")] const DIRECTORY = 0x1; #[doc(alias = "SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE")] const ALLOW_UNPRIVILEGED_CREATE = 0x2; } } ``` Produces the error: ``` error: `#[doc(alias = "...")]` isn't allowed on expression --> src\fs.rs:67:15 | 67 | #[doc(alias = "SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ```
This is a general problem for attributes that can't be applied to expressions now. In methods like `from_name` we now generate code like this: ```rust #[inline] pub fn from_name(name: &str) -> ::bitflags::__private::core::option::Option<Self> { match name { #[doc(alias = "SYMBOLIC_LINK_FLAG_DIRECTORY")] "DIRECTORY" => ::bitflags::__private::core::option::Option::Some(Self { bits: SymbolicLinkFlags::DIRECTORY.bits(), }), #[doc(alias = "SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE")] "ALLOW_UNPRIVILEGED_CREATE" => { ::bitflags::__private::core::option::Option::Some(Self { bits: SymbolicLinkFlags::ALLOW_UNPRIVILEGED_CREATE.bits(), }) } _ => ::bitflags::__private::core::option::Option::None, } } ``` I think the quickest fix would be to introduce a helper macro that filtered out some attributes like `#[doc(..)]` for these match arms. Any more of these that come up in the future could be added to that macro. What kinds of attributes would be useful to apply there other than `cfg`? I can't really think of any besides maybe `#[allow]`, but we handle those on the item itself. I think it would be fair to flip this into an allow-list so only `cfg` attributes get propagated.
bitflags__bitflags-341
[ "308" ]
dc971042c8132a5381ab3e2165983ee7f9d44c63
diff --git /dev/null b/tests/compile-pass/doc_alias.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/doc_alias.rs @@ -0,0 +1,14 @@ +#[macro_use] +extern crate bitflags; + +bitflags! { + #[doc(alias = "FLAG")] + pub struct Flags: u8 { + #[doc(alias = "FLAG_A")] + const A = 1; + } +} + +fn main() { + +}
2.1
341
2023-04-18T00:36:26Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -558,6 +558,315 @@ macro_rules! bitflags { } $($t:tt)* + ) => { + __declare_bitflags!( + $(#[$outer])* + $vis struct $BitFlags: $T { + $( + $(#[$inner $($args)*])* + const $Flag = $value; + )* + } + ); + + bitflags! { + $($t)* + } + }; + () => {}; +} + +/// A macro that processed the input to `bitflags!` and shuffles attributes around +/// based on whether or not they're "expression-safe". +/// +/// This macro is a token-tree muncher that works on 2 levels: +/// +/// 1. Each flag, like `#[cfg(true)] const A: 42` +/// 2. Each attribute on that flag, like `#[cfg(true)]` +/// +/// Flags and attributes start in an "unprocessed" list, and are shifted one token +/// at a time into an appropriate processed list until the unprocessed lists are empty. +/// +/// For each attribute, we explicitly match on its identifier, like `cfg` to determine +/// whether or not it should be considered expression-safe. +/// +/// If you find yourself with an attribute that should be considered expression-safe +/// and isn't, it can be added here. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __declare_bitflags { + // Entrypoint: Move all flags and all attributes into `unprocessed` lists + // where they'll be munched one-at-a-time + ( + $(#[$outer:meta])* + $vis:vis struct $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )* + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + // All flags start here + unprocessed: [ + $( + { + ident: $Flag, + value: $value, + attrs: { + // All attributes start here + unprocessed: [$(#[$inner $($args)*])*], + processed: { + // Attributes that should be added to item declarations go here + decl: [], + // Attributes that are safe on expressions go here + expr: [], + } + }, + }, + )* + ], + // Flags that have had their attributes sorted are pushed here + processed: [], + } + } + }; + // Process the next attribute on the current flag + // `cfg`: The next flag should be propagated to expressions + // NOTE: You can copy this rules block and replace `cfg` with + // your attribute name that should be considered expression-safe + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [ + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [ + // cfg matched here + #[cfg $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + decl: [$($decl:tt)*], + expr: [$($expr:tt)*], + } + }, + }, + $($flags_rest:tt)* + ], + processed: [ + $($flags:tt)* + ], + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + unprocessed: [ + { + ident: $Flag, + value: $value, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + decl: [ + // cfg added here + #[cfg $($args)*] + $($decl)* + ], + expr: [ + // cfg added here + #[cfg $($args)*] + $($expr)* + ], + } + }, + }, + $($flags_rest)* + ], + processed: [ + $($flags)* + ], + } + } + }; + // Process the next attribute on the current flag + // `$other`: The next flag should not be propagated to expressions + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [ + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [ + // $other matched here + #[$other:ident $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + decl: [$($decl:tt)*], + expr: [$($expr:tt)*], + } + }, + }, + $($flags_rest:tt)* + ], + processed: [ + $($flags:tt)* + ], + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + unprocessed: [ + { + ident: $Flag, + value: $value, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + decl: [ + // $other added here + #[$other $($args)*] + $($decl)* + ], + expr: [ + // $other not added here + $($expr)* + ], + } + }, + }, + $($flags_rest)* + ], + processed: [ + $($flags)* + ], + } + } + }; + // Complete the current flag once there are no unprocessed attributes left + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [ + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [], + processed: { + decl: [$($decl:tt)*], + expr: [$($expr:tt)*], + } + }, + }, + $($flags_rest:tt)* + ], + processed: [ + $($flags:tt)* + ], + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + unprocessed: [ + $($flags_rest)* + ], + processed: [ + $($flags)* + { + ident: $Flag, + value: $value, + attrs: { + unprocessed: [], + processed: { + decl: [ + $($decl)* + ], + expr: [ + $($expr)* + ], + } + }, + }, + ], + } + } + }; + // Once all attributes on all flags are processed, generate the actual code + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [], + processed: [ + $( + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [], + processed: { + decl: [$(#[$decl:ident $($declargs:tt)*])*], + expr: [$(#[$expr:ident $($exprargs:tt)*])*], + } + }, + }, + )* + ], + } ) => { // Declared in the scope of the `bitflags!` call // This type appears in the end-user's API diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -570,7 +879,7 @@ macro_rules! bitflags { __impl_public_bitflags_consts! { $BitFlags { $( - $(#[$inner $($args)*])* + $(#[$decl $($declargs)*])* #[allow( dead_code, deprecated, diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -603,7 +912,7 @@ macro_rules! bitflags { __impl_internal_bitflags! { InternalBitFlags: $T, $BitFlags, Iter, IterRaw { $( - $(#[$inner $($args)*])* + $(#[$expr $($exprargs)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -613,7 +922,7 @@ macro_rules! bitflags { __impl_external_bitflags! { InternalBitFlags: $T { $( - $(#[$inner $($args)*])* + $(#[$expr $($exprargs)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -623,12 +932,7 @@ macro_rules! bitflags { $BitFlags: $T, InternalBitFlags, Iter, IterRaw; } }; - - bitflags! { - $($t)* - } - }; - () => {}; + } } #[macro_use]
dc971042c8132a5381ab3e2165983ee7f9d44c63
bitflags/bitflags
Clippy warnings around "manual implementation of an assign operation" Hi. I've run into a new clippy lint warnings such as the following: > manual implementation of an assign operation > for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assign_op_pattern > `#[warn(clippy::assign_op_pattern)]` on by default I'm following the example from the docs page for the use of the macro (more or less, as below). Can you enlighten me as to why this lint notification is appearing here and if there is some way to fix it? I know I can silence the warnings, it's just annoying to see it pop up whenever I run into it. ```rust bitflags! { pub struct MemoryAccess: u8 { /// None. const N = 1 << 0; /// Public read. const R = 1 << 1; /// Public write. const W = 1 << 2; /// Private read. const PR = 1 << 3; /// Private write. const PW = 1 << 4; /// Execute. const EX = 1 << 5; } } ``` Thanks!
bitflags__bitflags-355
[ "357" ]
31d3e4afefc964045156d7fe3622733f48511353
diff --git a/tests/compile-fail/bitflags_custom_bits.rs b/tests/compile-fail/bitflags_custom_bits.rs --- a/tests/compile-fail/bitflags_custom_bits.rs +++ b/tests/compile-fail/bitflags_custom_bits.rs @@ -19,7 +19,7 @@ use std::{ }, }; -use bitflags::{bitflags, Bits, parser::{ParseError, FromHex}}; +use bitflags::{bitflags, Bits, parser::{ParseError, WriteHex, ParseHex}}; // Ideally we'd actually want this to work, but currently need something like `num`'s `Zero` // With some design work it could be made possible diff --git a/tests/compile-fail/bitflags_custom_bits.rs b/tests/compile-fail/bitflags_custom_bits.rs --- a/tests/compile-fail/bitflags_custom_bits.rs +++ b/tests/compile-fail/bitflags_custom_bits.rs @@ -117,12 +117,18 @@ impl Binary for MyInt { } } -impl FromHex for MyInt { - fn from_hex(input: &str) -> Result<Self, ParseError> { +impl ParseHex for MyInt { + fn parse_hex(input: &str) -> Result<Self, ParseError> { Ok(MyInt(u8::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))?)) } } +impl WriteHex for MyInt { + fn write_hex<W: fmt::Write>(&self, writer: W) -> fmt::Result { + LowerHex::fmt(&self.0, writer) + } +} + bitflags! { struct Flags128: MyInt { const A = MyInt(0b0000_0001u8); 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 @@ -1,7 +1,7 @@ error[E0277]: the trait bound `MyInt: bitflags::traits::Primitive` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:127:22 + --> tests/compile-fail/bitflags_custom_bits.rs:133:22 | -127 | struct Flags128: MyInt { +133 | struct Flags128: MyInt { | ^^^^^ the trait `bitflags::traits::Primitive` is not implemented for `MyInt` | = help: the following other types implement trait `bitflags::traits::Primitive`: 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 @@ -20,442 +20,457 @@ note: required by a bound in `PublicFlags::Primitive` | type Primitive: Primitive; | ^^^^^^^^^ required by this bound in `PublicFlags::Primitive` +error[E0308]: mismatched types + --> tests/compile-fail/bitflags_custom_bits.rs:128:32 + | +127 | fn write_hex<W: fmt::Write>(&self, writer: W) -> fmt::Result { + | - this type parameter +128 | LowerHex::fmt(&self.0, writer) + | ------------- ^^^^^^ expected `&mut Formatter<'_>`, found type parameter `W` + | | + | arguments to this function are incorrect + | + = note: expected mutable reference `&mut Formatter<'_>` + 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> 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) diff --git /dev/null b/tests/compile-pass/bitflags_self_in_value.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/bitflags_self_in_value.rs @@ -0,0 +1,15 @@ +use bitflags::bitflags; + +bitflags! { + pub struct Flags: u32 { + const SOME_FLAG = 1 << Self::SOME_FLAG_SHIFT; + } +} + +impl Flags { + const SOME_FLAG_SHIFT: u32 = 5; +} + +fn main() { + +} diff --git a/tests/smoke-test/src/main.rs b/tests/smoke-test/src/main.rs --- a/tests/smoke-test/src/main.rs +++ b/tests/smoke-test/src/main.rs @@ -1,3 +1,5 @@ +#![deny(warnings)] + use bitflags::bitflags; bitflags! {
2.3
355
2023-05-17T11:22:15Z
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -81,6 +81,23 @@ jobs: - name: Default features run: cross test --target mips-unknown-linux-gnu + clippy: + name: Clippy + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab + + - name: Install Clippy + run: | + rustup update beta + rustup component add clippy --toolchain beta + + - name: Default features + run: | + cd ./tests/smoke-test + cargo +beta clippy + embedded: name: Build (embedded) runs-on: ubuntu-latest diff --git a/src/example_generated.rs b/src/example_generated.rs --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -39,7 +39,7 @@ __impl_public_bitflags_forward! { } __impl_public_bitflags_iter! { - Flags + Flags: u32, Flags } __impl_public_bitflags_consts! { diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -19,7 +19,7 @@ Next, define a macro like so: #[cfg(feature = "serde")] macro_rules! __impl_external_bitflags_my_library { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -35,7 +35,7 @@ macro_rules! __impl_external_bitflags_my_library { #[cfg(not(feature = "my_library"))] macro_rules! __impl_external_bitflags_my_library { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -55,7 +55,7 @@ Now, we add our macro call to the `__impl_external_bitflags` macro body: ```rust __impl_external_bitflags_my_library! { - $InternalBitFlags: $T { + $InternalBitFlags: $T, $PublicBitFlags { $( $(#[$attr $($args)*])* $Flag; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -76,6 +76,51 @@ pub(crate) mod __private { pub use bytemuck; } +/// Implements traits from external libraries for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_external_bitflags { + ( + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + // Any new library traits impls should be added here + // Use `serde` as an example: generate code when the feature is available, + // and a no-op when it isn't + + __impl_external_bitflags_serde! { + $InternalBitFlags: $T, $PublicBitFlags { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } + + __impl_external_bitflags_arbitrary! { + $InternalBitFlags: $T, $PublicBitFlags { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } + + __impl_external_bitflags_bytemuck! { + $InternalBitFlags: $T, $PublicBitFlags { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } + }; +} + #[cfg(feature = "serde")] pub mod serde; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -85,11 +130,11 @@ pub mod serde; #[cfg(feature = "serde")] macro_rules! __impl_external_bitflags_serde { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; - )* + )* } ) => { impl $crate::__private::serde::Serialize for $InternalBitFlags { diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -98,7 +143,7 @@ macro_rules! __impl_external_bitflags_serde { serializer: S, ) -> $crate::__private::core::result::Result<S::Ok, S::Error> { $crate::serde::serialize( - self, + &$PublicBitFlags::from_bits_retain(self.bits()), serializer, ) } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -108,9 +153,11 @@ macro_rules! __impl_external_bitflags_serde { fn deserialize<D: $crate::__private::serde::Deserializer<'de>>( deserializer: D, ) -> $crate::__private::core::result::Result<Self, D::Error> { - $crate::serde::deserialize( + 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 @@ -121,11 +168,11 @@ macro_rules! __impl_external_bitflags_serde { #[cfg(not(feature = "serde"))] macro_rules! __impl_external_bitflags_serde { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; - )* + )* } ) => {}; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -136,58 +183,13 @@ pub mod arbitrary; #[cfg(feature = "bytemuck")] mod bytemuck; -/// Implements traits from external libraries for the internal bitflags type. -#[macro_export(local_inner_macros)] -#[doc(hidden)] -macro_rules! __impl_external_bitflags { - ( - $InternalBitFlags:ident: $T:ty { - $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* - } - ) => { - // Any new library traits impls should be added here - // Use `serde` as an example: generate code when the feature is available, - // and a no-op when it isn't - - __impl_external_bitflags_serde! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - $Flag; - )* - } - } - - __impl_external_bitflags_arbitrary! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - $Flag; - )* - } - } - - __impl_external_bitflags_bytemuck! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - $Flag; - )* - } - } - }; -} - /// Implement `Arbitrary` for the internal bitflags type. #[macro_export(local_inner_macros)] #[doc(hidden)] #[cfg(feature = "arbitrary")] macro_rules! __impl_external_bitflags_arbitrary { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -198,7 +200,7 @@ macro_rules! __impl_external_bitflags_arbitrary { fn arbitrary( u: &mut $crate::__private::arbitrary::Unstructured<'a>, ) -> $crate::__private::arbitrary::Result<Self> { - $crate::arbitrary::arbitrary(u) + $crate::arbitrary::arbitrary::<$PublicBitFlags>(u).map(|flags| flags.0) } } }; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -209,12 +211,12 @@ macro_rules! __impl_external_bitflags_arbitrary { #[cfg(not(feature = "arbitrary"))] macro_rules! __impl_external_bitflags_arbitrary { ( - $InternalBitFlags:ident: $T:ty { - $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* - } + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } ) => {}; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -224,11 +226,11 @@ macro_rules! __impl_external_bitflags_arbitrary { #[cfg(feature = "bytemuck")] macro_rules! __impl_external_bitflags_bytemuck { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* + $Flag:ident; + )* } ) => { // SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T, diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -256,11 +258,11 @@ macro_rules! __impl_external_bitflags_bytemuck { #[cfg(not(feature = "bytemuck"))] macro_rules! __impl_external_bitflags_bytemuck { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* + $Flag:ident; + )* } ) => {}; } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -98,7 +98,7 @@ macro_rules! __impl_internal_bitflags { // The internal flags type offers a similar API to the public one __impl_public_bitflags! { - $InternalBitFlags: $T { + $InternalBitFlags: $T, $PublicBitFlags { $( $(#[$attr $($args)*])* $Flag; diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -106,19 +106,8 @@ macro_rules! __impl_internal_bitflags { } } - __impl_public_bitflags_consts! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - #[allow( - dead_code, - deprecated, - unused_attributes, - non_upper_case_globals - )] - $Flag = $value; - )* - } + __impl_public_bitflags_iter! { + $InternalBitFlags: $T, $PublicBitFlags } impl $InternalBitFlags { diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -127,18 +116,6 @@ macro_rules! __impl_internal_bitflags { pub fn bits_mut(&mut self) -> &mut $T { &mut self.0 } - - /// 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.0), $PublicBitFlags::from_bits_retain(self.0)) - } - - /// 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.0), $PublicBitFlags::from_bits_retain(self.0)) - } } }; } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -590,7 +590,8 @@ macro_rules! bitflags { unused_attributes, unused_mut, unused_imports, - non_upper_case_globals + non_upper_case_globals, + clippy::assign_op_pattern )] 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 @@ -610,7 +611,7 @@ macro_rules! bitflags { // This is where new library trait implementations can be added __impl_external_bitflags! { - InternalBitFlags: $T { + InternalBitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* $Flag; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -623,7 +624,7 @@ macro_rules! bitflags { } __impl_public_bitflags_iter! { - $BitFlags + $BitFlags: $T, $BitFlags } }; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -657,11 +658,12 @@ macro_rules! bitflags { unused_attributes, unused_mut, unused_imports, - non_upper_case_globals + non_upper_case_globals, + clippy::assign_op_pattern )] const _: () = { __impl_public_bitflags! { - $BitFlags: $T { + $BitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* $Flag; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -670,7 +672,7 @@ macro_rules! bitflags { } __impl_public_bitflags_iter! { - $BitFlags + $BitFlags: $T, $BitFlags } }; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -57,7 +57,7 @@ macro_rules! __impl_public_bitflags_forward { Self($InternalBitFlags::from_bits_retain(bits)) } - fn from_name(name){ + fn from_name(name) { match $InternalBitFlags::from_name(name) { $crate::__private::core::option::Option::Some(bits) => $crate::__private::core::option::Option::Some(Self(bits)), $crate::__private::core::option::Option::None => $crate::__private::core::option::Option::None, diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -130,7 +130,7 @@ macro_rules! __impl_public_bitflags_forward { #[doc(hidden)] macro_rules! __impl_public_bitflags { ( - $PublicBitFlags:ident: $T:ty { + $BitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -138,7 +138,7 @@ macro_rules! __impl_public_bitflags { } ) => { __impl_bitflags! { - $PublicBitFlags: $T { + $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 @@ -260,7 +260,7 @@ macro_rules! __impl_public_bitflags { } } - __impl_public_bitflags_ops!($PublicBitFlags); + __impl_public_bitflags_ops!($BitFlags); }; } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -268,8 +268,8 @@ macro_rules! __impl_public_bitflags { #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! __impl_public_bitflags_iter { - ($PublicBitFlags:ident) => { - impl $PublicBitFlags { + ($BitFlags:ident: $T:ty, $PublicBitFlags:ident) => { + impl $BitFlags { /// Iterate over enabled flag values. #[inline] pub const fn iter(&self) -> $crate::iter::Iter<$PublicBitFlags> { diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -283,8 +283,8 @@ macro_rules! __impl_public_bitflags_iter { } } - impl $crate::__private::core::iter::IntoIterator for $PublicBitFlags { - type Item = Self; + impl $crate::__private::core::iter::IntoIterator for $BitFlags { + type Item = $PublicBitFlags; type IntoIter = $crate::iter::Iter<$PublicBitFlags>; fn into_iter(self) -> Self::IntoIter {
09f71f492d0f76d63cd286c3869c70676297e204
bitflags/bitflags
Bug: debug pretty-printing unknown flags display 0x0x main.rs ```rust use bitflags::bitflags; bitflags! { struct Flags: u8 { const TWO = 0x2; } } fn main() { let value = 0b11; let flags = unsafe { Flags::from_bits_unchecked(value) }; println!("{:?}", flags); println!("-----------"); println!("{:#?}", flags); } ``` will print the following: ```sh TWO | 0x1 ----------- TWO | 0x0x1 ``` the expected output would either be 0x1 for both, or 1, and 0x1 respectively
bitflags__bitflags-268
[ "267" ]
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
diff --git a/tests/compile-fail/trait/custom_impl.rs b/tests/compile-fail/trait/custom_impl.rs --- a/tests/compile-fail/trait/custom_impl.rs +++ b/tests/compile-fail/trait/custom_impl.rs @@ -62,4 +62,4 @@ impl BitFlags for BootlegFlags { } } -fn main() { } +fn main() {} diff --git a/tests/compile-pass/impls/convert.rs b/tests/compile-pass/impls/convert.rs --- a/tests/compile-pass/impls/convert.rs +++ b/tests/compile-pass/impls/convert.rs @@ -12,6 +12,4 @@ impl From<u32> for Flags { } } -fn main() { - -} +fn main() {} diff --git /dev/null b/tests/compile-pass/impls/fmt.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/impls/fmt.rs @@ -0,0 +1,14 @@ +use bitflags::bitflags; + +bitflags! { + struct Flags: u8 { + const TWO = 0x2; + } +} + +fn main() { + // bug #267 (https://github.com/bitflags/bitflags/issues/267) + let flags = unsafe { Flags::from_bits_unchecked(0b11) }; + assert_eq!(format!("{:?}", flags), "TWO | 0x1"); + assert_eq!(format!("{:#?}", flags), "TWO | 0x1"); +} diff --git a/tests/compile-pass/redefinition/stringify.rs b/tests/compile-pass/redefinition/macros.rs --- a/tests/compile-pass/redefinition/stringify.rs +++ b/tests/compile-pass/redefinition/macros.rs @@ -7,6 +7,11 @@ macro_rules! stringify { ($($t:tt)*) => { "..." }; } +#[allow(unused_macros)] +macro_rules! write { + ($($t:tt)*) => { "..." }; +} + bitflags! { struct Test: u8 { const A = 1; diff --git a/tests/compile-pass/redefinition/stringify.rs b/tests/compile-pass/redefinition/macros.rs --- a/tests/compile-pass/redefinition/stringify.rs +++ b/tests/compile-pass/redefinition/macros.rs @@ -14,6 +19,6 @@ bitflags! { } fn main() { - // Just make sure we don't call the redefined `stringify` macro - assert_eq!(format!("{:?}", Test::A), "A"); + // Just make sure we don't call the redefined `stringify` or `write` macro + assert_eq!(format!("{:?}", unsafe { Test::from_bits_unchecked(0b11) }), "A | 0x2"); }
1.3
268
2022-01-02T17:22:14Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -494,8 +494,7 @@ macro_rules! __impl_bitflags { f.write_str(" | ")?; } first = false; - f.write_str("0x")?; - $crate::_core::fmt::LowerHex::fmt(&extra_bits, f)?; + $crate::_core::write!(f, "{:#x}", extra_bits)?; } if first { f.write_str("(empty)")?;
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
The bitflags macro is not sanitary wrt. standard library types and enumerations The `bitflags` macro, expanded in the prescence of a definition of the type/value `Ok` errors. Reproduction code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3fda3e36c7c6a57e0f7a83c84e56df20 Interestingly, the relevant function, the `fmt` function from the Debug impl, does use `::bitflags::_core::fmt::Result`, however, it merely returns the value `Ok(())`.
bitflags__bitflags-266
[ "265" ]
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
diff --git /dev/null b/tests/compile-pass/redefinition/result.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/redefinition/result.rs @@ -0,0 +1,15 @@ +use bitflags::bitflags; + +// Checks for possible errors caused by overriding names used by `bitflags!` internally. + +// bug #265 (https://github.com/bitflags/bitflags/issues/265) + +pub struct Ok<T>(T); + +bitflags! { + pub struct Flags: u16{ + const FOO = 0x0001; + } +} + +fn main() {}
1.3
266
2021-12-16T09:38:14Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -500,7 +500,7 @@ macro_rules! __impl_bitflags { if first { f.write_str("(empty)")?; } - Ok(()) + $crate::_core::fmt::Result::Ok(()) } } impl $crate::_core::fmt::Binary for $BitFlags {
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
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!
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 🤔
bitflags__bitflags-380
[ "378" ]
472e392c0d082c0894b18fb31f4e68e0b145e29c
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();
2.4
380
2023-10-09T04:48:32Z
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/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! {
472e392c0d082c0894b18fb31f4e68e0b145e29c
bitflags/bitflags
Empty bitflags definitions fail to parse This doesn't parse: ```rust bitflags::bitflags! { pub struct BoxFlags: u8 { } } ```
Hmm, it looks like we're using `+` rather than `*` as the repetition control. I can't imagine an empty set of `bitflags` would be very useful. Do you have a case where you've run into this? It might useful when introducing the type and designing the API first, before you even actually add the various bitflags Yeh that seems fair. If there’s no reason to require bitflags have at least one item then we could probably just allow these to be written. > It might useful when introducing the type and designing the API first, before you even actually add the various bitflags Yeah I was doing that, just propagating some flag value which I know I will need but didn't know yet what the flags themselves will be. You can just put something like this in there: ```rust #[cfg(empty_bitflag_workaround)] const EMPTY_BITFLAG_WORKAROUND = 0; ```
bitflags__bitflags-225
[ "179" ]
bd24f9d8d266bfb2dfe4b8238b196ecf5e37dee1
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -992,6 +1026,11 @@ mod tests { } } + bitflags! { + struct EmptyFlags: u32 { + } + } + #[test] fn test_bits() { assert_eq!(Flags::empty().bits(), 0b00000000); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1000,6 +1039,8 @@ mod tests { assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00); assert_eq!(AnotherSetOfFlags::ANOTHER_FLAG.bits(), !0_i8); + + assert_eq!(EmptyFlags::empty().bits(), 0b00000000); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1014,6 +1055,9 @@ mod tests { 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] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1029,6 +1073,9 @@ mod tests { 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] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1037,6 +1084,7 @@ mod tests { assert_eq!(unsafe { Flags::from_bits_unchecked(0) }, Flags::empty()); assert_eq!(unsafe { Flags::from_bits_unchecked(0b1) }, Flags::A); assert_eq!(unsafe { Flags::from_bits_unchecked(0b10) }, Flags::B); + assert_eq!( unsafe { Flags::from_bits_unchecked(0b11) }, (Flags::A | Flags::B) diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1049,6 +1097,12 @@ mod tests { unsafe { Flags::from_bits_unchecked(0b1001) }, (extra | Flags::A) ); + + let extra = unsafe { EmptyFlags::from_bits_unchecked(0b1000) }; + assert_eq!( + unsafe { EmptyFlags::from_bits_unchecked(0b1000) }, + (extra | EmptyFlags::empty()) + ); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1058,6 +1112,9 @@ mod tests { assert!(!Flags::ABC.is_empty()); assert!(!AnotherSetOfFlags::ANOTHER_FLAG.is_empty()); + + assert!(EmptyFlags::empty().is_empty()); + assert!(EmptyFlags::all().is_empty()); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1067,6 +1124,9 @@ mod tests { assert!(Flags::ABC.is_all()); assert!(AnotherSetOfFlags::ANOTHER_FLAG.is_all()); + + assert!(EmptyFlags::all().is_all()); + assert!(EmptyFlags::empty().is_all()); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1108,6 +1168,8 @@ mod tests { assert!(Flags::ABC.contains(e2)); assert!(AnotherSetOfFlags::ANOTHER_FLAG.contains(AnotherSetOfFlags::ANOTHER_FLAG)); + + assert!(EmptyFlags::empty().contains(EmptyFlags::empty())); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1293,10 +1355,16 @@ mod tests { let extra = unsafe { Flags::from_bits_unchecked(0xb8) }; assert_eq!(format!("{:?}", extra), "0xb8"); assert_eq!(format!("{:?}", Flags::A | extra), "A | 0xb8"); + assert_eq!( format!("{:?}", Flags::ABC | extra), "A | B | C | ABC | 0xb8" ); + + assert_eq!( + format!("{:?}", EmptyFlags::empty()), + "(empty)" + ); } #[test]
1.2
225
2020-10-01T16:10:42Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -360,7 +360,7 @@ macro_rules! bitflags { $( $(#[$inner:ident $($args:tt)*])* const $Flag:ident = $value:expr; - )+ + )* } $($t:tt)* ) => { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -370,7 +370,7 @@ macro_rules! bitflags { $( $(#[$inner $($args)*])* $Flag = $value; - )+ + )* } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -414,7 +414,7 @@ macro_rules! __bitflags { $( $(#[$inner:ident $($args:tt)*])* $Flag:ident = $value:expr; - )+ + )* } ) => { $(#[$outer])* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -428,7 +428,7 @@ macro_rules! __bitflags { $( $(#[$inner $($args)*])* $Flag = $value; - )+ + )* } } }; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -490,7 +490,7 @@ macro_rules! __fn_bitflags { #[macro_export(local_inner_macros)] #[doc(hidden)] -macro_rules! __impl_bitflags { +macro_rules! __all_bitflags { ( $BitFlags:ident: $T:ty { $( diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -498,6 +498,55 @@ macro_rules! __impl_bitflags { $Flag:ident = $value:expr; )+ } + ) => { + __fn_bitflags! { + /// Returns the set containing all flags. + #[inline] + pub const fn all() -> $BitFlags { + // See `Debug::fmt` for why this approach is taken. + #[allow(non_snake_case)] + trait __BitFlags { + $( + const $Flag: $T = 0; + )+ + } + impl __BitFlags for $BitFlags { + $( + __impl_bitflags! { + #[allow(deprecated)] + $(? #[$attr $($args)*])* + const $Flag: $T = Self::$Flag.bits; + } + )+ + } + $BitFlags { bits: $(<$BitFlags as __BitFlags>::$Flag)|+ } + } + } + }; + ( + $BitFlags:ident: $T:ty { + } + ) => { + __fn_bitflags! { + /// Returns the set containing all flags. + #[inline] + pub const fn all() -> $BitFlags { + $BitFlags { bits: 0 } + } + } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_bitflags { + ( + $BitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident = $value:expr; + )* + } ) => { impl $crate::_core::fmt::Debug for $BitFlags { fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -514,7 +563,7 @@ macro_rules! __impl_bitflags { $( #[inline] fn $Flag(&self) -> bool { false } - )+ + )* } // Conditionally override the check for just those flags that diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -533,7 +582,7 @@ macro_rules! __impl_bitflags { } } } - )+ + )* } let mut first = true; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -545,7 +594,7 @@ macro_rules! __impl_bitflags { first = false; f.write_str(__bitflags_stringify!($Flag))?; } - )+ + )* let extra_bits = self.bits & !$BitFlags::all().bits(); if extra_bits != 0 { if !first { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -587,7 +636,7 @@ macro_rules! __impl_bitflags { $( $(#[$attr $($args)*])* pub const $Flag: $BitFlags = $BitFlags { bits: $value }; - )+ + )* __fn_bitflags! { /// Returns an empty set of flags. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -597,29 +646,14 @@ macro_rules! __impl_bitflags { } } - __fn_bitflags! { - /// Returns the set containing all flags. - #[inline] - pub const fn all() -> $BitFlags { - // See `Debug::fmt` for why this approach is taken. - #[allow(non_snake_case)] - trait __BitFlags { - $( - const $Flag: $T = 0; - )+ - } - impl __BitFlags for $BitFlags { + __all_bitflags! { + $BitFlags: $T { $( - __impl_bitflags! { - #[allow(deprecated)] - $(? #[$attr $($args)*])* - const $Flag: $T = Self::$Flag.bits; - } - )+ + $(#[$attr $($args)*])* + $Flag = $value; + )* } - $BitFlags { bits: $(<$BitFlags as __BitFlags>::$Flag)|+ } } - } __fn_bitflags! { /// Returns the raw value of the flags currently stored.
bd24f9d8d266bfb2dfe4b8238b196ecf5e37dee1
bitflags/bitflags
from_bits accepts non existing flags ```rs #[test] fn test_from_bits_edge_cases() { bitflags! { struct Flags: u8 { const A = 0b00000001; const BC = 0b00000110; } } let flags = Flags::from_bits(0b00000100); assert!(flags.is_none()); } ``` Unless I'm missing something this test should pass but it fails cause from_bits accepts flags that are not declared. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6fd4adbddc8b8740cbd35af2306073ca This is related to this issue in the implementation of iterators in this PR https://github.com/bitflags/bitflags/pull/204#issuecomment-950304444 Using `from_bits` instead of `from_bits_unchecked` should allow to produce any valid flags that are not a combination of other flags but at the moment `from_bits` seems to accept any flag that is included in a combination even if it's not declared. I can try to send a PR.
bitflags__bitflags-276
[ "275" ]
0141a07e55184304857384b0093d00959f0acfa6
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1891,6 +1907,37 @@ mod tests { } } + #[test] + fn test_from_bits_edge_cases() { + bitflags! { + 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! { + 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! { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1924,22 +1971,4 @@ mod tests { assert_eq!(iter.next().unwrap(), Flags::THREE); assert_eq!(iter.next(), None); } - - #[test] - fn test_iter_edge_cases() { - bitflags! { - struct Flags: u8 { - const A = 0b00000001; - const BC = 0b00000110; - } - } - - - let flags = Flags::all(); - assert_eq!(flags.iter().count(), 2); - let mut iter = flags.iter(); - assert_eq!(iter.next().unwrap(), Flags::A); - assert_eq!(iter.next().unwrap(), Flags::BC); - assert_eq!(iter.next(), None); - } } diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr.beta b/tests/compile-fail/non_integer_base/all_defined.stderr.beta --- a/tests/compile-fail/non_integer_base/all_defined.stderr.beta +++ b/tests/compile-fail/non_integer_base/all_defined.stderr.beta @@ -49,8 +49,41 @@ error[E0308]: mismatched types = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) help: try wrapping the expression in `MyInt` | -562 | if (bits & !Self::all().bits()) == MyInt(0) { - | ++++++ + +574 | if bits == MyInt(0) { + | ++++++ + + +error[E0277]: no implementation for `{integer} |= MyInt` + --> $DIR/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ no implementation for `{integer} |= MyInt` + | + = help: the trait `BitOrAssign<MyInt>` is not implemented for `{integer}` + = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0308]: mismatched types + --> $DIR/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ expected struct `MyInt`, found integer + | + = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) +help: try wrapping the expression in `MyInt` + | +589 | Self { bits: MyInt(truncated) } + | ++++++ + error[E0308]: mismatched types --> $DIR/all_defined.rs:115:1
1.3
276
2022-04-19T09:54:30Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -559,10 +559,11 @@ macro_rules! __impl_bitflags { /// representation contains bits that do not correspond to a flag. #[inline] pub const fn from_bits(bits: $T) -> $crate::_core::option::Option<Self> { - if (bits & !Self::all().bits()) == 0 { - $crate::_core::option::Option::Some(Self { bits }) + let truncated = Self::from_bits_truncate(bits).bits; + if truncated == bits { + Some(Self{ bits }) } else { - $crate::_core::option::Option::None + None } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -570,7 +571,22 @@ macro_rules! __impl_bitflags { /// that do not correspond to flags. #[inline] pub const fn from_bits_truncate(bits: $T) -> Self { - Self { bits: bits & Self::all().bits } + if bits == 0 { + return Self{ bits } + } + + #[allow(unused_mut)] + let mut truncated = 0; + + $( + #[allow(unused_doc_comments, unused_attributes)] + $(#[$attr $($args)*])* + if bits & Self::$Flag.bits == Self::$Flag.bits { + truncated |= Self::$Flag.bits + } + )* + + Self { bits: truncated } } /// Convert from underlying bit representation, preserving all
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
`cargo build --test` fails on Windows [One of the tests](https://github.com/bitflags/bitflags/blob/8a10bdc144bb2a4b97c63cfa76be90228954d029/src/lib.rs#L920) for `bitflags-1.1.0` fails to compile on Windows with a stable rustc (version 1.36.0). ``` [INFO] [stderr] error[E0425]: cannot find value `_CFG_A` in this scope [INFO] [stderr] --> src\lib.rs:927:28 [INFO] [stderr] | [INFO] [stderr] 927 | const _CFG_C = _CFG_A.bits | 0b10; [INFO] [stderr] | ^^^^^^ not found in this scope [INFO] [stderr] [INFO] [stderr] error: aborting due to previous error ``` This suggests that `#[cfg]` attributes are not being properly added to `const` declarations, but I'm not quite sure exactly what's going on here.
Thanks for the report @ecstatic-morse! I'm not in front of my Windows box right now, but will look into this when I am, unless somebody else checks it first. I would guess that swapping `#[cfg(unix)]` and `#[cfg(windows)]` in that test will result in a failure on *nix. Btw, this arose while testing out `crater` runs on Windows. I'm guessing this test was a holdover from before `bitflags` used associated consts? Should be `Self::_CFG_A`. This test should probably just be rewritten though.
bitflags__bitflags-186
[ "185" ]
8a10bdc144bb2a4b97c63cfa76be90228954d029
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1111,7 +1111,7 @@ mod tests { #[cfg(bitflags_const_fn)] #[test] fn test_const_fn() { - const M1: Flags = Flags::empty(); + const _M1: Flags = Flags::empty(); const M2: Flags = Flags::A; assert_eq!(M2, Flags::A);
1.1
186
2019-07-20T12:27:25Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -919,12 +919,12 @@ mod tests { bitflags! { struct _CfgFlags: u32 { - #[cfg(windows)] - const _CFG_A = 0b01; #[cfg(unix)] - const _CFG_B = 0b01; + const _CFG_A = 0b01; #[cfg(windows)] - const _CFG_C = _CFG_A.bits | 0b10; + const _CFG_B = 0b01; + #[cfg(unix)] + const _CFG_C = Self::_CFG_A.bits | 0b10; } }
8a10bdc144bb2a4b97c63cfa76be90228954d029
bitflags/bitflags
Bitflags values of zero are considered always present When a bitflag is built with a zero valued item then it is treated as always present by bitflags functions. This may cause bugs but it definitely causes confusion when printing such a value. See the following for an example: ``` #[macro_use] extern crate bitflags; bitflags! { struct Flags: u32 { const NONE = 0b0; const SOME = 0b1; } } fn main() { let none = Flags::NONE; let some = Flags::SOME; println!("NONE = {:?}", none); println!("SOME = {:?}", some); assert!(some.contains(Flags::NONE)); } ``` Results in an output of: ``` NONE = NONE SOME = NONE | SOME ``` I noticed this when printing some flags from git2, specifically [MergeAnalysis](https://docs.rs/git2/0.7.1/git2/struct.MergeAnalysis.html). The output of a `format("{:?}", flag)` ended up being "(ANALYSIS_NONE | ANALYSIS_NORMAL | ANALYSIS_FASTFORWARD)" which confused me greatly. ANALYSIS_NONE is zero as that is how it is defined in [git2](https://github.com/libgit2/libgit2/blob/HEAD/include/git2/merge.h#L320) It seems to me that way that flag is intended to be used is that NONE only shows up when there are no other things to set, or maybe as a placeholder and should only appear when nothing else is set.
I agree, a zero value should only show up in Debug output if no bits are set. Would you be interested in sending a PR to fix this? I would definitely be interested in doing so, where should I start? The Debug impls are constructed [here](https://github.com/rust-lang-nursery/bitflags/blob/1.0.2/src/lib.rs#L401). After looking some more at the code I think this is more involved than I thought. With the code considering empty flags as always present I think that changing just the debug output will make for bugs that are even more difficult to track down. For example `some.contains(Flags::NONE)` is always true in my example above, but if we remove it from the debug it will be more difficult to realise this is happening. At least `none.is_empty()` behaves correctly. In any case, I am happy to add this special case if I can also add to the documentation an explanation of zero flags.
bitflags__bitflags-157
[ "151" ]
74aa397b0e6899c8b5131da34351e7d87d247038
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1157,4 +1191,22 @@ mod tests { assert_eq!(module::value(), 1) } + + #[test] + fn test_zero_value_flags() { + bitflags! { + 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::empty()), "NONE"); + assert_eq!(format!("{:?}", Flags::SOME), "SOME"); + } }
1.0
157
2018-04-30T12:18:19Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -215,6 +215,36 @@ //! assert_eq!(implemented_default, (Flags::A | Flags::C)); //! } //! ``` +//! +//! # Zero Flags +//! +//! Flags with a value equal to zero will have some strange behavior that one should be aware of. +//! +//! ``` +//! #[macro_use] +//! extern crate bitflags; +//! +//! bitflags! { +//! struct Flags: u32 { +//! const NONE = 0b00000000; +//! const SOME = 0b00000001; +//! } +//! } +//! +//! fn main() { +//! let empty = Flags::empty(); +//! let none = Flags::NONE; +//! let some = Flags::SOME; +//! +//! // Zero flags are treated as always present +//! assert!(empty.contains(Flags::NONE)); +//! assert!(none.contains(Flags::NONE)); +//! assert!(some.contains(Flags::NONE)); +//! +//! // Zero flags will be ignored when testing for emptiness +//! assert!(none.is_empty()); +//! } +//! ``` #![no_std] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -424,7 +454,11 @@ macro_rules! __impl_bitflags { #[inline] $(? #[$attr $($args)*])* fn $Flag(&self) -> bool { - self.bits & Self::$Flag.bits == Self::$Flag.bits + if Self::$Flag.bits == 0 && self.bits != 0 { + false + } else { + self.bits & Self::$Flag.bits == Self::$Flag.bits + } } } )+
74aa397b0e6899c8b5131da34351e7d87d247038
bitflags/bitflags
pub(restricted) bitflags cc https://github.com/rust-lang/rust/issues/32409 - maybe no action is warranted until this feature is stable. ```rust bitflags! { pub(super) flags Flags: u8 { const A = 1 } } ```
pub(restricted) is now stable. But I think it is still blocked by `:vis` matcher (rust-lang/rust#41022) to allow a proper fix. ---- Currently the straightforward fix using `:vis` causes an error in `example_generated.rs` ```rust error: local ambiguity: multiple parsing options: built-in NTs vis ('vis') or 1 other option. --> src/example_generated.rs:5:5 | 4 | / bitflags! { 5 | | /// This is the same `Flags` struct defined in the [crate level example](../index.html#example). | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 6 | | /// Note that this struct is just for documentation purposes only, it must not be used outside 7 | | /// this crate. ... | 15 | | } 16 | | } | |_- in this macro invocation error: Could not compile `bitflags`. ``` <details><summary>(diff)</summary> ```diff diff --git a/src/lib.rs b/src/lib.rs index 1694837..356fba1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(macro_vis_matcher)] + //! A typesafe bitmask flag generator useful for sets of C-style bitmask flags. //! It can be used for creating typesafe wrappers around C APIs. //! @@ -305,16 +307,16 @@ pub extern crate core as _core; /// ``` #[macro_export] macro_rules! bitflags { - ($(#[$attr:meta])* pub struct $BitFlags:ident: $T:ty { + ($(#[$attr:meta])* $vis:vis struct $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ }) => { #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] $(#[$attr])* - pub struct $BitFlags { + $vis struct $BitFlags { bits: $T, } - $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + $($(#[$Flag_attr])* $vis const $Flag: $BitFlags = $BitFlags { bits: $value };)+ __impl_bitflags! { struct $BitFlags: $T { @@ -322,24 +324,6 @@ macro_rules! bitflags { } } }; - ($(#[$attr:meta])* struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ - }) => { - #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] - $(#[$attr])* - struct $BitFlags { - bits: $T, - } - - $($(#[$Flag_attr])* const $Flag: $BitFlags = $BitFlags { bits: $value };)+ - - __impl_bitflags! { - struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value;)+ - } - } - - }; } ``` </details> It looks like using `:vis` here is unblocked now, right?
bitflags__bitflags-135
[ "72" ]
8e163c64ec3ce242a9fef0347c73a82f5ea84b90
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1092,4 +1111,46 @@ mod tests { } } } + + #[test] + fn test_pub_crate() { + mod module { + bitflags! { + 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. + 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 (in super) fn value() -> u8 { + super::submodule::Test::FOO.bits() + } + } + + pub fn value() -> u8 { + test::value() + } + } + + assert_eq!(module::value(), 1) + } }
1.0
135
2017-11-08T05:38:51Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -336,6 +336,25 @@ macro_rules! bitflags { } } }; + ( + $(#[$outer:meta])* + pub ($($vis:tt)+) struct $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )+ + } + ) => { + __bitflags! { + $(#[$outer])* + (pub ($($vis)+)) $BitFlags: $T { + $( + $(#[$inner $($args)*])* + $Flag = $value; + )+ + } + } + }; } #[macro_export]
74aa397b0e6899c8b5131da34351e7d87d247038
bitflags/bitflags
Bitflags reverses order of multiline doc comments When compiling code like ``` bitflags! { pub struct AdjustFlags: u32 { /// Add buf.time to the current time. If buf.status includes the ADJ_NANO flag, then buf.time.tv_usec is interpreted as a nanosecond value; /// otherwise it is interpreted as microseconds. /// /// The value of buf.time is the sum of its two fields, but the field buf.time.tv_usec must always be nonnegative. /// The following example shows how to normalize a timeval with nanosecond resolution. /// /// ```C /// while (buf.time.tv_usec < 0) { /// buf.time.tv_sec -= 1; /// buf.time.tv_usec += 1000000000; /// } /// ``` const SETOFFSET = libc::ADJ_SETOFFSET; } } ``` The doc-comments order is reversed on compile, causing issues with generated docs and the doctest. This bug only occurs on bitflags 2.2.0 and not on earlier versions
This should be trivially fixed by swapping the order attributes are "pushed" in `__declare_bitflags`. We've already yanked `2.2.0` because it requires a lot more recursion, but will keep this open to make sure any new approach doesn't reverse the order of attributes.
bitflags__bitflags-345
[ "344" ]
cbcafa710fc31172511e62efa06ad9eb214e4734
diff --git /dev/null b/tests/compile-pass/large.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/large.rs @@ -0,0 +1,311 @@ +/* +Copyright (c) 2016 Anatoly Ikorsky + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + +#[macro_use] +extern crate bitflags; + +bitflags! { + /// Client capability flags + #[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)] + pub struct CapabilityFlags: u32 { + /// Use the improved version of Old Password Authentication. Assumed to be set since 4.1.1. + const CLIENT_LONG_PASSWORD = 0x0000_0001; + + /// Send found rows instead of affected rows in EOF_Packet. + const CLIENT_FOUND_ROWS = 0x0000_0002; + + /// Get all column flags. + /// Longer flags in Protocol::ColumnDefinition320. + /// + /// ### Server + /// Supports longer flags. + /// + /// ### Client + /// Expects longer flags. + const CLIENT_LONG_FLAG = 0x0000_0004; + + /// Database (schema) name can be specified on connect in Handshake Response Packet. + /// ### Server + /// Supports schema-name in Handshake Response Packet. + /// + /// ### Client + /// Handshake Response Packet contains a schema-name. + const CLIENT_CONNECT_WITH_DB = 0x0000_0008; + + /// Don't allow database.table.column. + const CLIENT_NO_SCHEMA = 0x0000_0010; + + /// Compression protocol supported. + /// + /// ### Server + /// Supports compression. + /// + /// ### Client + /// Switches to Compression compressed protocol after successful authentication. + const CLIENT_COMPRESS = 0x0000_0020; + + /// Special handling of ODBC behavior. + const CLIENT_ODBC = 0x0000_0040; + + /// Can use LOAD DATA LOCAL. + /// + /// ### Server + /// Enables the LOCAL INFILE request of LOAD DATA|XML. + /// + /// ### Client + /// Will handle LOCAL INFILE request. + const CLIENT_LOCAL_FILES = 0x0000_0080; + + /// Ignore spaces before '('. + /// + /// ### Server + /// Parser can ignore spaces before '('. + /// + /// ### Client + /// Let the parser ignore spaces before '('. + const CLIENT_IGNORE_SPACE = 0x0000_0100; + + const CLIENT_PROTOCOL_41 = 0x0000_0200; + + /// This is an interactive client. + /// Use System_variables::net_wait_timeout versus System_variables::net_interactive_timeout. + /// + /// ### Server + /// Supports interactive and noninteractive clients. + /// + /// ### Client + /// Client is interactive. + const CLIENT_INTERACTIVE = 0x0000_0400; + + /// Use SSL encryption for the session. + /// + /// ### Server + /// Supports SSL + /// + /// ### Client + /// Switch to SSL after sending the capability-flags. + const CLIENT_SSL = 0x0000_0800; + + /// Client only flag. Not used. + /// + /// ### Client + /// Do not issue SIGPIPE if network failures occur (libmysqlclient only). + const CLIENT_IGNORE_SIGPIPE = 0x0000_1000; + + /// Client knows about transactions. + /// + /// ### Server + /// Can send status flags in OK_Packet / EOF_Packet. + /// + /// ### Client + /// Expects status flags in OK_Packet / EOF_Packet. + /// + /// ### Note + /// This flag is optional in 3.23, but always set by the server since 4.0. + const CLIENT_TRANSACTIONS = 0x0000_2000; + + const CLIENT_RESERVED = 0x0000_4000; + + const CLIENT_SECURE_CONNECTION = 0x0000_8000; + + /// Enable/disable multi-stmt support. + /// Also sets CLIENT_MULTI_RESULTS. Currently not checked anywhere. + /// + /// ### Server + /// Can handle multiple statements per COM_QUERY and COM_STMT_PREPARE. + /// + /// ### Client + /// May send multiple statements per COM_QUERY and COM_STMT_PREPARE. + const CLIENT_MULTI_STATEMENTS = 0x0001_0000; + + /// Enable/disable multi-results. + /// + /// ### Server + /// Can send multiple resultsets for COM_QUERY. Error if the server needs to send + /// them and client does not support them. + /// + /// ### Client + /// Can handle multiple resultsets for COM_QUERY. + /// + /// ### Requires + /// `CLIENT_PROTOCOL_41` + const CLIENT_MULTI_RESULTS = 0x0002_0000; + + /// Multi-results and OUT parameters in PS-protocol. + /// + /// ### Server + /// Can send multiple resultsets for COM_STMT_EXECUTE. + /// + /// ### Client + /// Can handle multiple resultsets for COM_STMT_EXECUTE. + /// + /// ### Requires + /// `CLIENT_PROTOCOL_41` + const CLIENT_PS_MULTI_RESULTS = 0x0004_0000; + + /// Client supports plugin authentication. + /// + /// ### Server + /// Sends extra data in Initial Handshake Packet and supports the pluggable + /// authentication protocol. + /// + /// ### Client + /// Supports authentication plugins. + /// + /// ### Requires + /// `CLIENT_PROTOCOL_41` + const CLIENT_PLUGIN_AUTH = 0x0008_0000; + + /// Client supports connection attributes. + /// + /// ### Server + /// Permits connection attributes in Protocol::HandshakeResponse41. + /// + /// ### Client + /// Sends connection attributes in Protocol::HandshakeResponse41. + const CLIENT_CONNECT_ATTRS = 0x0010_0000; + + /// Enable authentication response packet to be larger than 255 bytes. + /// When the ability to change default plugin require that the initial password + /// field in the Protocol::HandshakeResponse41 paclet can be of arbitrary size. + /// However, the 4.1 client-server protocol limits the length of the auth-data-field + /// sent from client to server to 255 bytes. The solution is to change the type of + /// the field to a true length encoded string and indicate the protocol change with + /// this client capability flag. + /// + /// ### Server + /// Understands length-encoded integer for auth response data in + /// Protocol::HandshakeResponse41. + /// + /// ### Client + /// Length of auth response data in Protocol::HandshakeResponse41 is a + /// length-encoded integer. + /// + /// ### Note + /// The flag was introduced in 5.6.6, but had the wrong value. + const CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x0020_0000; + + /// Don't close the connection for a user account with expired password. + /// + /// ### Server + /// Announces support for expired password extension. + /// + /// ### Client + /// Can handle expired passwords. + const CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS = 0x0040_0000; + + /// Capable of handling server state change information. + /// Its a hint to the server to include the state change information in OK_Packet. + /// + /// ### Server + /// Can set SERVER_SESSION_STATE_CHANGED in the SERVER_STATUS_flags_enum and send + /// Session State Information in a OK_Packet. + /// + /// ### Client + /// Expects the server to send Session State Information in a OK_Packet. + const CLIENT_SESSION_TRACK = 0x0080_0000; + + /// Client no longer needs EOF_Packet and will use OK_Packet instead. + /// + /// ### Server + /// Can send OK after a Text Resultset. + /// + /// ### Client + /// Expects an OK_Packet (instead of EOF_Packet) after the resultset + /// rows of a Text Resultset. + /// + /// ### Background + /// To support CLIENT_SESSION_TRACK, additional information must be sent after all + /// successful commands. Although the OK_Packet is extensible, the EOF_Packet is + /// not due to the overlap of its bytes with the content of the Text Resultset Row. + /// + /// Therefore, the EOF_Packet in the Text Resultset is replaced with an OK_Packet. + /// EOF_Packet is deprecated as of MySQL 5.7.5. + const CLIENT_DEPRECATE_EOF = 0x0100_0000; + + /// The client can handle optional metadata information in the resultset. + const CLIENT_OPTIONAL_RESULTSET_METADATA = 0x0200_0000; + + /// Compression protocol extended to support zstd compression method. + /// + /// This capability flag is used to send zstd compression level between client and server + /// provided both client and server are enabled with this flag. + /// + /// # Server + /// + /// Server sets this flag when global variable protocol-compression-algorithms has zstd + /// in its list of supported values. + /// + /// # Client + /// + /// Client sets this flag when it is configured to use zstd compression method. + const CLIENT_ZSTD_COMPRESSION_ALGORITHM = 0x0400_0000; + + /// Support optional extension for query parameters into the COM_QUERY + /// and COM_STMT_EXECUTE packets. + /// + /// # Server + /// + /// Expects an optional part containing the query parameter set(s). + /// Executes the query for each set of parameters or returns an error if more than 1 set + /// of parameters is sent and the server can't execute it. + /// + /// # Client + /// + /// Can send the optional part containing the query parameter set(s). + const CLIENT_QUERY_ATTRIBUTES = 0x0800_0000; + + /// Support Multi factor authentication. + /// + /// # Server + /// + /// Server sends AuthNextFactor packet after every nth factor + /// authentication method succeeds, except the last factor authentication. + /// + /// # Client + /// + /// Client reads AuthNextFactor packet sent by server + /// and initiates next factor authentication method. + const MULTI_FACTOR_AUTHENTICATION = 0x1000_0000; + + /// Client or server supports progress reports within error packet. + const CLIENT_PROGRESS_OBSOLETE = 0x2000_0000; + + /// Verify server certificate. Client only flag. + /// + /// Deprecated in favor of –ssl-mode. + const CLIENT_SSL_VERIFY_SERVER_CERT = 0x4000_0000; + + /// Don't reset the options after an unsuccessful connect. Client only flag. + const CLIENT_REMEMBER_OPTIONS = 0x8000_0000; + } +} + +fn main() { + +}
2.2
345
2023-04-24T04:29:26Z
diff --git a/src/example_generated.rs b/src/example_generated.rs --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -33,8 +33,17 @@ __impl_public_bitflags! { __impl_public_bitflags_consts! { Flags { + /// Field `A`. + /// + /// This flag has the value `0b00000001`. A = 0b00000001; + /// Field `B`. + /// + /// This flag has the value `0b00000010`. B = 0b00000010; + /// Field `C`. + /// + /// This flag has the value `0b00000100`. C = 0b00000100; ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -224,10 +224,14 @@ macro_rules! __impl_internal_bitflags { let mut truncated = <$T as $crate::__private::Bits>::EMPTY; $( - $(#[$attr $($args)*])* - if bits & $BitFlags::$Flag.bits() == $BitFlags::$Flag.bits() { - truncated |= $BitFlags::$Flag.bits() - } + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + if bits & $BitFlags::$Flag.bits() == $BitFlags::$Flag.bits() { + truncated |= $BitFlags::$Flag.bits() + } + } + ); )* Self { bits: truncated } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -240,13 +244,19 @@ macro_rules! __impl_internal_bitflags { #[inline] pub fn from_name(name: &str) -> $crate::__private::core::option::Option<Self> { - match name { - $( + $( + __expr_safe_flags!( $(#[$attr $($args)*])* - $crate::__private::core::stringify!($Flag) => $crate::__private::core::option::Option::Some(Self { bits: $BitFlags::$Flag.bits() }), - )* - _ => $crate::__private::core::option::Option::None, - } + { + if name == $crate::__private::core::stringify!($Flag) { + return $crate::__private::core::option::Option::Some(Self { bits: $BitFlags::$Flag.bits() }); + } + } + ); + )* + + let _ = name; + $crate::__private::core::option::Option::None } #[inline] diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -384,10 +394,12 @@ macro_rules! __impl_internal_bitflags { let mut num_flags = 0; $( - $(#[$attr $($args)*])* - { - num_flags += 1; - } + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + { num_flags += 1; } + } + ); )* num_flags diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -395,15 +407,23 @@ macro_rules! __impl_internal_bitflags { const OPTIONS: [$T; NUM_FLAGS] = [ $( - $(#[$attr $($args)*])* - $BitFlags::$Flag.bits(), + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + $BitFlags::$Flag.bits() + } + ), )* ]; const OPTIONS_NAMES: [&'static str; NUM_FLAGS] = [ $( - $(#[$attr $($args)*])* - $crate::__private::core::stringify!($Flag), + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + $crate::__private::core::stringify!($Flag) + } + ), )* ]; diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -439,3 +459,112 @@ macro_rules! __impl_internal_bitflags { } }; } + +/// A macro that processed the input to `bitflags!` and shuffles attributes around +/// based on whether or not they're "expression-safe". +/// +/// This macro is a token-tree muncher that works on 2 levels: +/// +/// For each attribute, we explicitly match on its identifier, like `cfg` to determine +/// whether or not it should be considered expression-safe. +/// +/// If you find yourself with an attribute that should be considered expression-safe +/// and isn't, it can be added here. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __expr_safe_flags { + // Entrypoint: Move all flags and all attributes into `unprocessed` lists + // where they'll be munched one-at-a-time + ( + $(#[$inner:ident $($args:tt)*])* + { $e:expr } + ) => { + __expr_safe_flags! { + expr: { $e }, + attrs: { + // All attributes start here + unprocessed: [$(#[$inner $($args)*])*], + processed: { + // Attributes that are safe on expressions go here + expr: [], + }, + }, + } + }; + // Process the next attribute on the current flag + // `cfg`: The next flag should be propagated to expressions + // NOTE: You can copy this rules block and replace `cfg` with + // your attribute name that should be considered expression-safe + ( + expr: { $e:expr }, + attrs: { + unprocessed: [ + // cfg matched here + #[cfg $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + expr: [$($expr:tt)*], + }, + }, + ) => { + __expr_safe_flags! { + expr: { $e }, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + expr: [ + $($expr)* + // cfg added here + #[cfg $($args)*] + ], + }, + }, + } + }; + // Process the next attribute on the current flag + // `$other`: The next flag should not be propagated to expressions + ( + expr: { $e:expr }, + attrs: { + unprocessed: [ + // $other matched here + #[$other:ident $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + expr: [$($expr:tt)*], + }, + }, + ) => { + __expr_safe_flags! { + expr: { $e }, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + expr: [ + // $other not added here + $($expr)* + ], + }, + }, + } + }; + // Once all attributes on all flags are processed, generate the actual code + ( + expr: { $e:expr }, + attrs: { + unprocessed: [], + processed: { + expr: [$(#[$expr:ident $($exprargs:tt)*])*], + }, + }, + ) => { + $(#[$expr $($exprargs)*])* + { $e } + } +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -558,315 +558,6 @@ macro_rules! bitflags { } $($t:tt)* - ) => { - __declare_bitflags!( - $(#[$outer])* - $vis struct $BitFlags: $T { - $( - $(#[$inner $($args)*])* - const $Flag = $value; - )* - } - ); - - bitflags! { - $($t)* - } - }; - () => {}; -} - -/// A macro that processed the input to `bitflags!` and shuffles attributes around -/// based on whether or not they're "expression-safe". -/// -/// This macro is a token-tree muncher that works on 2 levels: -/// -/// 1. Each flag, like `#[cfg(true)] const A: 42` -/// 2. Each attribute on that flag, like `#[cfg(true)]` -/// -/// Flags and attributes start in an "unprocessed" list, and are shifted one token -/// at a time into an appropriate processed list until the unprocessed lists are empty. -/// -/// For each attribute, we explicitly match on its identifier, like `cfg` to determine -/// whether or not it should be considered expression-safe. -/// -/// If you find yourself with an attribute that should be considered expression-safe -/// and isn't, it can be added here. -#[macro_export(local_inner_macros)] -#[doc(hidden)] -macro_rules! __declare_bitflags { - // Entrypoint: Move all flags and all attributes into `unprocessed` lists - // where they'll be munched one-at-a-time - ( - $(#[$outer:meta])* - $vis:vis struct $BitFlags:ident: $T:ty { - $( - $(#[$inner:ident $($args:tt)*])* - const $Flag:ident = $value:expr; - )* - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - // All flags start here - unprocessed: [ - $( - { - ident: $Flag, - value: $value, - attrs: { - // All attributes start here - unprocessed: [$(#[$inner $($args)*])*], - processed: { - // Attributes that should be added to item declarations go here - decl: [], - // Attributes that are safe on expressions go here - expr: [], - } - }, - }, - )* - ], - // Flags that have had their attributes sorted are pushed here - processed: [], - } - } - }; - // Process the next attribute on the current flag - // `cfg`: The next flag should be propagated to expressions - // NOTE: You can copy this rules block and replace `cfg` with - // your attribute name that should be considered expression-safe - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [ - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [ - // cfg matched here - #[cfg $($args:tt)*] - $($attrs_rest:tt)* - ], - processed: { - decl: [$($decl:tt)*], - expr: [$($expr:tt)*], - } - }, - }, - $($flags_rest:tt)* - ], - processed: [ - $($flags:tt)* - ], - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - unprocessed: [ - { - ident: $Flag, - value: $value, - attrs: { - unprocessed: [ - $($attrs_rest)* - ], - processed: { - decl: [ - // cfg added here - #[cfg $($args)*] - $($decl)* - ], - expr: [ - // cfg added here - #[cfg $($args)*] - $($expr)* - ], - } - }, - }, - $($flags_rest)* - ], - processed: [ - $($flags)* - ], - } - } - }; - // Process the next attribute on the current flag - // `$other`: The next flag should not be propagated to expressions - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [ - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [ - // $other matched here - #[$other:ident $($args:tt)*] - $($attrs_rest:tt)* - ], - processed: { - decl: [$($decl:tt)*], - expr: [$($expr:tt)*], - } - }, - }, - $($flags_rest:tt)* - ], - processed: [ - $($flags:tt)* - ], - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - unprocessed: [ - { - ident: $Flag, - value: $value, - attrs: { - unprocessed: [ - $($attrs_rest)* - ], - processed: { - decl: [ - // $other added here - #[$other $($args)*] - $($decl)* - ], - expr: [ - // $other not added here - $($expr)* - ], - } - }, - }, - $($flags_rest)* - ], - processed: [ - $($flags)* - ], - } - } - }; - // Complete the current flag once there are no unprocessed attributes left - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [ - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [], - processed: { - decl: [$($decl:tt)*], - expr: [$($expr:tt)*], - } - }, - }, - $($flags_rest:tt)* - ], - processed: [ - $($flags:tt)* - ], - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - unprocessed: [ - $($flags_rest)* - ], - processed: [ - $($flags)* - { - ident: $Flag, - value: $value, - attrs: { - unprocessed: [], - processed: { - decl: [ - $($decl)* - ], - expr: [ - $($expr)* - ], - } - }, - }, - ], - } - } - }; - // Once all attributes on all flags are processed, generate the actual code - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [], - processed: [ - $( - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [], - processed: { - decl: [$(#[$decl:ident $($declargs:tt)*])*], - expr: [$(#[$expr:ident $($exprargs:tt)*])*], - } - }, - }, - )* - ], - } ) => { // Declared in the scope of the `bitflags!` call // This type appears in the end-user's API diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -879,7 +570,7 @@ macro_rules! __declare_bitflags { __impl_public_bitflags_consts! { $BitFlags { $( - $(#[$decl $($declargs)*])* + $(#[$inner $($args)*])* #[allow( dead_code, deprecated, diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -912,7 +603,7 @@ macro_rules! __declare_bitflags { __impl_internal_bitflags! { InternalBitFlags: $T, $BitFlags, Iter, IterRaw { $( - $(#[$expr $($exprargs)*])* + $(#[$inner $($args)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -922,7 +613,7 @@ macro_rules! __declare_bitflags { __impl_external_bitflags! { InternalBitFlags: $T { $( - $(#[$expr $($exprargs)*])* + $(#[$inner $($args)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -932,7 +623,12 @@ macro_rules! __declare_bitflags { $BitFlags: $T, InternalBitFlags, Iter, IterRaw; } }; - } + + bitflags! { + $($t)* + } + }; + () => {}; } #[macro_use]
cbcafa710fc31172511e62efa06ad9eb214e4734
bitflags/bitflags
serde support Are there any plans to support `Serialize` and `Deserialize` for generated types? I'm writing the impls manually in my code, but this falls apart once there's a ton of `bitflags` generated types. If others are interested in such a feature, maybe I can find the time to implement it myself and submit a pull request :)
During the libs blitz evaluation we saw that a grand total of 8 crates have dependencies on both bitflags and Serde, so we decided not to pursue it at the time. I would welcome a PR that adds Serialize and Deserialize impls behind a cfg. Adding `#[derive(Serialize, Deserialize)]` to the struct seems to work fine, I'm not sure it's really necessary to add this to the library itself.
bitflags__bitflags-125
[ "108" ]
29e60b23708123121a540fa9bde3254260952511
diff --git /dev/null b/tests/serde.rs new file mode 100644 --- /dev/null +++ b/tests/serde.rs @@ -0,0 +1,35 @@ +#[macro_use] +extern crate bitflags; + +#[macro_use] +extern crate serde_derive; +extern crate serde; +extern crate serde_json; + +bitflags! { + #[derive(Serialize, Deserialize)] + struct Flags: u32 { + const A = 1; + const B = 2; + const C = 4; + const D = 8; + } +} + +#[test] +fn serialize() { + let flags = Flags::A | Flags::B; + + let serialized = serde_json::to_string(&flags).unwrap(); + + assert_eq!(serialized, r#"{"bits":3}"#); +} + +#[test] +fn deserialize() { + let deserialized: Flags = serde_json::from_str(r#"{"bits":12}"#).unwrap(); + + let expected = Flags::C | Flags::D; + + assert_eq!(deserialized.bits, expected.bits); +}
1.0
125
2017-10-11T15:27:55Z
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -28,5 +28,8 @@ example_generated = [] [dev-dependencies] # Trick Cargo into testing this crate when we run `cargo test --all`. bitflags-compiletest = { path = "compiletest" } +serde = "1.0" +serde_derive = "1.0" +serde_json = "1.0" [workspace]
74aa397b0e6899c8b5131da34351e7d87d247038
bitflags/bitflags
is_all() vs. from_bits_unchecked() [`unsafe from_bits_unchecked()`](https://docs.rs/bitflags/1.2.1/bitflags/example_generated/struct.Flags.html#method.from_bits_unchecked) allows creating instances with extra bits. The caller of the `bitflags!` macro can decide if this is allowed for their type. Let's assume it is for `Example`. I checked the provided methods for surprising interactions with extra bits, and found (only) this: `is_all()` returns **false** when there are *more* than "all" flags. This does not match the documentation: > Returns true if all flags are currently set. Should we update the documentation or the implementation? --- ```rust use bitflags::bitflags; bitflags! { struct Example: u32 { const A = 1; } } fn main() { unsafe { assert!(Example::from_bits_unchecked(1).is_all()); // true assert!(Example::from_bits_unchecked(3).is_all()); // false } } ``` https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cda2672387dd0ff4ba629b1317a9c57c
bitflags__bitflags-211
[ "208" ]
15e911c304d5bd8805af55d7e4f8c5324ed798ee
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1048,6 +1048,11 @@ mod tests { assert!(!Flags::A.is_all()); assert!(Flags::ABC.is_all()); + let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + assert!(!extra.is_all()); + assert!(!(Flags::A | extra).is_all()); + assert!((Flags::ABC | extra).is_all()); + assert!(AnotherSetOfFlags::ANOTHER_FLAG.is_all()); }
1.2
211
2020-02-04T10:52:16Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -664,7 +664,7 @@ macro_rules! __impl_bitflags { /// Returns `true` if all flags are currently set. #[inline] pub const fn is_all(&self) -> bool { - self.bits == $BitFlags::all().bits + $BitFlags::all().bits | self.bits == self.bits } }
bd24f9d8d266bfb2dfe4b8238b196ecf5e37dee1
bitflags/bitflags
Create a test suite crate #61 adds an `unstable_testing` feature that is only considered by tests. It seems unfortunate to leak this into the public API. Having a separate crate for tests ([like in Serde](https://github.com/serde-rs/serde/tree/master/test_suite)) would avoid this.
bitflags__bitflags-127
[ "68" ]
862582d107bb74ce4c7b505b2490eb815bc3a8c2
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -9,23 +10,14 @@ rust: - beta - nightly sudo: false -before_script: - - pip install -v 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - - if [[ -e ~/Library/Python/2.7/bin ]]; then export PATH=~/Library/Python/2.7/bin:$PATH; fi script: - - travis-cargo build - - travis-cargo test - - travis-cargo --only nightly test -- --all - - travis-cargo --only stable doc -after_success: - - travis-cargo --only nightly doc-upload + - cargo test + - if [ "$TRAVIS_RUST_VERSION" = nightly ]; then (cd ./test_suite && cargo test --features unstable); fi env: global: - - TRAVIS_CARGO_NIGHTLY_FEATURE=unstable_testing - secure: "DoZ8g8iPs+X3xEEucke0Ae02JbkQ1qd1SSv/L2aQqxULmREtRcbzRauhiT+ToQO5Ft1Lul8uck14nPfs4gMr/O3jFFBhEBVpSlbkJx7eNL3kwUdp95UNroA8I43xPN/nccJaHDN6TMTD3+uajTQTje2SyzOQP+1gvdKg17kguvE=" - notifications: email: on_success: never diff --git a/compiletest/tests/tests.rs /dev/null --- a/compiletest/tests/tests.rs +++ /dev/null @@ -1,30 +0,0 @@ -extern crate compiletest_rs as compiletest; - -use std::fs; -use std::path::PathBuf; -use compiletest::common::Mode; - -fn run_mode(mode: Mode) { - let config = compiletest::Config { - mode: mode, - src_base: PathBuf::from(format!("tests/{}", mode)), - target_rustcflags: fs::read_dir("../target/debug/deps").unwrap().filter_map(|entry| { - let path = entry.unwrap().path(); - path.file_name().map(|file_name| file_name.to_string_lossy()).and_then(|file_name| { - if file_name.starts_with("libbitflags-") && file_name.ends_with(".rlib") { - Some(format!("--extern bitflags={}", path.to_string_lossy())) - } else { - None - } - }) - }).next(), - ..Default::default() - }; - - compiletest::run_tests(&config); -} - -#[test] -fn compile_test() { - run_mode(Mode::CompileFail); -} diff --git /dev/null b/test_suite/Cargo.toml new file mode 100644 --- /dev/null +++ b/test_suite/Cargo.toml @@ -0,0 +1,13 @@ +[project] +name = "test_suite" +version = "0.0.0" + +[features] +unstable = ["compiletest_rs"] + +[dependencies] +bitflags = { path = "../" } +compiletest_rs = { version = "*", optional = true } +serde = "1.0" +serde_derive = "1.0" +serde_json = "1.0" diff --git /dev/null b/test_suite/tests/compiletest.rs new file mode 100644 --- /dev/null +++ b/test_suite/tests/compiletest.rs @@ -0,0 +1,32 @@ +#![cfg(feature = "unstable")] + +extern crate compiletest_rs as compiletest; + +use std::result::Result; +use std::fs; + +use compiletest::common::Mode; + +fn run_mode(mode: Mode) { + let config = compiletest::Config { + mode: mode, + src_base: format!("tests/{}", mode).into(), + target_rustcflags: fs::read_dir("target/debug/deps").unwrap().map(Result::unwrap).filter(|entry| { + let file_name = entry.file_name(); + let file_name = file_name.to_string_lossy(); + file_name.starts_with("libbitflags-") && file_name.ends_with(".rlib") + }).max_by_key(|entry| { + entry.metadata().unwrap().modified().unwrap() + }).map(|entry| { + format!("--extern bitflags={}", entry.path().to_string_lossy()) + }), + ..Default::default() + }; + + compiletest::run_tests(&config); +} + +#[test] +fn compile_test() { + run_mode(Mode::CompileFail); +} diff --git a/tests/i128_bitflags.rs b/test_suite/tests/i128_bitflags.rs --- a/tests/i128_bitflags.rs +++ b/test_suite/tests/i128_bitflags.rs @@ -1,4 +1,4 @@ -#![cfg(feature = "unstable_testing")] +#![cfg(feature = "unstable")] #![feature(i128_type)]
1.0
127
2017-10-17T16:27:59Z
diff --git a/.gitignore b/.gitignore --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -/target -/Cargo.lock +target +Cargo.lock diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,7 @@ os: - linux - osx language: rust +cache: cargo rust: # This version is tested to avoid unintentional bumping of the minimum supported Rust version - 1.20.0 diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -22,14 +22,4 @@ travis-ci = { repository = "rust-lang-nursery/bitflags" } [features] default = ["example_generated"] -unstable_testing = [] example_generated = [] - -[dev-dependencies] -# Trick Cargo into testing this crate when we run `cargo test --all`. -bitflags-compiletest = { path = "compiletest" } -serde = "1.0" -serde_derive = "1.0" -serde_json = "1.0" - -[workspace] diff --git a/compiletest/Cargo.toml /dev/null --- a/compiletest/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[project] -name = "bitflags-compiletest" -version = "0.0.0" - -[dev-dependencies] -bitflags = { path = "../" } -compiletest_rs = { version = "0.2" }
74aa397b0e6899c8b5131da34351e7d87d247038
bitflags/bitflags
Debug formatting leads to less desireable output [Link to rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=%23%5Bmacro_use%5D%0Aextern%20crate%20bitflags%3B%0A%0Abitflags!%20%7B%0A%20%20%20%20struct%20Flags%3A%20u32%20%7B%0A%20%20%20%20%20%20%20%20const%20A%20%3D%200b00000001%3B%0A%20%20%20%20%20%20%20%20const%20B%20%3D%200b00000010%3B%0A%20%20%20%20%20%20%20%20const%20C%20%3D%200b00000100%3B%0A%20%20%20%20%20%20%20%20const%20ABC%20%3D%20Self%3A%3AA.bits%20%7C%20Self%3A%3AB.bits%20%7C%20Self%3A%3AC.bits%3B%0A%20%20%20%20%7D%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20Flags%3A%3AA%20%7C%20Flags%3A%3AB%20%7C%20Flags%3A%3AC%20)%3B%0A%7D) ```rust #[macro_use] extern crate bitflags; bitflags! { struct Flags: u32 { const A = 0b00000001; const B = 0b00000010; const C = 0b00000100; const ABC = Self::A.bits | Self::B.bits | Self::C.bits; } } fn main() { println!("{:?}", Flags::A | Flags::B | Flags::C ); } ``` prints: ```bash A | B | C | ABC ``` I find it somewhat less helpful that both the expanded (`A | B | C`) and "compressed" form (`ABC`) are reported... Is there a reason behind this? Is this considered more correct for some reason?
I think the current algorithm used for debug output is to loop over all flags and append identifiers that correspond to set bits. I think an alternative here that could work would be to short-circuit when we’ve built a format that covers all the set bits. As an implementation note we wouldn’t be able to work off a single source and just mask out bits as we see them, we’ll need to use the whole set of bits to see if a flag is applicable and then a second set that’s masked to see when we’ve catered for all set bits. Otherwise something like this wouldn’t work: ``` const A: 0b00000100 const B: 0b00001100 let input = B; ``` we’d mask out bit 3 for `A` but then have one leftover for `B` that doesn’t correspond to it. In that example we’d end up writing `A | B` still, but wouldn’t duplicate compound identifiers the same. In general, I’m not sure if there’s a reasonable algorithm that would produce the smallest possible format for any given set of bits.
bitflags__bitflags-281
[ "215" ]
f38ce72d11ef3e264d4b62f360bd8a5597b916d9
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1353,7 +1321,10 @@ mod tests { 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)); + assert_eq!( + SYM_DIFFERENCE, + (Flags::A | Flags::C) ^ (Flags::all() - Flags::A) + ); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1609,13 +1580,15 @@ mod tests { assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); assert_eq!(format!("{:?}", Flags::empty()), "(empty)"); assert_eq!(format!("{:?}", Flags::ABC), "A | B | C"); + let extra = unsafe { Flags::from_bits_unchecked(0xb8) }; + assert_eq!(format!("{:?}", extra), "0xb8"); assert_eq!(format!("{:?}", Flags::A | extra), "A | 0xb8"); assert_eq!( format!("{:?}", Flags::ABC | extra), - "A | B | C | 0xb8" + "A | B | C | ABC | 0xb8" ); assert_eq!(format!("{:?}", EmptyFlags::empty()), "(empty)"); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1830,7 +1803,8 @@ mod tests { fn test_serde_bitflags_roundtrip() { let flags = SerdeFlags::A | SerdeFlags::B; - let deserialized: SerdeFlags = serde_json::from_str(&serde_json::to_string(&flags).unwrap()).unwrap(); + let deserialized: SerdeFlags = + serde_json::from_str(&serde_json::to_string(&flags).unwrap()).unwrap(); assert_eq!(deserialized.bits, flags.bits); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1875,7 +1848,7 @@ mod tests { let flags = Flags::from_bits_truncate(0b00000101); assert_eq!(flags, Flags::A); } - + #[test] fn test_iter() { bitflags! { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1887,24 +1860,31 @@ mod tests { const FOUR_WIN = 0b1000; #[cfg(unix)] const FOUR_UNIX = 0b10000; + const FIVE = 0b01000100; } } let count = { #[cfg(any(unix, windows))] { - 4 + 5 } #[cfg(not(any(unix, windows)))] { - 3 + 4 } }; let flags = Flags::all(); assert_eq!(flags.iter().count(), count); + + for (_, flag) in flags.iter() { + assert!(flags.contains(flag)); + } + let mut iter = flags.iter(); + assert_eq!(iter.next().unwrap(), ("ONE", Flags::ONE)); assert_eq!(iter.next().unwrap(), ("TWO", Flags::TWO)); assert_eq!(iter.next().unwrap(), ("THREE", Flags::THREE)); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1918,6 +1898,8 @@ mod tests { 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(); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1925,7 +1907,9 @@ mod tests { let flags = Flags::ONE | Flags::THREE; assert_eq!(flags.iter().count(), 2); + let mut iter = flags.iter(); + assert_eq!(iter.next().unwrap(), ("ONE", Flags::ONE)); assert_eq!(iter.next().unwrap(), ("THREE", Flags::THREE)); assert_eq!(iter.next(), None);
1.3
281
2022-05-03T06:59:46Z
diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -1,3 +1,5 @@ +use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not}; + #[doc(hidden)] pub trait ImplementedByBitFlagsMacro {} diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -5,7 +7,8 @@ pub trait ImplementedByBitFlagsMacro {} /// /// It should not be implemented manually. pub trait BitFlags: ImplementedByBitFlagsMacro { - type Bits; + type Bits: Bits; + /// Returns an empty set of flags. fn empty() -> Self; /// Returns the set containing all flags. diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -15,7 +18,8 @@ pub trait BitFlags: ImplementedByBitFlagsMacro { /// Convert from underlying bit representation, unless that /// representation contains bits that do not correspond to a flag. fn from_bits(bits: Self::Bits) -> Option<Self> - where Self: Sized; + where + Self: Sized; /// Convert from underlying bit representation, dropping any bits /// that do not correspond to flags. fn from_bits_truncate(bits: Self::Bits) -> Self; diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -48,3 +52,58 @@ pub trait BitFlags: ImplementedByBitFlagsMacro { /// Inserts or removes the specified flags depending on the passed value. fn set(&mut self, other: Self, value: bool); } + +// Not re-exported +pub trait Sealed {} + +/// A private trait that encodes the requirements of underlying bits types that can hold flags. +/// +/// This trait may be made public at some future point, but it presents a compatibility hazard +/// so is left internal for now. +#[doc(hidden)] +pub trait Bits: + Clone + + Copy + + BitAnd + + BitAndAssign + + BitOr + + BitOrAssign + + BitXor + + BitXorAssign + + Not + + Sized + + Sealed +{ + /// The value of `Self` where no bits are set. + const EMPTY: Self; + + /// The value of `Self` where all bits are set. + const ALL: Self; +} + +macro_rules! impl_bits { + ($($u:ty, $i:ty,)*) => { + $( + impl Bits for $u { + const EMPTY: $u = 0; + const ALL: $u = <$u>::MAX; + } + + impl Bits for $i { + const EMPTY: $i = 0; + const ALL: $i = <$u>::MAX as $i; + } + + impl Sealed for $u {} + impl Sealed for $i {} + )* + } +} + +impl_bits! { + u8, i8, + u16, i16, + u32, i32, + u64, i64, + u128, i128, +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -285,8 +285,8 @@ mod bitflags_trait; #[doc(hidden)] pub mod __private { + pub use crate::bitflags_trait::{Bits, ImplementedByBitFlagsMacro}; pub use core; - pub use crate::bitflags_trait::ImplementedByBitFlagsMacro; } /// The macro used to generate the flag structure. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -389,45 +389,6 @@ macro_rules! bitflags { () => {}; } -// A helper macro to implement the `all` function. -#[macro_export(local_inner_macros)] -#[doc(hidden)] -macro_rules! __impl_all_bitflags { - ( - $BitFlags:ident: $T:ty { - $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident = $value:expr; - )+ - } - ) => { - // See `Debug::fmt` for why this approach is taken. - #[allow(non_snake_case)] - trait __BitFlags { - $( - #[allow(deprecated)] - const $Flag: $T = 0; - )+ - } - #[allow(non_snake_case)] - impl __BitFlags for $BitFlags { - $( - __impl_bitflags! { - #[allow(deprecated)] - $(? #[$attr $($args)*])* - const $Flag: $T = Self::$Flag.bits; - } - )+ - } - Self { bits: $(<Self as __BitFlags>::$Flag)|+ } - }; - ( - $BitFlags:ident: $T:ty { } - ) => { - Self { bits: 0 } - }; -} - #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! __impl_bitflags { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -455,7 +416,7 @@ macro_rules! __impl_bitflags { // Append any extra bits that correspond to flags to the end of the format let extra_bits = self.bits & !Self::all().bits(); - if extra_bits != 0 { + if extra_bits != <$T as $crate::__private::Bits>::EMPTY { if !first { f.write_str(" | ")?; } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -495,7 +456,14 @@ macro_rules! __impl_bitflags { } } - #[allow(dead_code)] + #[allow( + dead_code, + deprecated, + unused_doc_comments, + unused_attributes, + unused_mut, + non_upper_case_globals + )] impl $BitFlags { $( $(#[$attr $($args)*])* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -505,20 +473,13 @@ macro_rules! __impl_bitflags { /// Returns an empty set of flags. #[inline] pub const fn empty() -> Self { - Self { bits: 0 } + Self { bits: <$T as $crate::__private::Bits>::EMPTY } } /// Returns the set containing all flags. #[inline] pub const fn all() -> Self { - __impl_all_bitflags! { - $BitFlags: $T { - $( - $(#[$attr $($args)*])* - $Flag = $value; - )* - } - } + Self::from_bits_truncate(<$T as $crate::__private::Bits>::ALL) } /// Returns the raw value of the flags currently stored. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -532,8 +493,9 @@ macro_rules! __impl_bitflags { #[inline] pub const fn from_bits(bits: $T) -> $crate::__private::core::option::Option<Self> { let truncated = Self::from_bits_truncate(bits).bits; + if truncated == bits { - $crate::__private::core::option::Option::Some(Self{ bits }) + $crate::__private::core::option::Option::Some(Self { bits }) } else { $crate::__private::core::option::Option::None } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -543,15 +505,13 @@ macro_rules! __impl_bitflags { /// that do not correspond to flags. #[inline] pub const fn from_bits_truncate(bits: $T) -> Self { - if bits == 0 { + if bits == <$T as $crate::__private::Bits>::EMPTY { return Self { bits } } - #[allow(unused_mut)] - let mut truncated = 0; + let mut truncated = <$T as $crate::__private::Bits>::EMPTY; $( - #[allow(unused_doc_comments, unused_attributes)] $(#[$attr $($args)*])* if bits & Self::$Flag.bits == Self::$Flag.bits { truncated |= Self::$Flag.bits diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -719,15 +679,13 @@ macro_rules! __impl_bitflags { } /// Returns an iterator over set flags and their names. - pub fn iter(mut self) -> impl $crate::__private::core::iter::Iterator<Item = (&'static str, Self)> { + pub fn iter(self) -> impl $crate::__private::core::iter::Iterator<Item = (&'static str, Self)> { use $crate::__private::core::iter::Iterator as _; const NUM_FLAGS: usize = { - #[allow(unused_mut)] let mut num_flags = 0; $( - #[allow(unused_doc_comments, unused_attributes)] $(#[$attr $($args)*])* { num_flags += 1; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -739,13 +697,11 @@ macro_rules! __impl_bitflags { const OPTIONS: [$BitFlags; NUM_FLAGS] = [ $( - #[allow(unused_doc_comments, unused_attributes)] $(#[$attr $($args)*])* $BitFlags::$Flag, )* ]; - #[allow(unused_doc_comments, unused_attributes)] const OPTIONS_NAMES: [&'static str; NUM_FLAGS] = [ $( $(#[$attr $($args)*])* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -754,17 +710,29 @@ macro_rules! __impl_bitflags { ]; let mut start = 0; + let mut state = self; $crate::__private::core::iter::from_fn(move || { - if self.is_empty() || NUM_FLAGS == 0 { + if state.is_empty() || NUM_FLAGS == 0 { $crate::__private::core::option::Option::None } else { for (flag, flag_name) in OPTIONS[start..NUM_FLAGS].iter().copied() .zip(OPTIONS_NAMES[start..NUM_FLAGS].iter().copied()) { start += 1; + + // 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: + // + // 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.contains(flag) { - self.remove(flag); + state.remove(flag); return $crate::__private::core::option::Option::Some((flag_name, flag)) } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1854,7 +1828,6 @@ mod tests { } } - let flags = Flags::from_bits(0b00000100); assert_eq!(flags, None); let flags = Flags::from_bits(0b00000101); diff --git a/tests/compile-fail/cfg/multi.stderr /dev/null --- a/tests/compile-fail/cfg/multi.stderr +++ /dev/null @@ -1,17 +0,0 @@ -error[E0428]: the name `FOO` is defined multiple times - --> tests/compile-fail/cfg/multi.rs:6:1 - | -6 | / bitflags! { -7 | | pub struct Flags: u32 { -8 | | #[cfg(target_os = "linux")] -9 | | const FOO = 1; -... | -12 | | } -13 | | } - | | ^ - | | | - | |_`FOO` redefined here - | previous definition of the value `FOO` here - | - = note: `FOO` must be defined only once in the value namespace of this trait - = note: this error originates in the macro `__impl_all_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -1,22 +1,16 @@ -error[E0308]: mismatched types - --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 +error[E0277]: the trait bound `MyInt: Bits` is not satisfied + --> tests/compile-fail/non_integer_base/all_defined.rs:116:22 | -115 | / bitflags! { -116 | | struct Flags128: MyInt { -117 | | const A = MyInt(0b0000_0001u8); -118 | | const B = MyInt(0b0000_0010u8); -119 | | const C = MyInt(0b0000_0100u8); -120 | | } -121 | | } - | |_^ expected struct `MyInt`, found integer +116 | struct Flags128: MyInt { + | ^^^^^ the trait `Bits` is not implemented for `MyInt` | - = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) -help: try wrapping the expression in `MyInt` +note: required by a bound in `bitflags::BitFlags::Bits` + --> src/bitflags_trait.rs | -458 | if extra_bits != MyInt(0) { - | ++++++ + + | type Bits: Bits; + | ^^^^ required by this bound in `bitflags::BitFlags::Bits` -error[E0308]: mismatched types +error[E0277]: the trait bound `MyInt: Bits` is not satisfied --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 | 115 | / bitflags! { diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -26,15 +20,11 @@ error[E0308]: mismatched types 119 | | const C = MyInt(0b0000_0100u8); 120 | | } 121 | | } - | |_^ expected struct `MyInt`, found integer + | |_^ the trait `Bits` is not implemented for `MyInt` | = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) -help: try wrapping the expression in `MyInt` - | -508 | Self { bits: MyInt(0) } - | ++++++ + -error[E0308]: mismatched types +error[E0277]: the trait bound `MyInt: Bits` is not satisfied --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 | 115 | / bitflags! { diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -44,15 +34,11 @@ error[E0308]: mismatched types 119 | | const C = MyInt(0b0000_0100u8); 120 | | } 121 | | } - | |_^ expected struct `MyInt`, found integer + | |_^ the trait `Bits` is not implemented for `MyInt` | = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) -help: try wrapping the expression in `MyInt` - | -546 | if bits == MyInt(0) { - | ++++++ + -error[E0277]: no implementation for `{integer} |= MyInt` +error[E0277]: the trait bound `MyInt: Bits` is not satisfied --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 | 115 | / bitflags! { diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -62,12 +48,11 @@ error[E0277]: no implementation for `{integer} |= MyInt` 119 | | const C = MyInt(0b0000_0100u8); 120 | | } 121 | | } - | |_^ no implementation for `{integer} |= MyInt` + | |_^ the trait `Bits` is not implemented for `MyInt` | - = help: the trait `BitOrAssign<MyInt>` is not implemented for `{integer}` = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0308]: mismatched types +error[E0277]: the trait bound `MyInt: Bits` is not satisfied --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 | 115 | / bitflags! { diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -77,28 +62,6 @@ error[E0308]: mismatched types 119 | | const C = MyInt(0b0000_0100u8); 120 | | } 121 | | } - | |_^ expected struct `MyInt`, found integer + | |_^ the trait `Bits` is not implemented for `MyInt` | = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) -help: try wrapping the expression in `MyInt` - | -561 | Self { bits: MyInt(truncated) } - | ++++++ + - -error[E0308]: mismatched types - --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 - | -115 | / bitflags! { -116 | | struct Flags128: MyInt { -117 | | const A = MyInt(0b0000_0001u8); -118 | | const B = MyInt(0b0000_0010u8); -119 | | const C = MyInt(0b0000_0100u8); -120 | | } -121 | | } - | |_^ expected struct `MyInt`, found integer - | - = note: this error originates in the macro `__impl_all_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) -help: try wrapping the expression in `MyInt` - | -409 | const $Flag: $T = MyInt(0); - | ++++++ + diff --git a/tests/compile-fail/trait/custom_impl.stderr b/tests/compile-fail/trait/custom_impl.stderr --- a/tests/compile-fail/trait/custom_impl.stderr +++ b/tests/compile-fail/trait/custom_impl.stderr @@ -1,11 +1,11 @@ error[E0277]: the trait bound `BootlegFlags: ImplementedByBitFlagsMacro` is not satisfied - --> $DIR/custom_impl.rs:5:6 + --> tests/compile-fail/trait/custom_impl.rs:5:6 | 5 | impl BitFlags for BootlegFlags { | ^^^^^^^^ the trait `ImplementedByBitFlagsMacro` is not implemented for `BootlegFlags` | note: required by a bound in `BitFlags` - --> $DIR/bitflags_trait.rs:7:21 + --> src/bitflags_trait.rs | -7 | pub trait BitFlags: ImplementedByBitFlagsMacro { + | pub trait BitFlags: ImplementedByBitFlagsMacro { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `BitFlags` diff --git a/tests/compile-fail/cfg/multi.rs b/tests/compile-pass/cfg/redefined-value.rs --- a/tests/compile-fail/cfg/multi.rs +++ b/tests/compile-pass/cfg/redefined-value.rs @@ -1,12 +1,11 @@ #[macro_use] extern crate bitflags; -// NOTE: Ideally this would work, but our treatment of CFGs -// assumes flags may be missing but not redefined bitflags! { pub struct Flags: u32 { #[cfg(target_os = "linux")] const FOO = 1; + #[cfg(not(target_os = "linux"))] const FOO = 2; } diff --git a/tests/compile-fail/cfg/multi.rs b/tests/compile-pass/cfg/redefined-value.rs --- a/tests/compile-fail/cfg/multi.rs +++ b/tests/compile-pass/cfg/redefined-value.rs @@ -20,6 +19,6 @@ fn main() { #[cfg(not(target_os = "linux"))] { - assert_eq!(1, Flags::FOO.bits()); + assert_eq!(2, Flags::FOO.bits()); } } diff --git /dev/null b/tests/compile-pass/deprecated.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/deprecated.rs @@ -0,0 +1,14 @@ +#![deny(warnings)] + +#[macro_use] +extern crate bitflags; + +bitflags! { + pub struct Flags: u32 { + #[deprecated = "Use something else"] + const A = 0b00000001; + const B = 0b00000010; + } +} + +fn main() {} diff --git /dev/null b/tests/compile-pass/non_snake_case.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/non_snake_case.rs @@ -0,0 +1,13 @@ +#![deny(warnings)] + +#[macro_use] +extern crate bitflags; + +bitflags! { + pub struct Flags: u32 { + const CamelCase = 0b00000001; + const B = 0b00000010; + } +} + +fn main() {}
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
Empty bitflags has unhelpful Debug representation The Debug representation is the empty string. This is not very debuggable. I think "(empty)" would be more helpful. ```rust #[macro_use] extern crate bitflags; bitflags! { pub flags Flags: u8 { const A = 0, } } fn main() { println!("{:?}", Flags::empty()); } ```
Do as suggested in the op.
bitflags__bitflags-85
[ "64" ]
7acacb4e869a6a0c8b427c25ade53086e5f024a1
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -765,6 +764,7 @@ mod tests { #[test] fn test_debug() { assert_eq!(format!("{:?}", FlagA | FlagB), "FlagA | FlagB"); + assert_eq!(format!("{:?}", Flags::empty()), "(empty)"); assert_eq!(format!("{:?}", FlagABC), "FlagA | FlagB | FlagC | FlagABC"); }
0.8
85
2017-03-22T12:28:53Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -252,8 +252,7 @@ macro_rules! bitflags { } )+ if first { - // TODO: should not be the empty string - // https://github.com/rust-lang-nursery/bitflags/issues/64 + try!(f.write_str("(empty)")); } Ok(()) }
7acacb4e869a6a0c8b427c25ade53086e5f024a1
bitflags/bitflags
Bitflags should be private by default Bitflags should match the semantics of structs, which are private by default unless explicitly exported using `pub`. Since this is a compat-breaking change, it would make sense to do it at the same time as the switch to associated constants and namespaced flags (#24). Example: ``` rust bitflags! { pub flags Flags: u32 { const FLAG_A = 0b00000001, const FLAG_B = 0b00000010, } } ```
bitflags__bitflags-38
[ "25" ]
95a521ddd2d4ae36df7a91d22be8b5f89c620e59
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -661,4 +745,27 @@ mod tests { assert_eq!(format!("{:?}", FlagA | FlagB), "FlagA | FlagB"); assert_eq!(format!("{:?}", FlagABC), "FlagA | FlagB | FlagC | FlagABC"); } + + mod submodule { + bitflags! { + pub flags PublicFlags: i8 { + const FlagX = 0, + } + } + bitflags! { + flags PrivateFlags: i8 { + const FlagY = 0, + } + } + + #[test] + fn test_private() { + let _ = FlagY; + } + } + + #[test] + fn test_public() { + let _ = submodule::FlagX; + } }
0.4
38
2016-01-16T10:00:58Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -101,6 +101,35 @@ pub use std as __core; /// } /// ``` /// +/// # Visibility +/// +/// The generated struct and its associated flag constants are not exported +/// out of the current module by default. A definition can be exported out of +/// the current module by adding `pub` before `flags`: +/// +/// ```{.rust},ignore +/// #[macro_use] +/// extern crate bitflags; +/// +/// mod example { +/// bitflags! { +/// pub flags Flags1: u32 { +/// const FLAG_A = 0b00000001, +/// } +/// } +/// bitflags! { +/// flags Flags2: u32 { +/// const FLAG_B = 0b00000010, +/// } +/// } +/// } +/// +/// fn main() { +/// let flag1 = example::FLAG_A; +/// let flag2 = example::FLAG_B; // error: const `FLAG_B` is private +/// } +/// ``` +/// /// # Attributes /// /// Attributes can be attached to the generated `struct` by placing them diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -153,7 +182,7 @@ pub use std as __core; /// if they are. #[macro_export] macro_rules! bitflags { - ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { + ($(#[$attr:meta])* pub flags $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ }) => { #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -164,35 +193,73 @@ macro_rules! bitflags { $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + bitflags! { + @_impl flags $BitFlags: $T { + $($(#[$Flag_attr])* const $Flag = $value),+ + } + } + }; + ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + }) => { + #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] + $(#[$attr])* + struct $BitFlags { + bits: $T, + } + + $($(#[$Flag_attr])* const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + + bitflags! { + @_impl flags $BitFlags: $T { + $($(#[$Flag_attr])* const $Flag = $value),+ + } + } + }; + (@_impl flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + }) => { impl $crate::__core::fmt::Debug for $BitFlags { fn fmt(&self, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { // This convoluted approach is to handle #[cfg]-based flag // omission correctly. Some of the $Flag variants may not be // defined in this module so we create an inner module which - // defines *all* flags to the value of 0. Afterwards when the - // glob import variants from the outer module, shadowing all + // defines *all* flags to the value of 0. We then create a + // second inner module that defines all of the flags with #[cfg] + // to their real values. Afterwards the glob will import + // variants from the second inner module, shadowing all // defined variants, leaving only the undefined ones with the // bit value of 0. #[allow(dead_code)] #[allow(unused_assignments)] mod dummy { + // We can't use the real $BitFlags struct because it may be + // private, which prevents us from using it to define + // public constants. + pub struct $BitFlags { + bits: $T, + } + mod real_flags { + use super::$BitFlags; + $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + } // Now we define the "undefined" versions of the flags. // This way, all the names exist, even if some are #[cfg]ed // out. - $(const $Flag: super::$BitFlags = super::$BitFlags { bits: 0 };)+ + $(const $Flag: $BitFlags = $BitFlags { bits: 0 };)+ #[inline] - pub fn fmt(self_: &super::$BitFlags, + pub fn fmt(self_: $T, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { // Now we import the real values for the flags. // Only ones that are #[cfg]ed out will be 0. - use super::*; + use self::real_flags::*; let mut first = true; $( // $Flag.bits == 0 means that $Flag doesn't exist - if $Flag.bits != 0 && self_.contains($Flag) { + if $Flag.bits != 0 && self_ & $Flag.bits == $Flag.bits { if !first { try!(f.write_str(" | ")); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -203,7 +270,7 @@ macro_rules! bitflags { Ok(()) } } - dummy::fmt(self, f) + dummy::fmt(self.bits, f) } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -221,15 +288,22 @@ macro_rules! bitflags { // See above `dummy` module for why this approach is taken. #[allow(dead_code)] mod dummy { - $(const $Flag: super::$BitFlags = super::$BitFlags { bits: 0 };)+ + pub struct $BitFlags { + bits: $T, + } + mod real_flags { + use super::$BitFlags; + $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + } + $(const $Flag: $BitFlags = $BitFlags { bits: 0 };)+ #[inline] - pub fn all() -> super::$BitFlags { - use super::*; - $BitFlags { bits: $($Flag.bits)|+ } + pub fn all() -> $T { + use self::real_flags::*; + $($Flag.bits)|+ } } - dummy::all() + $BitFlags { bits: dummy::all() } } /// Returns the raw value of the flags currently stored. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -399,6 +473,16 @@ macro_rules! bitflags { } } }; + ($(#[$attr:meta])* pub flags $BitFlags:ident: $T:ty { + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+, + }) => { + bitflags! { + $(#[$attr])* + pub flags $BitFlags: $T { + $($(#[$Flag_attr])* const $Flag = $value),+ + } + } + }; ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+, }) => {
95a521ddd2d4ae36df7a91d22be8b5f89c620e59
bitflags/bitflags
Function-local bitflags Is there any hope of supporting usage like this? The error here is inconsistent with being able to declare structs and other types of items local to a function. ```rust #[macro_use] extern crate bitflags; fn main() { bitflags! { flags Flags: u8 { const A = 1, const B = 2, } } println!("{:?}", A); } ``` ``` error[E0425]: cannot find value `A` in module `super::super` --> src/main.rs:5:5 | 5 | bitflags! { | _____^ starting here... 6 | | flags Flags: u8 { 7 | | const A = 1, 8 | | const B = 2, 9 | | } 10 | | } | |_____^ ...ending here: not found in `super::super` | = note: this error originates in a macro outside of the current crate ```
bitflags__bitflags-74
[ "71" ]
2fecde2b33c34659bd37d82f64b9c07f002d6a30
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -837,4 +807,17 @@ mod tests { } } } + + #[test] + fn test_in_function() { + bitflags! { + flags Flags: u8 { + const A = 1, + #[cfg(any())] // false + const B = 2, + } + } + assert_eq!(Flags::all(), A); + assert_eq!(format!("{:?}", A), "A"); + } }
0.8
74
2017-03-08T02:00:24Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -216,63 +216,46 @@ macro_rules! bitflags { impl $crate::__core::fmt::Debug for $BitFlags { fn fmt(&self, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { // This convoluted approach is to handle #[cfg]-based flag - // omission correctly. Some of the $Flag variants may not be - // defined in this module so we create an inner module which - // defines *all* flags to the value of 0. We then create a - // second inner module that defines all of the flags with #[cfg] - // to their real values. Afterwards the glob will import - // variants from the second inner module, shadowing all - // defined variants, leaving only the undefined ones with the - // bit value of 0. - #[allow(dead_code)] - #[allow(unused_assignments)] - mod dummy { - // We can't use the real $BitFlags struct because it may be - // private, which prevents us from using it to define - // public constants. - pub struct __Pub(super::$BitFlags); - impl $crate::__core::convert::From<super::$BitFlags> for __Pub { - fn from(original: super::$BitFlags) -> Self { - __Pub(original) - } - } - mod real_flags { - use super::__Pub; - $( - $(#[$Flag_attr])* - pub const $Flag: __Pub = __Pub(super::super::$Flag); - )+ - } - // Now we define the "undefined" versions of the flags. - // This way, all the names exist, even if some are #[cfg]ed - // out. + // omission correctly. For example it needs to support: + // + // #[cfg(unix)] const A: Flag = /* ... */; + // #[cfg(windows)] const B: Flag = /* ... */; + + // Unconditionally define a check for every flag, even disabled + // ones. + #[allow(non_snake_case)] + trait __BitFlags { + $( + fn $Flag(&self) -> bool { false } + )+ + } + + // Conditionally override the check for just those flags that + // are not #[cfg]ed away. + impl __BitFlags for $BitFlags { $( - const $Flag: __Pub = __Pub(super::$BitFlags { bits: 0 }); + $(#[$Flag_attr])* + fn $Flag(&self) -> bool { + self.bits & $Flag.bits == $Flag.bits + } )+ + } - #[inline] - pub fn fmt(self_: __Pub, - f: &mut $crate::__core::fmt::Formatter) - -> $crate::__core::fmt::Result { - // Now we import the real values for the flags. - // Only ones that are #[cfg]ed out will be 0. - use self::real_flags::*; - - let mut first = true; - $( - // $Flag.bits == 0 means that $Flag doesn't exist - if $Flag.0.bits != 0 && self_.0.bits & $Flag.0.bits == $Flag.0.bits { - if !first { - try!(f.write_str(" | ")); - } - first = false; - try!(f.write_str(stringify!($Flag))); - } - )+ - Ok(()) + let mut first = true; + $( + if <$BitFlags as __BitFlags>::$Flag(self) { + if !first { + try!(f.write_str(" | ")); + } + first = false; + try!(f.write_str(stringify!($Flag))); } + )+ + if first { + // TODO: should not be the empty string + // https://github.com/rust-lang-nursery/bitflags/issues/64 } - dummy::fmt($crate::__core::convert::From::from(*self), f) + Ok(()) } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -287,33 +270,20 @@ macro_rules! bitflags { /// Returns the set containing all flags. #[inline] pub fn all() -> $BitFlags { - // See above `dummy` module for why this approach is taken. - #[allow(dead_code)] - mod dummy { - pub struct __Pub(super::$BitFlags); - impl $crate::__core::convert::From<__Pub> for super::$BitFlags { - fn from(wrapper: __Pub) -> Self { - wrapper.0 - } - } - mod real_flags { - use super::__Pub; - $( - $(#[$Flag_attr])* - pub const $Flag: __Pub = __Pub(super::super::$Flag); - )+ - } + // See `Debug::fmt` for why this approach is taken. + #[allow(non_snake_case)] + trait __BitFlags { $( - const $Flag: __Pub = __Pub(super::$BitFlags { bits: 0 }); + fn $Flag() -> $T { 0 } + )+ + } + impl __BitFlags for $BitFlags { + $( + $(#[$Flag_attr])* + fn $Flag() -> $T { $Flag.bits } )+ - - #[inline] - pub fn all() -> __Pub { - use self::real_flags::*; - __Pub(super::$BitFlags { bits: $($Flag.0.bits)|+ }) - } } - $crate::__core::convert::From::from(dummy::all()) + $BitFlags { bits: $(<$BitFlags as __BitFlags>::$Flag())|+ } } /// Returns the raw value of the flags currently stored.
7acacb4e869a6a0c8b427c25ade53086e5f024a1
bitflags/bitflags
Possibly unintended breakage between 0.8 and 0.9 involving use of the `#[deprecated]` attribute Given the following snippet of code compiled with bitflags 0.8: ```rust #![allow(deprecated)] #[macro_use] extern crate bitflags; bitflags! { pub flags TestFlags: u32 { #[deprecated(note = "test note")] const FLAG_ONE = 1, } } ``` Everything works fine: ```bash Compiling bitflags_breakage_test v0.1.0 (file:///home/cldfire/programming_projects/bitflags_breakage_test) Finished dev [unoptimized + debuginfo] target(s) in 0.10 secs ``` And everything looks fine in the docs as well: ![spectacle h29900](https://user-images.githubusercontent.com/13814214/26940771-faeeefac-4c49-11e7-9cb0-76ad068732e0.png) ![spectacle t29900](https://user-images.githubusercontent.com/13814214/26940787-07d93376-4c4a-11e7-915a-214261986bbd.png) However, given the same snippet of code (ignoring syntax changes) compiled with bitflags 0.9: ```rust #![allow(deprecated)] #[macro_use] extern crate bitflags; bitflags! { pub struct TestFlags: u32 { #[deprecated(note = "test note")] const FLAG_ONE = 1; } } ``` It does not compile: ```bash Updating registry `https://github.com/rust-lang/crates.io-index` Compiling bitflags_breakage_test v0.1.0 (file:///home/cldfire/programming_projects/bitflags_breakage_test) error: This deprecation annotation is useless --> src/lib.rs:6:1 | 6 | / bitflags! { 7 | | pub struct TestFlags: u32 { 8 | | #[deprecated(note = "test note")] 9 | | const FLAG_ONE = 1; 10 | | } 11 | | } | |_^ | = note: this error originates in a macro outside of the current crate error: This deprecation annotation is useless --> src/lib.rs:6:1 | 6 | / bitflags! { 7 | | pub struct TestFlags: u32 { 8 | | #[deprecated(note = "test note")] 9 | | const FLAG_ONE = 1; 10 | | } 11 | | } | |_^ | = note: this error originates in a macro outside of the current crate error: aborting due to 2 previous errors error: Could not compile `bitflags_breakage_test`. To learn more, run the command again with --verbose. ``` I am not sure if this behavior is intended or not, or if use of attributes such as `#[deprecated]` was supported in the first place. If this is correct behavior it would be nice to mention it in the release notes (I encountered this issue while bumping bitflags from 0.8 -> 0.9 in my own crate).
bitflags__bitflags-112
[ "109" ]
8ee624463bb29c3a749ef134fda7cc0fa1192552
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -988,4 +1075,14 @@ mod tests { assert_eq!(Flags::all(), A); assert_eq!(format!("{:?}", A), "A"); } + + #[test] + fn test_deprecated() { + bitflags! { + pub struct TestFlags: u32 { + #[deprecated(note = "Use something else.")] + const FLAG_ONE = 1; + } + } + } }
0.9
112
2017-08-06T08:33:36Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -305,49 +305,77 @@ pub extern crate core as _core; /// ``` #[macro_export] macro_rules! bitflags { - ($(#[$attr:meta])* pub struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ - }) => { + ( + $(#[$outer:meta])* + pub struct $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )+ + } + ) => { #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] - $(#[$attr])* + $(#[$outer])* pub struct $BitFlags { bits: $T, } - $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + $( + $(#[$inner $($args)*])* + pub const $Flag: $BitFlags = $BitFlags { bits: $value }; + )+ __impl_bitflags! { struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value;)+ + $( + $(#[$inner $($args)*])* + const $Flag = $value; + )+ } } }; - ($(#[$attr:meta])* struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ - }) => { + ( + $(#[$outer:meta])* + struct $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )+ + } + ) => { #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] - $(#[$attr])* + $(#[$outer])* struct $BitFlags { bits: $T, } - $($(#[$Flag_attr])* const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + $( + $(#[$inner $($args)*])* + const $Flag: $BitFlags = $BitFlags { bits: $value }; + )+ __impl_bitflags! { struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value;)+ + $( + $(#[$inner $($args)*])* + const $Flag = $value; + )+ } } - }; } #[macro_export] #[doc(hidden)] macro_rules! __impl_bitflags { - (struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ - }) => { + ( + struct $BitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )+ + } + ) => { impl $crate::_core::fmt::Debug for $BitFlags { fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { // This convoluted approach is to handle #[cfg]-based flag diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -369,9 +397,12 @@ macro_rules! __impl_bitflags { // are not #[cfg]ed away. impl __BitFlags for $BitFlags { $( - $(#[$Flag_attr])* - fn $Flag(&self) -> bool { - self.bits & $Flag.bits == $Flag.bits + __impl_bitflags! { + #[allow(deprecated)] + $(? #[$attr $($args)*])* + fn $Flag(&self) -> bool { + self.bits & $Flag.bits == $Flag.bits + } } )+ } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -433,8 +464,11 @@ macro_rules! __impl_bitflags { } impl __BitFlags for $BitFlags { $( - $(#[$Flag_attr])* - fn $Flag() -> $T { $Flag.bits } + __impl_bitflags! { + #[allow(deprecated)] + $(? #[$attr $($args)*])* + fn $Flag() -> $T { $Flag.bits } + } )+ } $BitFlags { bits: $(<$BitFlags as __BitFlags>::$Flag())|+ } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -619,6 +653,59 @@ macro_rules! __impl_bitflags { } } }; + + // Every attribute that the user writes on a const is applied to the + // corresponding const that we generate, but within the implementation of + // Debug and all() we want to ignore everything but #[cfg] attributes. In + // particular, including a #[deprecated] attribute on those items would fail + // to compile. + // https://github.com/rust-lang-nursery/bitflags/issues/109 + // + // Input: + // + // ? #[cfg(feature = "advanced")] + // ? #[deprecated(note = "Use somthing else.")] + // ? #[doc = r"High quality documentation."] + // fn f() -> i32 { /* ... */ } + // + // Output: + // + // #[cfg(feature = "advanced")] + // fn f() -> i32 { /* ... */ } + ( + $(#[$filtered:meta])* + ? #[cfg $($cfgargs:tt)*] + $(? #[$rest:ident $($restargs:tt)*])* + fn $($item:tt)* + ) => { + __impl_bitflags! { + $(#[$filtered])* + #[cfg $($cfgargs)*] + $(? #[$rest $($restargs)*])* + fn $($item)* + } + }; + ( + $(#[$filtered:meta])* + // $next != `cfg` + ? #[$next:ident $($nextargs:tt)*] + $(? #[$rest:ident $($restargs:tt)*])* + fn $($item:tt)* + ) => { + __impl_bitflags! { + $(#[$filtered])* + // $next filtered out + $(? #[$rest $($restargs)*])* + fn $($item)* + } + }; + ( + $(#[$filtered:meta])* + fn $($item:tt)* + ) => { + $(#[$filtered])* + fn $($item)* + }; } #[cfg(feature = "example_generated")]
8ee624463bb29c3a749ef134fda7cc0fa1192552
bitflags/bitflags
Add an option for checking for valid bits is in the getter rather than constructor Hi, I want to use bitflags for generated code that interacts with data in other languages, some of which are bitflags (https://github.com/google/flatbuffers/pull/6098). I don't want to drop data so I'd like to use `from_bits_unchecked`. However, it is marked as unsafe. I'd like to submit a PR to add an option to get around this. I have two ideas: 1) Move the valid-bits-check to the getter: There'll be only one constructor: `from_bits` and the `bits()` getter becomes `bits() -> Result<...>`, `unsafe bits_unchecked()`, and `bits_truncated()` 2) #200 documents that this crate uses `unsafe` to mean a usage issue rather than a memory issue, so maybe I could make an option to remove the unsafe altogether, and update the generated documentation appropriately? What are your thoughts on these ideas? Does bitflags depend on the "bits are truncated to defined flags" invariant?
Related: #188, #200, #207, #208, #211 @niklasf @KodrAus worked on #200 Bump! I'll do the PR if needed Hi @CasperN! :wave: We can't consider any changes to the `bits()` method, because the library is already stable. The way we modeled this originally was that the flags represents a closed enum, where the set specified in the definition is the complete set of possible flags the enum could combine. Since not all valid bit patterns of the underlying integer type are valid bit patterns of the flags it's not safe for us to simply accept any integer and treat it as valid flags. So we made the `unchecked` method unsafe. If we wanted to clean up the semantics we could consider allowing an `#[open]` attribute or something on the `bitflags!` definition itself, so you'd declare an open bitflags that could happily accept any integer, assuming it's not the source-of-truth for what flags exist: ```rust bitflags! { #[open] struct Flags: u32 { const A = 0b00000001; const B = 0b00000010; } } ``` Then let these `#[open]` bitflags have `#[repr(transparent)]` and so can be soundly transmuted to and from the given integer type, making `from_bits_unchecked` safe. What do you think? We could also use `#[repr(transparent)]` for this. I don’t think that’s too much of a semantic hijacking, so long as it also does apply the attribute.
bitflags__bitflags-282
[ "228" ]
810dc35aba3df7314de01b93c7aa137968e925d4
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -46,8 +46,17 @@ jobs: profile: minimal toolchain: ${{ matrix.channel }}-${{ matrix.rust_target }} - - name: Tests - run: cargo test --features example_generated + - name: Install cargo-hack + run: cargo install cargo-hack + + - name: Powerset + run: cargo hack test --feature-powerset --lib --optional-deps "serde" --depth 3 --skip rustc-dep-of-std + + - name: Docs + run: cargo doc --features example_generated + + - name: Smoke test + run: cargo run --manifest-path tests/smoke-test/Cargo.toml embedded: name: Build (embedded) diff --git a/tests/basic.rs b/tests/basic.rs --- a/tests/basic.rs +++ b/tests/basic.rs @@ -4,13 +4,14 @@ use bitflags::bitflags; bitflags! { /// baz + #[derive(Debug, PartialEq, Eq)] struct Flags: u32 { const A = 0b00000001; #[doc = "bar"] const B = 0b00000010; const C = 0b00000100; #[doc = "foo"] - const ABC = Flags::A.bits | Flags::B.bits | Flags::C.bits; + const ABC = Flags::A.bits() | Flags::B.bits() | Flags::C.bits(); } } diff --git /dev/null b/tests/smoke-test/Cargo.toml new file mode 100644 --- /dev/null +++ b/tests/smoke-test/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "bitflags-smoke-test" +version = "0.0.0" +edition = "2021" +publish = false + +[dependencies.bitflags] +path = "../../"
1.3
282
2022-05-25T04:14:38Z
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -16,16 +16,16 @@ categories = ["no-std"] description = """ A macro to generate structures which behave like bitflags. """ -exclude = ["bors.toml"] +exclude = ["tests", ".github"] [dependencies] -core = { version = '1.0.0', optional = true, package = 'rustc-std-workspace-core' } -compiler_builtins = { version = '0.1.2', optional = true } +serde = { version = "1.0", optional = true } +core = { version = "1.0.0", optional = true, package = "rustc-std-workspace-core" } +compiler_builtins = { version = "0.1.2", optional = true } [dev-dependencies] trybuild = "1.0" rustversion = "1.0" -serde = "1.0" serde_derive = "1.0" serde_json = "1.0" diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -1,8 +1,5 @@ use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not}; -#[doc(hidden)] -pub trait ImplementedByBitFlagsMacro {} - /// A trait that is automatically implemented for all bitflags. /// /// It should not be implemented manually. diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -25,16 +22,7 @@ pub trait BitFlags: ImplementedByBitFlagsMacro { fn from_bits_truncate(bits: Self::Bits) -> Self; /// Convert from underlying bit representation, preserving all /// bits (even those not corresponding to a defined flag). - /// - /// # Safety - /// - /// The caller of the `bitflags!` macro can chose to allow or - /// disallow extra bits for their bitflags type. - /// - /// The caller of `from_bits_unchecked()` has to ensure that - /// all bits correspond to a defined flag or that extra bits - /// are valid for this bitflags type. - unsafe fn from_bits_unchecked(bits: Self::Bits) -> Self; + fn from_bits_retain(bits: Self::Bits) -> Self; /// Returns `true` if no flags are currently stored. fn is_empty(&self) -> bool; /// Returns `true` if all flags are currently set. diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -53,9 +41,22 @@ pub trait BitFlags: ImplementedByBitFlagsMacro { fn set(&mut self, other: Self, value: bool); } +/// A marker trait that signals that an implementation of `BitFlags` came from the `bitflags!` macro. +/// +/// There's nothing stopping an end-user from implementing this trait, but we don't guarantee their +/// manual implementations won't break between non-breaking releases. +#[doc(hidden)] +pub trait ImplementedByBitFlagsMacro {} + // Not re-exported pub trait Sealed {} +// Private implementation details +// +// The `Bits`, `PublicFlags`, and `InternalFlags` traits are implementation details of the `bitflags!` +// macro that we're free to change here. They work with the `bitflags!` macro to separate the generated +// code that belongs to end-users, and the generated code that belongs to this library. + /// A private trait that encodes the requirements of underlying bits types that can hold flags. /// /// This trait may be made public at some future point, but it presents a compatibility hazard diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs --- a/src/bitflags_trait.rs +++ b/src/bitflags_trait.rs @@ -107,3 +108,11 @@ impl_bits! { u64, i64, u128, i128, } + +pub trait PublicFlags { + type InternalFlags; +} + +pub trait InternalFlags { + type PublicFlags; +} diff --git a/src/example_generated.rs b/src/example_generated.rs --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -9,6 +9,35 @@ bitflags! { const A = 0b00000001; const B = 0b00000010; const C = 0b00000100; - const ABC = Self::A.bits | Self::B.bits | Self::C.bits; + const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } } + +/// This is the same internal field available as `self.0` on bitflags types. +/// These types aren't reachable by callers of `bitflags!`, they don't appear in the API of your +/// crate, but you can still interact with them through `self.0` in the module that defines the +/// bitflags type. +/// +/// You can use this example as a reference for what methods are available to all internal bitflags +/// fields if you want to add custom functionality to your bitflags types. +/// +/// Note that this struct is just for documentation purposes only, it must not be used outside +/// this crate. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(transparent)] +pub struct FlagsField { + bits: u32, +} + +__impl_internal_bitflags! { + FlagsField: u32 { + A; + B; + C; + ABC; + } +} + +impl crate::__private::InternalFlags for FlagsField { + type PublicFlags = Flags; +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -21,11 +21,12 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; //! const C = 0b00000100; -//! const ABC = Self::A.bits | Self::B.bits | Self::C.bits; +//! 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 @@ -51,6 +52,7 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -59,14 +61,7 @@ //! //! impl Flags { //! pub fn clear(&mut self) { -//! self.bits = 0; // The `bits` field can be accessed from within the -//! // same module where the `bitflags!` macro was invoked. -//! } -//! } -//! -//! impl fmt::Display for Flags { -//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -//! write!(f, "hi!") +//! *self.0.bits_mut() = 0; //! } //! } //! diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -74,9 +69,8 @@ //! let mut flags = Flags::A | Flags::B; //! flags.clear(); //! assert!(flags.is_empty()); -//! assert_eq!(format!("{}", flags), "hi!"); -//! assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); -//! assert_eq!(format!("{:?}", Flags::B), "B"); +//! assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)"); +//! assert_eq!(format!("{:?}", Flags::B), "Flags(B)"); //! } //! ``` //! diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -91,10 +85,12 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! pub struct Flags1: u32 { //! const A = 0b00000001; //! } //! +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! # pub //! struct Flags2: u32 { //! const B = 0b00000010; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -123,6 +119,7 @@ //! //! bitflags! { //! #[repr(transparent)] +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -133,13 +130,8 @@ //! //! # Trait implementations //! -//! The `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord` and `Hash` -//! traits are automatically derived for the `struct`s using the `derive` attribute. -//! Additional traits can be derived by providing an explicit `derive` -//! attribute on `struct`. -//! -//! The `Extend` and `FromIterator` traits are implemented for the `struct`s, -//! too: `Extend` adds the union of the instances of the `struct` iterated over, +//! The `Extend` and `FromIterator` traits are implemented for the `struct`s. +//! `Extend` adds the union of the instances of the `struct` iterated over, //! while `FromIterator` calculates the union. //! //! The `Binary`, `Debug`, `LowerHex`, `Octal` and `UpperHex` traits are also diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -167,7 +159,7 @@ //! defined flag //! - `from_bits_truncate`: convert from underlying bit representation, dropping //! any bits that do not correspond to defined flags -//! - `from_bits_unchecked`: convert from underlying bit representation, keeping +//! - `from_bits_retain`: convert from underlying bit representation, keeping //! all bits (even those not corresponding to defined //! flags) //! - `is_empty`: `true` if no flags are currently stored diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -204,7 +196,7 @@ //! //! bitflags! { //! // Results in default value with bits: 0 -//! #[derive(Default)] +//! #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -224,6 +216,7 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -252,6 +245,7 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const NONE = 0b00000000; //! const SOME = 0b00000001; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -285,10 +279,62 @@ mod bitflags_trait; #[doc(hidden)] pub mod __private { - pub use crate::bitflags_trait::{Bits, ImplementedByBitFlagsMacro}; + pub use crate::bitflags_trait::{Bits, ImplementedByBitFlagsMacro, InternalFlags, PublicFlags}; pub use core; + + #[cfg(feature = "serde")] + pub use serde; } +/* +How does the bitflags crate work? + +This library generates `struct`s in the end-user's crate with a bunch of constants on it that represent flags. +The difference between `bitflags` and a lot of other libraries is that we don't actually control the generated `struct` in the end. +It's part of the end-user's crate, so it belongs to them. That makes it difficult to extend `bitflags` with new functionality +because we could end up breaking valid code that was already written. + +Our solution is to split the type we generate into two: the public struct owned by the end-user, and an internal struct owned by `bitflags` (us). +To give you an example, let's say we had a crate that called `bitflags!`: + +```rust +bitflags! { + pub struct MyFlags: u32 { + const A = 1; + const B = 2; + } +} +``` + +What they'd end up with looks something like this: + +```rust +pub struct MyFlags(<MyFlags as PublicFlags>::InternalFlags); + +const _: () = { + #[repr(transparent)] + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub struct MyInternalFlags { + bits: u32, + } + + impl PublicFlags for MyFlags { + type InternalFlags = InternalFlags; + } + + impl InternalFlags for MyInternalFlags { + type PublicFlags = MyFlags; + } +}; +``` + +If we want to expose something like a new trait impl for generated flags types, we add it to our generated `MyInternalFlags`, +and let `#[derive]` on `MyFlags` pick up that implementation, if an end-user chooses to add one. + +The public API is generated in the `__impl_bitflags_public!` macro, and the internal API is generated in +the `__impl_bitflags_internal!` macro. +*/ + /// The macro used to generate the flag structure. /// /// See the [crate level docs](../bitflags/index.html) for complete documentation. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -299,11 +345,12 @@ pub mod __private { /// use bitflags::bitflags; /// /// bitflags! { +/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] /// struct Flags: u32 { /// const A = 0b00000001; /// const B = 0b00000010; /// const C = 0b00000100; -/// const ABC = Self::A.bits | Self::B.bits | Self::C.bits; +/// 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 @@ -326,6 +373,7 @@ pub mod __private { /// use bitflags::bitflags; /// /// bitflags! { +/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] /// struct Flags: u32 { /// const A = 0b00000001; /// const B = 0b00000010; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -334,14 +382,7 @@ pub mod __private { /// /// impl Flags { /// pub fn clear(&mut self) { -/// self.bits = 0; // The `bits` field can be accessed from within the -/// // same module where the `bitflags!` macro was invoked. -/// } -/// } -/// -/// impl fmt::Display for Flags { -/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -/// write!(f, "hi!") +/// *self.0.bits_mut() = 0; /// } /// } /// diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -349,9 +390,8 @@ pub mod __private { /// let mut flags = Flags::A | Flags::B; /// flags.clear(); /// assert!(flags.is_empty()); -/// assert_eq!(format!("{}", flags), "hi!"); -/// assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); -/// assert_eq!(format!("{:?}", Flags::B), "B"); +/// assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)"); +/// assert_eq!(format!("{:?}", Flags::B), "Flags(B)"); /// } /// ``` #[macro_export(local_inner_macros)] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -368,12 +408,9 @@ macro_rules! bitflags { $($t:tt)* ) => { $(#[$outer])* - #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] - $vis struct $BitFlags { - bits: $T, - } + $vis struct $BitFlags(<$BitFlags as $crate::__private::PublicFlags>::InternalFlags); - __impl_bitflags! { + __impl_public_bitflags! { $BitFlags: $T { $( $(#[$inner $($args)*])* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -382,6 +419,31 @@ macro_rules! bitflags { } } + const _: () = { + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] + #[repr(transparent)] + $vis struct InternalFlags { + bits: $T, + } + + __impl_internal_bitflags! { + InternalFlags: $T { + $( + $(#[$inner $($args)*])* + $Flag; + )* + } + } + + impl $crate::__private::InternalFlags for InternalFlags { + type PublicFlags = $BitFlags; + } + + impl $crate::__private::PublicFlags for $BitFlags { + type InternalFlags = InternalFlags; + } + }; + bitflags! { $($t)* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -389,70 +451,42 @@ macro_rules! bitflags { () => {}; } +/// Implement functions on the public (user-facing) bitflags type. +/// +/// We need to be careful about adding new methods and trait implementations here because they +/// could conflict with items added by the end-user. #[macro_export(local_inner_macros)] #[doc(hidden)] -macro_rules! __impl_bitflags { +macro_rules! __impl_public_bitflags { ( - $BitFlags:ident: $T:ty { + $PublicBitFlags:ident: $T:ty { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident = $value:expr; )* } ) => { - impl $crate::__private::core::fmt::Debug for $BitFlags { + impl $crate::__private::core::fmt::Binary for $PublicBitFlags { fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { - // Iterate over the valid flags - let mut first = true; - for (name, _) in self.iter() { - if !first { - f.write_str(" | ")?; - } - - first = false; - f.write_str(name)?; - } - - // Append any extra bits that correspond to flags to the end of the format - let extra_bits = self.bits & !Self::all().bits(); - - if extra_bits != <$T as $crate::__private::Bits>::EMPTY { - if !first { - f.write_str(" | ")?; - } - first = false; - $crate::__private::core::write!(f, "{:#x}", extra_bits)?; - } - - if first { - f.write_str("(empty)")?; - } - - $crate::__private::core::fmt::Result::Ok(()) - } - } - - impl $crate::__private::core::fmt::Binary for $BitFlags { - fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { - $crate::__private::core::fmt::Binary::fmt(&self.bits, f) + $crate::__private::core::fmt::Binary::fmt(&self.0, f) } } - impl $crate::__private::core::fmt::Octal for $BitFlags { + impl $crate::__private::core::fmt::Octal for $PublicBitFlags { fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { - $crate::__private::core::fmt::Octal::fmt(&self.bits, f) + $crate::__private::core::fmt::Octal::fmt(&self.0, f) } } - impl $crate::__private::core::fmt::LowerHex for $BitFlags { + impl $crate::__private::core::fmt::LowerHex for $PublicBitFlags { fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { - $crate::__private::core::fmt::LowerHex::fmt(&self.bits, f) + $crate::__private::core::fmt::LowerHex::fmt(&self.0, f) } } - impl $crate::__private::core::fmt::UpperHex for $BitFlags { + impl $crate::__private::core::fmt::UpperHex for $PublicBitFlags { fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { - $crate::__private::core::fmt::UpperHex::fmt(&self.bits, f) + $crate::__private::core::fmt::UpperHex::fmt(&self.0, f) } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -464,40 +498,37 @@ macro_rules! __impl_bitflags { unused_mut, non_upper_case_globals )] - impl $BitFlags { + impl $PublicBitFlags { $( $(#[$attr $($args)*])* - pub const $Flag: Self = Self { bits: $value }; + pub const $Flag: Self = Self::from_bits_retain($value); )* /// Returns an empty set of flags. #[inline] pub const fn empty() -> Self { - Self { bits: <$T as $crate::__private::Bits>::EMPTY } + Self(<$PublicBitFlags as $crate::__private::PublicFlags>::InternalFlags::empty()) } /// Returns the set containing all flags. #[inline] pub const fn all() -> Self { - Self::from_bits_truncate(<$T as $crate::__private::Bits>::ALL) + Self(<$PublicBitFlags as $crate::__private::PublicFlags>::InternalFlags::all()) } /// Returns the raw value of the flags currently stored. #[inline] pub const fn bits(&self) -> $T { - self.bits + self.0.bits() } /// Convert from underlying bit representation, unless that /// representation contains bits that do not correspond to a flag. #[inline] pub const fn from_bits(bits: $T) -> $crate::__private::core::option::Option<Self> { - let truncated = Self::from_bits_truncate(bits).bits; - - if truncated == bits { - $crate::__private::core::option::Option::Some(Self { bits }) - } else { - $crate::__private::core::option::Option::None + match <$PublicBitFlags as $crate::__private::PublicFlags>::InternalFlags::from_bits(bits) { + $crate::__private::core::option::Option::Some(bits) => $crate::__private::core::option::Option::Some(Self(bits)), + $crate::__private::core::option::Option::None => $crate::__private::core::option::Option::None, } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -505,20 +536,7 @@ macro_rules! __impl_bitflags { /// that do not correspond to flags. #[inline] pub const fn from_bits_truncate(bits: $T) -> Self { - if bits == <$T as $crate::__private::Bits>::EMPTY { - return Self { bits } - } - - let mut truncated = <$T as $crate::__private::Bits>::EMPTY; - - $( - $(#[$attr $($args)*])* - if bits & Self::$Flag.bits == Self::$Flag.bits { - truncated |= Self::$Flag.bits - } - )* - - Self { bits: truncated } + Self(<$PublicBitFlags as $crate::__private::PublicFlags>::InternalFlags::from_bits_truncate(bits)) } /// Convert from underlying bit representation, preserving all diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -529,64 +547,60 @@ macro_rules! __impl_bitflags { /// The caller of the `bitflags!` macro can choose to allow or /// disallow extra bits for their bitflags type. /// - /// The caller of `from_bits_unchecked()` has to ensure that + /// The caller of `from_bits_retain()` has to ensure that /// all bits correspond to a defined flag or that extra bits /// are valid for this bitflags type. #[inline] - pub const unsafe fn from_bits_unchecked(bits: $T) -> Self { - Self { bits } + pub const fn from_bits_retain(bits: $T) -> Self { + Self(<$PublicBitFlags as $crate::__private::PublicFlags>::InternalFlags::from_bits_retain(bits)) } /// Returns `true` if no flags are currently stored. #[inline] pub const fn is_empty(&self) -> bool { - self.bits() == Self::empty().bits() + self.0.is_empty() } /// Returns `true` if all flags are currently set. #[inline] pub const fn is_all(&self) -> bool { - Self::all().bits | self.bits == self.bits + self.0.is_all() } /// Returns `true` if there are flags common to both `self` and `other`. #[inline] pub const fn intersects(&self, other: Self) -> bool { - !(Self { bits: self.bits & other.bits}).is_empty() + self.0.intersects(other.0) } /// Returns `true` if all of the flags in `other` are contained within `self`. #[inline] pub const fn contains(&self, other: Self) -> bool { - (self.bits & other.bits) == other.bits + self.0.contains(other.0) } /// Inserts the specified flags in-place. #[inline] pub fn insert(&mut self, other: Self) { - self.bits |= other.bits; + self.0.insert(other.0) } /// Removes the specified flags in-place. #[inline] pub fn remove(&mut self, other: Self) { - self.bits &= !other.bits; + self.0.remove(other.0) } /// Toggles the specified flags in-place. #[inline] pub fn toggle(&mut self, other: Self) { - self.bits ^= other.bits; + self.0.toggle(other.0) } /// Inserts or removes the specified flags depending on the passed value. #[inline] pub fn set(&mut self, other: Self, value: bool) { - if value { - self.insert(other); - } else { - self.remove(other); - } + self.0.set(other.0, value) } /// Returns the intersection between the flags in `self` and diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -602,7 +616,7 @@ macro_rules! __impl_bitflags { #[inline] #[must_use] pub const fn intersection(self, other: Self) -> Self { - Self { bits: self.bits & other.bits } + Self(self.0.intersection(other.0)) } /// Returns the union of between the flags in `self` and `other`. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -619,7 +633,7 @@ macro_rules! __impl_bitflags { #[inline] #[must_use] pub const fn union(self, other: Self) -> Self { - Self { bits: self.bits | other.bits } + Self(self.0.union(other.0)) } /// Returns the difference between the flags in `self` and `other`. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -637,7 +651,7 @@ macro_rules! __impl_bitflags { #[inline] #[must_use] pub const fn difference(self, other: Self) -> Self { - Self { bits: self.bits & !other.bits } + Self(self.0.difference(other.0)) } /// Returns the [symmetric difference][sym-diff] between the flags diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -656,7 +670,7 @@ macro_rules! __impl_bitflags { #[inline] #[must_use] pub const fn symmetric_difference(self, other: Self) -> Self { - Self { bits: self.bits ^ other.bits } + Self(self.0.symmetric_difference(other.0)) } /// Returns the complement of this set of flags. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -675,159 +689,101 @@ macro_rules! __impl_bitflags { #[inline] #[must_use] pub const fn complement(self) -> Self { - Self::from_bits_truncate(!self.bits) + Self(self.0.complement()) } /// Returns an iterator over set flags and their names. pub fn iter(self) -> impl $crate::__private::core::iter::Iterator<Item = (&'static str, Self)> { use $crate::__private::core::iter::Iterator as _; - const NUM_FLAGS: usize = { - let mut num_flags = 0; - - $( - $(#[$attr $($args)*])* - { - num_flags += 1; - } - )* - - num_flags - }; - - const OPTIONS: [$BitFlags; NUM_FLAGS] = [ - $( - $(#[$attr $($args)*])* - $BitFlags::$Flag, - )* - ]; - - const OPTIONS_NAMES: [&'static str; NUM_FLAGS] = [ - $( - $(#[$attr $($args)*])* - $crate::__private::core::stringify!($Flag), - )* - ]; - - let mut start = 0; - let mut state = self; - - $crate::__private::core::iter::from_fn(move || { - if state.is_empty() || NUM_FLAGS == 0 { - $crate::__private::core::option::Option::None - } else { - for (flag, flag_name) in OPTIONS[start..NUM_FLAGS].iter().copied() - .zip(OPTIONS_NAMES[start..NUM_FLAGS].iter().copied()) - { - start += 1; - - // 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: - // - // 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.contains(flag) { - state.remove(flag); - - return $crate::__private::core::option::Option::Some((flag_name, flag)) - } - } - - $crate::__private::core::option::Option::None - } - }) + self.0.iter().map(|(name, bits)| (name, Self::from_bits_retain(bits))) } } - impl $crate::__private::core::ops::BitOr for $BitFlags { + impl $crate::__private::core::ops::BitOr for $PublicBitFlags { type Output = Self; /// Returns the union of the two sets of flags. #[inline] - fn bitor(self, other: $BitFlags) -> Self { - Self { bits: self.bits | other.bits } + fn bitor(self, other: $PublicBitFlags) -> Self { + self.union(other) } } - impl $crate::__private::core::ops::BitOrAssign for $BitFlags { + impl $crate::__private::core::ops::BitOrAssign for $PublicBitFlags { /// Adds the set of flags. #[inline] fn bitor_assign(&mut self, other: Self) { - self.bits |= other.bits; + self.0 = self.0.union(other.0); } } - impl $crate::__private::core::ops::BitXor for $BitFlags { + impl $crate::__private::core::ops::BitXor for $PublicBitFlags { type Output = Self; /// Returns the left flags, but with all the right flags toggled. #[inline] fn bitxor(self, other: Self) -> Self { - Self { bits: self.bits ^ other.bits } + self.symmetric_difference(other) } } - impl $crate::__private::core::ops::BitXorAssign for $BitFlags { + impl $crate::__private::core::ops::BitXorAssign for $PublicBitFlags { /// Toggles the set of flags. #[inline] fn bitxor_assign(&mut self, other: Self) { - self.bits ^= other.bits; + self.0 = self.0.symmetric_difference(other.0); } } - impl $crate::__private::core::ops::BitAnd for $BitFlags { + impl $crate::__private::core::ops::BitAnd for $PublicBitFlags { type Output = Self; /// Returns the intersection between the two sets of flags. #[inline] fn bitand(self, other: Self) -> Self { - Self { bits: self.bits & other.bits } + self.intersection(other) } } - impl $crate::__private::core::ops::BitAndAssign for $BitFlags { + impl $crate::__private::core::ops::BitAndAssign for $PublicBitFlags { /// Disables all flags disabled in the set. #[inline] fn bitand_assign(&mut self, other: Self) { - self.bits &= other.bits; + self.0 = self.0.intersection(other.0); } } - impl $crate::__private::core::ops::Sub for $BitFlags { + impl $crate::__private::core::ops::Sub for $PublicBitFlags { type Output = Self; /// Returns the set difference of the two sets of flags. #[inline] fn sub(self, other: Self) -> Self { - Self { bits: self.bits & !other.bits } + self.difference(other) } } - impl $crate::__private::core::ops::SubAssign for $BitFlags { + impl $crate::__private::core::ops::SubAssign for $PublicBitFlags { /// Disables all flags enabled in the set. #[inline] fn sub_assign(&mut self, other: Self) { - self.bits &= !other.bits; + self.0 = self.0.difference(other.0); } } - impl $crate::__private::core::ops::Not for $BitFlags { + impl $crate::__private::core::ops::Not for $PublicBitFlags { type Output = Self; /// Returns the complement of this set of flags. #[inline] fn not(self) -> Self { - Self { bits: !self.bits } & Self::all() + self.complement() } } - impl $crate::__private::core::iter::Extend<$BitFlags> for $BitFlags { + impl $crate::__private::core::iter::Extend<$PublicBitFlags> for $PublicBitFlags { 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/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -835,7 +791,7 @@ macro_rules! __impl_bitflags { } } - impl $crate::__private::core::iter::FromIterator<$BitFlags> for $BitFlags { + impl $crate::__private::core::iter::FromIterator<$PublicBitFlags> for $PublicBitFlags { fn from_iter<T: $crate::__private::core::iter::IntoIterator<Item=Self>>(iterator: T) -> Self { use $crate::__private::core::iter::Extend; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -845,181 +801,421 @@ macro_rules! __impl_bitflags { } } - impl $crate::BitFlags for $BitFlags { + impl $crate::BitFlags for $PublicBitFlags { type Bits = $T; fn empty() -> Self { - $BitFlags::empty() + $PublicBitFlags::empty() } fn all() -> Self { - $BitFlags::all() + $PublicBitFlags::all() } fn bits(&self) -> $T { - $BitFlags::bits(self) + $PublicBitFlags::bits(self) } - fn from_bits(bits: $T) -> $crate::__private::core::option::Option<$BitFlags> { - $BitFlags::from_bits(bits) + fn from_bits(bits: $T) -> $crate::__private::core::option::Option<$PublicBitFlags> { + $PublicBitFlags::from_bits(bits) } - fn from_bits_truncate(bits: $T) -> $BitFlags { - $BitFlags::from_bits_truncate(bits) + fn from_bits_truncate(bits: $T) -> $PublicBitFlags { + $PublicBitFlags::from_bits_truncate(bits) } - unsafe fn from_bits_unchecked(bits: $T) -> $BitFlags { - $BitFlags::from_bits_unchecked(bits) + fn from_bits_retain(bits: $T) -> $PublicBitFlags { + $PublicBitFlags::from_bits_retain(bits) } fn is_empty(&self) -> bool { - $BitFlags::is_empty(self) + $PublicBitFlags::is_empty(self) } fn is_all(&self) -> bool { - $BitFlags::is_all(self) + $PublicBitFlags::is_all(self) } - fn intersects(&self, other: $BitFlags) -> bool { - $BitFlags::intersects(self, other) + fn intersects(&self, other: $PublicBitFlags) -> bool { + $PublicBitFlags::intersects(self, other) } - fn contains(&self, other: $BitFlags) -> bool { - $BitFlags::contains(self, other) + fn contains(&self, other: $PublicBitFlags) -> bool { + $PublicBitFlags::contains(self, other) } - fn insert(&mut self, other: $BitFlags) { - $BitFlags::insert(self, other) + fn insert(&mut self, other: $PublicBitFlags) { + $PublicBitFlags::insert(self, other) } - fn remove(&mut self, other: $BitFlags) { - $BitFlags::remove(self, other) + fn remove(&mut self, other: $PublicBitFlags) { + $PublicBitFlags::remove(self, other) } - fn toggle(&mut self, other: $BitFlags) { - $BitFlags::toggle(self, other) + fn toggle(&mut self, other: $PublicBitFlags) { + $PublicBitFlags::toggle(self, other) } - fn set(&mut self, other: $BitFlags, value: bool) { - $BitFlags::set(self, other, value) + fn set(&mut self, other: $PublicBitFlags, value: bool) { + $PublicBitFlags::set(self, other, value) } } - impl $crate::__private::ImplementedByBitFlagsMacro for $BitFlags {} + impl $crate::__private::ImplementedByBitFlagsMacro for $PublicBitFlags {} }; +} - // Every attribute that the user writes on a const is applied to the - // corresponding const that we generate, but within the implementation of - // Debug and all() we want to ignore everything but #[cfg] attributes. In - // particular, including a #[deprecated] attribute on those items would fail - // to compile. - // https://github.com/bitflags/bitflags/issues/109 - // - // Input: - // - // ? #[cfg(feature = "advanced")] - // ? #[deprecated(note = "Use something else.")] - // ? #[doc = r"High quality documentation."] - // fn f() -> i32 { /* ... */ } - // - // Output: - // - // #[cfg(feature = "advanced")] - // fn f() -> i32 { /* ... */ } +/// Implement functions on the private (bitflags-facing) bitflags type. +/// +/// Methods and trait implementations can be freely added here without breaking end-users. +/// If we want to expose new functionality to `#[derive]`, this is the place to do it. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_internal_bitflags { ( - $(#[$filtered:meta])* - ? #[cfg $($cfgargs:tt)*] - $(? #[$rest:ident $($restargs:tt)*])* - fn $($item:tt)* - ) => { - __impl_bitflags! { - $(#[$filtered])* - #[cfg $($cfgargs)*] - $(? #[$rest $($restargs)*])* - fn $($item)* + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* } - }; - ( - $(#[$filtered:meta])* - // $next != `cfg` - ? #[$next:ident $($nextargs:tt)*] - $(? #[$rest:ident $($restargs:tt)*])* - fn $($item:tt)* ) => { - __impl_bitflags! { - $(#[$filtered])* - // $next filtered out - $(? #[$rest $($restargs)*])* - fn $($item)* + // Any new library traits impls should be added here + __impl_internal_bitflags_serde! { + $InternalBitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } } - }; - ( - $(#[$filtered:meta])* - fn $($item:tt)* - ) => { - $(#[$filtered])* - fn $($item)* - }; - // Every attribute that the user writes on a const is applied to the - // corresponding const that we generate, but within the implementation of - // Debug and all() we want to ignore everything but #[cfg] attributes. In - // particular, including a #[deprecated] attribute on those items would fail - // to compile. - // https://github.com/bitflags/bitflags/issues/109 - // - // const version - // - // Input: - // - // ? #[cfg(feature = "advanced")] - // ? #[deprecated(note = "Use something else.")] - // ? #[doc = r"High quality documentation."] - // const f: i32 { /* ... */ } - // - // Output: - // - // #[cfg(feature = "advanced")] - // const f: i32 { /* ... */ } - ( - $(#[$filtered:meta])* - ? #[cfg $($cfgargs:tt)*] - $(? #[$rest:ident $($restargs:tt)*])* - const $($item:tt)* - ) => { - __impl_bitflags! { - $(#[$filtered])* - #[cfg $($cfgargs)*] - $(? #[$rest $($restargs)*])* - const $($item)* + impl $crate::__private::core::default::Default for $InternalBitFlags { + #[inline] + fn default() -> Self { + $InternalBitFlags::empty() + } + } + + impl $crate::__private::core::fmt::Debug for $InternalBitFlags { + fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + // Iterate over the valid flags + let mut first = true; + for (name, _) in self.iter() { + if !first { + f.write_str(" | ")?; + } + + first = false; + f.write_str(name)?; + } + + // Append any extra bits that correspond to flags to the end of the format + let extra_bits = self.bits & !Self::all().bits; + + if extra_bits != <$T as $crate::__private::Bits>::EMPTY { + if !first { + f.write_str(" | ")?; + } + first = false; + $crate::__private::core::write!(f, "{:#x}", extra_bits)?; + } + + if first { + f.write_str("empty")?; + } + + $crate::__private::core::fmt::Result::Ok(()) + } + } + + impl $crate::__private::core::fmt::Binary for $InternalBitFlags { + fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + $crate::__private::core::fmt::Binary::fmt(&self.bits(), f) + } + } + + impl $crate::__private::core::fmt::Octal for $InternalBitFlags { + fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + $crate::__private::core::fmt::Octal::fmt(&self.bits(), f) + } + } + + impl $crate::__private::core::fmt::LowerHex for $InternalBitFlags { + fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + $crate::__private::core::fmt::LowerHex::fmt(&self.bits(), f) + } + } + + impl $crate::__private::core::fmt::UpperHex for $InternalBitFlags { + fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter) -> $crate::__private::core::fmt::Result { + $crate::__private::core::fmt::UpperHex::fmt(&self.bits(), f) + } + } + + #[allow( + dead_code, + deprecated, + unused_doc_comments, + unused_attributes, + unused_mut, + non_upper_case_globals + )] + impl $InternalBitFlags { + #[inline] + pub const fn empty() -> Self { + Self { bits: <$T as $crate::__private::Bits>::EMPTY } + } + + #[inline] + pub const fn all() -> Self { + Self::from_bits_truncate(<$T as $crate::__private::Bits>::ALL) + } + + #[inline] + pub const fn bits(&self) -> $T { + self.bits + } + + #[inline] + pub fn bits_mut(&mut self) -> &mut $T { + &mut self.bits + } + + #[inline] + pub const fn from_bits(bits: $T) -> $crate::__private::core::option::Option<Self> { + let truncated = Self::from_bits_truncate(bits).bits; + + if truncated == bits { + $crate::__private::core::option::Option::Some(Self { bits }) + } else { + $crate::__private::core::option::Option::None + } + } + + #[inline] + pub const fn from_bits_truncate(bits: $T) -> Self { + if bits == <$T as $crate::__private::Bits>::EMPTY { + return Self { bits } + } + + let mut truncated = <$T as $crate::__private::Bits>::EMPTY; + + $( + $(#[$attr $($args)*])* + if bits & <$InternalBitFlags as $crate::__private::InternalFlags>::PublicFlags::$Flag.bits() == <$InternalBitFlags as $crate::__private::InternalFlags>::PublicFlags::$Flag.bits() { + truncated |= <$InternalBitFlags as $crate::__private::InternalFlags>::PublicFlags::$Flag.bits() + } + )* + + Self { bits: truncated } + } + + #[inline] + pub const fn from_bits_retain(bits: $T) -> Self { + Self { bits } + } + + #[inline] + pub const fn is_empty(&self) -> bool { + self.bits == Self::empty().bits + } + + #[inline] + pub const fn is_all(&self) -> bool { + Self::all().bits | self.bits == self.bits + } + + #[inline] + pub const fn intersects(&self, other: Self) -> bool { + !(Self { bits: self.bits & other.bits}).is_empty() + } + + #[inline] + pub const fn contains(&self, other: Self) -> bool { + (self.bits & other.bits) == other.bits + } + + #[inline] + pub fn insert(&mut self, other: Self) { + self.bits |= other.bits; + } + + #[inline] + pub fn remove(&mut self, other: Self) { + self.bits &= !other.bits; + } + + #[inline] + pub fn toggle(&mut self, other: Self) { + self.bits ^= other.bits; + } + + #[inline] + pub fn set(&mut self, other: Self, value: bool) { + if value { + self.insert(other); + } else { + self.remove(other); + } + } + + #[inline] + #[must_use] + pub const fn intersection(self, other: Self) -> Self { + Self { bits: self.bits & other.bits } + } + + #[inline] + #[must_use] + pub const fn union(self, other: Self) -> Self { + Self { bits: self.bits | other.bits } + } + + #[inline] + #[must_use] + pub const fn difference(self, other: Self) -> Self { + Self { bits: self.bits & !other.bits } + } + + #[inline] + #[must_use] + pub const fn symmetric_difference(self, other: Self) -> Self { + Self { bits: self.bits ^ other.bits } + } + + #[inline] + #[must_use] + pub const fn complement(self) -> Self { + Self::from_bits_truncate(!self.bits) + } + + pub fn iter(self) -> impl $crate::__private::core::iter::Iterator<Item = (&'static str, $T)> { + use $crate::__private::core::iter::Iterator as _; + + const NUM_FLAGS: usize = { + let mut num_flags = 0; + + $( + $(#[$attr $($args)*])* + { + num_flags += 1; + } + )* + + num_flags + }; + + const OPTIONS: [$T; NUM_FLAGS] = [ + $( + $(#[$attr $($args)*])* + <$InternalBitFlags as $crate::__private::InternalFlags>::PublicFlags::$Flag.bits(), + )* + ]; + + const OPTIONS_NAMES: [&'static str; NUM_FLAGS] = [ + $( + $(#[$attr $($args)*])* + $crate::__private::core::stringify!($Flag), + )* + ]; + + let mut start = 0; + let mut state = self; + + $crate::__private::core::iter::from_fn(move || { + if state.is_empty() || NUM_FLAGS == 0 { + $crate::__private::core::option::Option::None + } else { + for (flag, flag_name) in OPTIONS[start..NUM_FLAGS].iter().copied() + .zip(OPTIONS_NAMES[start..NUM_FLAGS].iter().copied()) + { + start += 1; + + // 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: + // + // 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.contains(Self { bits: flag }) { + state.remove(Self { bits: flag }); + + return $crate::__private::core::option::Option::Some((flag_name, flag)) + } + } + + $crate::__private::core::option::Option::None + } + }) + } } }; +} + +// Optional features +// +// These macros implement additional library traits for the internal bitflags type so that +// the end-user can either implement or derive those same traits based on the implementation +// we provide in `bitflags`. +// +// These macros all follow a similar pattern. If an optional feature of `bitflags` is enabled +// they'll expand to some impl blocks based on a re-export of the library. If the optional feature +// is not enabled then they expand to a no-op. + +/// Implement `Serialize` and `Deserialize` for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(feature = "serde")] +macro_rules! __impl_internal_bitflags_serde { ( - $(#[$filtered:meta])* - // $next != `cfg` - ? #[$next:ident $($nextargs:tt)*] - $(? #[$rest:ident $($restargs:tt)*])* - const $($item:tt)* + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } ) => { - __impl_bitflags! { - $(#[$filtered])* - // $next filtered out - $(? #[$rest $($restargs)*])* - const $($item)* + impl $crate::__private::serde::Serialize for $InternalBitFlags { + fn serialize<S: $crate::__private::serde::Serializer>(&self, serializer: S) -> $crate::__private::core::result::Result<S::Ok, S::Error> { + $crate::serde_support::serialize_bits_default($crate::__private::core::stringify!($InternalBitFlags), &self.bits, serializer) + } } - }; + + impl<'de> $crate::__private::serde::Deserialize<'de> for $InternalBitFlags { + fn deserialize<D: $crate::__private::serde::Deserializer<'de>>(deserializer: D) -> $crate::__private::core::result::Result<Self, D::Error> { + let bits = $crate::serde_support::deserialize_bits_default($crate::__private::core::stringify!($InternalBitFlags), deserializer)?; + + $crate::__private::core::result::Result::Ok($InternalBitFlags::from_bits_retain(bits)) + } + } + } +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "serde"))] +macro_rules! __impl_internal_bitflags_serde { ( - $(#[$filtered:meta])* - const $($item:tt)* - ) => { - $(#[$filtered])* - const $($item)* - }; + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { } } #[cfg(feature = "example_generated")] pub mod example_generated; +#[cfg(feature = "serde")] +pub mod serde_support; + #[cfg(test)] mod tests { use std::collections::hash_map::DefaultHasher; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1030,7 +1226,7 @@ mod tests { #[doc = "> you are the easiest person to fool."] #[doc = "> "] #[doc = "> - Richard Feynman"] - #[derive(Default)] + #[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"] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1039,28 +1235,32 @@ mod tests { #[doc = "* cmr bed"] #[doc = "* strcat table"] #[doc = "<strcat> wait what?"] - const ABC = Self::A.bits | Self::B.bits | Self::C.bits; + 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; + 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; } } bitflags! { + #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] struct EmptyFlags: u32 { } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1113,28 +1313,28 @@ mod tests { } #[test] - fn test_from_bits_unchecked() { - let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; - assert_eq!(unsafe { Flags::from_bits_unchecked(0) }, Flags::empty()); - assert_eq!(unsafe { Flags::from_bits_unchecked(0b1) }, Flags::A); - assert_eq!(unsafe { Flags::from_bits_unchecked(0b10) }, Flags::B); + 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!( - unsafe { Flags::from_bits_unchecked(0b11) }, + Flags::from_bits_retain(0b11), (Flags::A | Flags::B) ); assert_eq!( - unsafe { Flags::from_bits_unchecked(0b1000) }, + Flags::from_bits_retain(0b1000), (extra | Flags::empty()) ); assert_eq!( - unsafe { Flags::from_bits_unchecked(0b1001) }, + Flags::from_bits_retain(0b1001), (extra | Flags::A) ); - let extra = unsafe { EmptyFlags::from_bits_unchecked(0b1000) }; + let extra = EmptyFlags::from_bits_retain(0b1000); assert_eq!( - unsafe { EmptyFlags::from_bits_unchecked(0b1000) }, + EmptyFlags::from_bits_retain(0b1000), (extra | EmptyFlags::empty()) ); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1157,7 +1357,7 @@ mod tests { assert!(!Flags::A.is_all()); assert!(Flags::ABC.is_all()); - let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + let extra = Flags::from_bits_retain(0b1000); assert!(!extra.is_all()); assert!(!(Flags::A | extra).is_all()); assert!((Flags::ABC | extra).is_all()); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1255,7 +1455,7 @@ mod tests { #[test] fn test_operators_unchecked() { - let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + 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 diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1274,9 +1474,9 @@ mod tests { 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.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)); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1329,10 +1529,10 @@ mod tests { #[test] fn test_set_ops_unchecked() { - let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + 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.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); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1346,11 +1546,12 @@ mod tests { 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_unchecked`). + // `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; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1364,12 +1565,12 @@ mod tests { } } let iter_test_flags = - || (0..=0b111_1111_1111).map(|bits| unsafe { Test::from_bits_unchecked(bits) }); + || (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), + Test::from_bits_truncate(!a.bits()), "wrong result: !({:?})", a, ); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1378,37 +1579,37 @@ mod tests { // Check that the named operations produce the expected bitwise // values. assert_eq!( - a.union(b).bits, - a.bits | b.bits, + a.union(b).bits(), + a.bits() | b.bits(), "wrong result: `{:?}` | `{:?}`", a, b, ); assert_eq!( - a.intersection(b).bits, - a.bits & b.bits, + a.intersection(b).bits(), + a.bits() & b.bits(), "wrong result: `{:?}` & `{:?}`", a, b, ); assert_eq!( - a.symmetric_difference(b).bits, - a.bits ^ b.bits, + a.symmetric_difference(b).bits(), + a.bits() ^ b.bits(), "wrong result: `{:?}` ^ `{:?}`", a, b, ); assert_eq!( - a.difference(b).bits, - a.bits & !b.bits, + 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, + b.difference(a).bits(), + b.bits() & !a.bits(), "wrong result: `{:?}` - `{:?}`", b, a, diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1577,28 +1778,28 @@ mod tests { #[test] fn test_debug() { - assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); - assert_eq!(format!("{:?}", Flags::empty()), "(empty)"); - assert_eq!(format!("{:?}", Flags::ABC), "A | B | C"); + assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)"); + assert_eq!(format!("{:?}", Flags::empty()), "Flags(empty)"); + assert_eq!(format!("{:?}", Flags::ABC), "Flags(A | B | C)"); - let extra = unsafe { Flags::from_bits_unchecked(0xb8) }; + let extra = Flags::from_bits_retain(0xb8); - assert_eq!(format!("{:?}", extra), "0xb8"); - assert_eq!(format!("{:?}", Flags::A | extra), "A | 0xb8"); + assert_eq!(format!("{:?}", extra), "Flags(0xb8)"); + assert_eq!(format!("{:?}", Flags::A | extra), "Flags(A | 0xb8)"); assert_eq!( format!("{:?}", Flags::ABC | extra), - "A | B | C | ABC | 0xb8" + "Flags(A | B | C | ABC | 0xb8)" ); - assert_eq!(format!("{:?}", EmptyFlags::empty()), "(empty)"); + assert_eq!(format!("{:?}", EmptyFlags::empty()), "EmptyFlags(empty)"); } #[test] fn test_binary() { assert_eq!(format!("{:b}", Flags::ABC), "111"); assert_eq!(format!("{:#b}", Flags::ABC), "0b111"); - let extra = unsafe { Flags::from_bits_unchecked(0b1010000) }; + let extra = Flags::from_bits_retain(0b1010000); assert_eq!(format!("{:b}", Flags::ABC | extra), "1010111"); assert_eq!(format!("{:#b}", Flags::ABC | extra), "0b1010111"); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1607,7 +1808,7 @@ mod tests { fn test_octal() { assert_eq!(format!("{:o}", LongFlags::LONG_A), "177777"); assert_eq!(format!("{:#o}", LongFlags::LONG_A), "0o177777"); - let extra = unsafe { LongFlags::from_bits_unchecked(0o5000000) }; + 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"); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1616,7 +1817,7 @@ mod tests { fn test_lowerhex() { assert_eq!(format!("{:x}", LongFlags::LONG_A), "ffff"); assert_eq!(format!("{:#x}", LongFlags::LONG_A), "0xffff"); - let extra = unsafe { LongFlags::from_bits_unchecked(0xe00000) }; + 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"); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1625,17 +1826,19 @@ mod tests { fn test_upperhex() { assert_eq!(format!("{:X}", LongFlags::LONG_A), "FFFF"); assert_eq!(format!("{:#X}", LongFlags::LONG_A), "0xFFFF"); - let extra = unsafe { LongFlags::from_bits_unchecked(0xe00000) }; + 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; } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1659,6 +1862,7 @@ mod tests { bitflags! { /// baz + #[derive(Clone, Copy)] struct Flags: foo::Bar { const A = 0b00000001; #[cfg(foo)] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1672,19 +1876,21 @@ mod tests { #[test] fn test_in_function() { bitflags! { - struct Flags: u8 { + #[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), "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; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1696,6 +1902,7 @@ mod tests { fn test_pub_crate() { mod module { bitflags! { + #[derive(Clone, Copy)] pub (crate) struct Test: u8 { const FOO = 1; } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1712,6 +1919,7 @@ mod tests { 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; } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1737,6 +1945,7 @@ mod tests { #[test] fn test_zero_value_flags() { bitflags! { + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Flags: u32 { const NONE = 0b0; const SOME = 0b1; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1747,8 +1956,8 @@ mod tests { assert!(Flags::SOME.contains(Flags::NONE)); assert!(Flags::NONE.is_empty()); - assert_eq!(format!("{:?}", Flags::empty()), "(empty)"); - assert_eq!(format!("{:?}", Flags::SOME), "NONE | SOME"); + assert_eq!(format!("{:?}", Flags::empty()), "Flags(empty)"); + assert_eq!(format!("{:?}", Flags::SOME), "Flags(NONE | SOME)"); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1759,69 +1968,33 @@ mod tests { #[test] fn test_u128_bitflags() { bitflags! { - struct Flags128: u128 { + #[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; + const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } } - assert_eq!(Flags128::ABC, Flags128::A | Flags128::B | Flags128::C); - assert_eq!(Flags128::A.bits, 0x0000_0000_0000_0000_0000_0000_0000_0001); - assert_eq!(Flags128::B.bits, 0x0000_0000_0000_1000_0000_0000_0000_0000); - assert_eq!(Flags128::C.bits, 0x8000_0000_0000_0000_0000_0000_0000_0000); + 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!( - Flags128::ABC.bits, + Flags::ABC.bits(), 0x8000_0000_0000_1000_0000_0000_0000_0001 ); - assert_eq!(format!("{:?}", Flags128::A), "A"); - assert_eq!(format!("{:?}", Flags128::B), "B"); - assert_eq!(format!("{:?}", Flags128::C), "C"); - assert_eq!(format!("{:?}", Flags128::ABC), "A | B | C"); - } - - #[test] - fn test_serde_bitflags_serialize() { - let flags = SerdeFlags::A | SerdeFlags::B; - - let serialized = serde_json::to_string(&flags).unwrap(); - - assert_eq!(serialized, r#"{"bits":3}"#); - } - - #[test] - fn test_serde_bitflags_deserialize() { - let deserialized: SerdeFlags = serde_json::from_str(r#"{"bits":12}"#).unwrap(); - - let expected = SerdeFlags::C | SerdeFlags::D; - - assert_eq!(deserialized.bits, expected.bits); - } - - #[test] - fn test_serde_bitflags_roundtrip() { - let flags = SerdeFlags::A | SerdeFlags::B; - - let deserialized: SerdeFlags = - serde_json::from_str(&serde_json::to_string(&flags).unwrap()).unwrap(); - - assert_eq!(deserialized.bits, flags.bits); - } - - bitflags! { - #[derive(serde_derive::Serialize, serde_derive::Deserialize)] - struct SerdeFlags: u32 { - const A = 1; - const B = 2; - const C = 4; - const D = 8; - } + 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; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1837,6 +2010,7 @@ mod tests { #[test] fn test_from_bits_truncate_edge_cases() { bitflags! { + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Flags: u8 { const A = 0b00000001; const BC = 0b00000110; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1852,6 +2026,7 @@ mod tests { #[test] fn test_iter() { bitflags! { + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Flags: u32 { const ONE = 0b001; const TWO = 0b010; diff --git /dev/null b/src/serde_support.rs new file mode 100644 --- /dev/null +++ b/src/serde_support.rs @@ -0,0 +1,84 @@ +use core::fmt; +use serde::{Serializer, Deserializer, Serialize, Deserialize, ser::SerializeStruct, de::{Error, MapAccess, Visitor}}; + +// These methods are compatible with the result of `#[derive(Serialize, Deserialize)]` on bitflags `1.0` types + +pub fn serialize_bits_default<B: Serialize, S: Serializer>(name: &'static str, bits: &B, serializer: S) -> Result<S::Ok, S::Error> { + let mut serialize_struct = serializer.serialize_struct(name, 1)?; + serialize_struct.serialize_field("bits", bits)?; + serialize_struct.end() +} + +pub fn deserialize_bits_default<'de, B: Deserialize<'de>, D: Deserializer<'de>>(name: &'static str, deserializer: D) -> Result<B, D::Error> { + struct BitsVisitor<T>(core::marker::PhantomData<T>); + + impl<'de, T: Deserialize<'de>> Visitor<'de> for BitsVisitor<T> { + type Value = T; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a primitive bitflags value wrapped in a struct") + } + + fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> { + let mut bits = None; + + while let Some(key) = map.next_key()? { + match key { + "bits" => { + if bits.is_some() { + return Err(Error::duplicate_field("bits")); + } + + bits = Some(map.next_value()?); + } + v => return Err(Error::unknown_field(v, &["bits"])) + } + } + + bits.ok_or_else(|| Error::missing_field("bits")) + } + } + + deserializer.deserialize_struct(name, &["bits"], BitsVisitor(Default::default())) +} + +#[cfg(test)] +mod tests { + bitflags! { + #[derive(serde_derive::Serialize, serde_derive::Deserialize)] + struct SerdeFlags: u32 { + const A = 1; + const B = 2; + const C = 4; + const D = 8; + } + } + + #[test] + fn test_serde_bitflags_default_serialize() { + let flags = SerdeFlags::A | SerdeFlags::B; + + let serialized = serde_json::to_string(&flags).unwrap(); + + assert_eq!(serialized, r#"{"bits":3}"#); + } + + #[test] + fn test_serde_bitflags_default_deserialize() { + let deserialized: SerdeFlags = serde_json::from_str(r#"{"bits":12}"#).unwrap(); + + let expected = SerdeFlags::C | SerdeFlags::D; + + assert_eq!(deserialized.bits(), expected.bits()); + } + + #[test] + fn test_serde_bitflags_default_roundtrip() { + let flags = SerdeFlags::A | SerdeFlags::B; + + let deserialized: SerdeFlags = + serde_json::from_str(&serde_json::to_string(&flags).unwrap()).unwrap(); + + assert_eq!(deserialized.bits(), flags.bits()); + } +} \ No newline at end of file diff --git a/tests/compile-fail/impls/copy.stderr /dev/null --- a/tests/compile-fail/impls/copy.stderr +++ /dev/null @@ -1,27 +0,0 @@ -error[E0119]: conflicting implementations of trait `std::marker::Copy` for type `Flags` - --> $DIR/copy.rs:3:1 - | -3 | / bitflags! { -4 | | #[derive(Clone, Copy)] - | | ---- first implementation here -5 | | struct Flags: u32 { -6 | | const A = 0b00000001; -7 | | } -8 | | } - | |_^ conflicting implementation for `Flags` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0119]: conflicting implementations of trait `std::clone::Clone` for type `Flags` - --> $DIR/copy.rs:3:1 - | -3 | / bitflags! { -4 | | #[derive(Clone, Copy)] - | | ----- first implementation here -5 | | struct Flags: u32 { -6 | | const A = 0b00000001; -7 | | } -8 | | } - | |_^ conflicting implementation for `Flags` - | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/compile-fail/impls/eq.stderr /dev/null --- a/tests/compile-fail/impls/eq.stderr +++ /dev/null @@ -1,55 +0,0 @@ -error[E0119]: conflicting implementations of trait `std::marker::StructuralPartialEq` for type `Flags` - --> $DIR/eq.rs:3:1 - | -3 | / bitflags! { -4 | | #[derive(PartialEq, Eq)] - | | --------- first implementation here -5 | | struct Flags: u32 { -6 | | const A = 0b00000001; -7 | | } -8 | | } - | |_^ conflicting implementation for `Flags` - | - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0119]: conflicting implementations of trait `std::cmp::PartialEq` for type `Flags` - --> $DIR/eq.rs:3:1 - | -3 | / bitflags! { -4 | | #[derive(PartialEq, Eq)] - | | --------- first implementation here -5 | | struct Flags: u32 { -6 | | const A = 0b00000001; -7 | | } -8 | | } - | |_^ conflicting implementation for `Flags` - | - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0119]: conflicting implementations of trait `std::marker::StructuralEq` for type `Flags` - --> $DIR/eq.rs:3:1 - | -3 | / bitflags! { -4 | | #[derive(PartialEq, Eq)] - | | -- first implementation here -5 | | struct Flags: u32 { -6 | | const A = 0b00000001; -7 | | } -8 | | } - | |_^ conflicting implementation for `Flags` - | - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0119]: conflicting implementations of trait `std::cmp::Eq` for type `Flags` - --> $DIR/eq.rs:3:1 - | -3 | / bitflags! { -4 | | #[derive(PartialEq, Eq)] - | | -- first implementation here -5 | | struct Flags: u32 { -6 | | const A = 0b00000001; -7 | | } -8 | | } - | |_^ conflicting implementation for `Flags` - | - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -4,6 +4,16 @@ error[E0277]: the trait bound `MyInt: Bits` is not satisfied 116 | struct Flags128: MyInt { | ^^^^^ the trait `Bits` is not implemented for `MyInt` | + = help: the following other types implement trait `Bits`: + i128 + i16 + i32 + i64 + i8 + u128 + u16 + u32 + and 2 others note: required by a bound in `bitflags::BitFlags::Bits` --> src/bitflags_trait.rs | diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -22,7 +32,17 @@ error[E0277]: the trait bound `MyInt: Bits` is not satisfied 121 | | } | |_^ the trait `Bits` is not implemented for `MyInt` | - = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + = help: the following other types implement trait `Bits`: + i128 + i16 + i32 + i64 + i8 + u128 + u16 + u32 + and 2 others + = note: this error originates in the macro `__impl_internal_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: Bits` is not satisfied --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -36,7 +56,17 @@ error[E0277]: the trait bound `MyInt: Bits` is not satisfied 121 | | } | |_^ the trait `Bits` is not implemented for `MyInt` | - = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + = help: the following other types implement trait `Bits`: + i128 + i16 + i32 + i64 + i8 + u128 + u16 + u32 + and 2 others + = note: this error originates in the macro `__impl_internal_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: Bits` is not satisfied --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -50,7 +80,69 @@ error[E0277]: the trait bound `MyInt: Bits` is not satisfied 121 | | } | |_^ the trait `Bits` is not implemented for `MyInt` | - = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + = help: the following other types implement trait `Bits`: + i128 + i16 + i32 + i64 + i8 + u128 + u16 + u32 + and 2 others + = note: this error originates in the macro `__impl_internal_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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ 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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ + = note: this error originates in the macro `__impl_internal_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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ 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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ + = note: this error originates in the macro `__impl_internal_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: Bits` is not satisfied --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ b/tests/compile-fail/non_integer_base/all_defined.stderr @@ -64,4 +156,142 @@ error[E0277]: the trait bound `MyInt: Bits` is not satisfied 121 | | } | |_^ the trait `Bits` is not implemented for `MyInt` | - = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + = help: the following other types implement trait `Bits`: + i128 + i16 + i32 + i64 + i8 + u128 + u16 + u32 + and 2 others + = note: this error originates in the macro `__impl_internal_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: Bits` is not satisfied + --> tests/compile-fail/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ the trait `Bits` is not implemented for `MyInt` + | + = help: the following other types implement trait `Bits`: + i128 + i16 + i32 + i64 + i8 + u128 + u16 + u32 + and 2 others + = note: this error originates in the macro `__impl_internal_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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ 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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ + = note: this error originates in the macro `__impl_internal_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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ 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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ + = note: this error originates in the macro `__impl_internal_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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ 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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ + = note: this error originates in the macro `__impl_internal_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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ 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/non_integer_base/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ + = note: this error originates in the macro `__impl_internal_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/compile-fail/non_integer_base/all_missing.stderr b/tests/compile-fail/non_integer_base/all_missing.stderr --- a/tests/compile-fail/non_integer_base/all_missing.stderr +++ b/tests/compile-fail/non_integer_base/all_missing.stderr @@ -1,5 +1,5 @@ error[E0204]: the trait `Copy` may not be implemented for this type - --> $DIR/all_missing.rs:5:1 + --> tests/compile-fail/non_integer_base/all_missing.rs:5:1 | 5 | / bitflags! { 6 | | struct Flags128: MyInt { diff --git a/tests/compile-fail/non_integer_base/all_missing.stderr b/tests/compile-fail/non_integer_base/all_missing.stderr --- a/tests/compile-fail/non_integer_base/all_missing.stderr +++ b/tests/compile-fail/non_integer_base/all_missing.stderr @@ -10,4 +10,4 @@ error[E0204]: the trait `Copy` may not be implemented for this type 11 | | } | |_^ this field does not implement `Copy` | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the derive macro `Copy` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git /dev/null b/tests/compile-fail/redefined.rs new file mode 100644 --- /dev/null +++ b/tests/compile-fail/redefined.rs @@ -0,0 +1,14 @@ +#[macro_use] +extern crate bitflags; + +bitflags! { + pub struct Flags1 { + const A = 1; + } +} + +bitflags! { + pub struct Flags1 { + const A = 1; + } +} diff --git /dev/null b/tests/compile-fail/redefined.stderr new file mode 100644 --- /dev/null +++ b/tests/compile-fail/redefined.stderr @@ -0,0 +1,17 @@ +error: no rules expected the token `{` + --> tests/compile-fail/redefined.rs:5:23 + | +5 | pub struct Flags1 { + | ^ no rules expected this token in macro call + +error: no rules expected the token `{` + --> tests/compile-fail/redefined.rs:11:23 + | +11 | pub struct Flags1 { + | ^ no rules expected this token in macro call + +error[E0601]: `main` function not found in crate `$CRATE` + --> tests/compile-fail/redefined.rs:14:2 + | +14 | } + | ^ consider adding a `main` function to `$DIR/tests/compile-fail/redefined.rs` diff --git /dev/null b/tests/compile-fail/syntax/missing_type.rs new file mode 100644 --- /dev/null +++ b/tests/compile-fail/syntax/missing_type.rs @@ -0,0 +1,8 @@ +#[macro_use] +extern crate bitflags; + +bitflags! { + pub struct Flags1 { + const A = 1; + } +} diff --git /dev/null b/tests/compile-fail/syntax/missing_type.stderr new file mode 100644 --- /dev/null +++ b/tests/compile-fail/syntax/missing_type.stderr @@ -0,0 +1,11 @@ +error: no rules expected the token `{` + --> tests/compile-fail/syntax/missing_type.rs:5:23 + | +5 | pub struct Flags1 { + | ^ no rules expected this token in macro call + +error[E0601]: `main` function not found in crate `$CRATE` + --> tests/compile-fail/syntax/missing_type.rs:8:2 + | +8 | } + | ^ consider adding a `main` function to `$DIR/tests/compile-fail/syntax/missing_type.rs` diff --git /dev/null b/tests/compile-fail/syntax/missing_value.rs new file mode 100644 --- /dev/null +++ b/tests/compile-fail/syntax/missing_value.rs @@ -0,0 +1,8 @@ +#[macro_use] +extern crate bitflags; + +bitflags! { + pub struct Flags1 { + const A; + } +} diff --git /dev/null b/tests/compile-fail/syntax/missing_value.stderr new file mode 100644 --- /dev/null +++ b/tests/compile-fail/syntax/missing_value.stderr @@ -0,0 +1,11 @@ +error: no rules expected the token `{` + --> tests/compile-fail/syntax/missing_value.rs:5:23 + | +5 | pub struct Flags1 { + | ^ no rules expected this token in macro call + +error[E0601]: `main` function not found in crate `$CRATE` + --> tests/compile-fail/syntax/missing_value.rs:8:2 + | +8 | } + | ^ consider adding a `main` function to `$DIR/tests/compile-fail/syntax/missing_value.rs` diff --git a/tests/compile-fail/trait/custom_impl.rs b/tests/compile-fail/trait/custom_impl.rs --- a/tests/compile-fail/trait/custom_impl.rs +++ b/tests/compile-fail/trait/custom_impl.rs @@ -25,7 +25,7 @@ impl BitFlags for BootlegFlags { unimplemented!() } - unsafe fn from_bits_unchecked(_: u32) -> BootlegFlags { + fn from_bits_retain(_: u32) -> BootlegFlags { unimplemented!() } diff --git a/tests/compile-fail/visibility/private_field.rs /dev/null --- a/tests/compile-fail/visibility/private_field.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod example { - use bitflags::bitflags; - - bitflags! { - pub struct Flags1: u32 { - const FLAG_A = 0b00000001; - } - } -} - -fn main() { - let flag1 = example::Flags1::FLAG_A.bits; -} diff --git a/tests/compile-fail/visibility/private_field.stderr /dev/null --- a/tests/compile-fail/visibility/private_field.stderr +++ /dev/null @@ -1,10 +0,0 @@ -error[E0616]: field `bits` of struct `Flags1` is private - --> $DIR/private_field.rs:12:41 - | -12 | let flag1 = example::Flags1::FLAG_A.bits; - | ^^^^ private field - | -help: a method `bits` also exists, call it with parentheses - | -12 | let flag1 = example::Flags1::FLAG_A.bits(); - | ++ diff --git a/tests/compile-fail/visibility/private_flags.rs b/tests/compile-fail/visibility/private_flags.rs --- a/tests/compile-fail/visibility/private_flags.rs +++ b/tests/compile-fail/visibility/private_flags.rs @@ -13,6 +13,6 @@ mod example { } fn main() { - let flag1 = example::Flags1::FLAG_A; - let flag2 = example::Flags2::FLAG_B; + let _ = example::Flags1::FLAG_A; + let _ = example::Flags2::FLAG_B; } diff --git a/tests/compile-fail/visibility/private_flags.stderr b/tests/compile-fail/visibility/private_flags.stderr --- a/tests/compile-fail/visibility/private_flags.stderr +++ b/tests/compile-fail/visibility/private_flags.stderr @@ -1,11 +1,11 @@ error[E0603]: struct `Flags2` is private - --> $DIR/private_flags.rs:17:26 + --> tests/compile-fail/visibility/private_flags.rs:17:22 | -17 | let flag2 = example::Flags2::FLAG_B; - | ^^^^^^ private struct +17 | let _ = example::Flags2::FLAG_B; + | ^^^^^^ private struct | note: the struct `Flags2` is defined here - --> $DIR/private_flags.rs:4:5 + --> tests/compile-fail/visibility/private_flags.rs:4:5 | 4 | / bitflags! { 5 | | pub struct Flags1: u32 { diff --git a/tests/compile-pass/impls/fmt.rs b/tests/compile-pass/impls/fmt.rs --- a/tests/compile-pass/impls/fmt.rs +++ b/tests/compile-pass/impls/fmt.rs @@ -1,6 +1,7 @@ use bitflags::bitflags; bitflags! { + #[derive(Debug)] struct Flags: u8 { const TWO = 0x2; } diff --git a/tests/compile-pass/impls/fmt.rs b/tests/compile-pass/impls/fmt.rs --- a/tests/compile-pass/impls/fmt.rs +++ b/tests/compile-pass/impls/fmt.rs @@ -8,7 +9,7 @@ bitflags! { fn main() { // bug #267 (https://github.com/bitflags/bitflags/issues/267) - let flags = unsafe { Flags::from_bits_unchecked(0b11) }; - assert_eq!(format!("{:?}", flags), "TWO | 0x1"); - assert_eq!(format!("{:#?}", flags), "TWO | 0x1"); + let flags = Flags::from_bits_retain(0b11); + assert_eq!(format!("{:?}", flags), "Flags(TWO | 0x1)"); + assert_eq!(format!("{:#?}", flags), "Flags(\n TWO | 0x1,\n)"); } diff --git /dev/null b/tests/compile-pass/item_positions.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/item_positions.rs @@ -0,0 +1,52 @@ +#[macro_use] +extern crate bitflags; + +bitflags! { + pub struct Flags1: u32 { + const A = 1; + } +} + +bitflags! { + pub struct Flags2: u32 { + const A = 1; + } +} + +pub mod nested { + bitflags! { + pub struct Flags1: u32 { + const A = 1; + } + } + + bitflags! { + pub struct Flags2: u32 { + const A = 1; + } + } +} + +pub const _: () = { + bitflags! { + pub struct Flags1: u32 { + const A = 1; + } + } +}; + +fn main() { + bitflags! { + pub struct Flags1: u32 { + const A = 1; + } + } + + let _ = { + bitflags! { + pub struct Flags2: u32 { + const A = 1; + } + } + }; +} diff --git a/tests/compile-pass/no_prelude.rs b/tests/compile-pass/no_prelude.rs --- a/tests/compile-pass/no_prelude.rs +++ b/tests/compile-pass/no_prelude.rs @@ -7,7 +7,7 @@ bitflags::bitflags! { const A = 0b00000001; const B = 0b00000010; const C = 0b00000100; - const ABC = Flags::A.bits | Flags::B.bits | Flags::C.bits; + const ABC = Flags::A.bits() | Flags::B.bits() | Flags::C.bits(); } } diff --git a/tests/compile-pass/redefinition/macros.rs b/tests/compile-pass/redefinition/macros.rs --- a/tests/compile-pass/redefinition/macros.rs +++ b/tests/compile-pass/redefinition/macros.rs @@ -13,6 +13,7 @@ macro_rules! write { } bitflags! { + #[derive(Debug)] struct Test: u8 { const A = 1; } diff --git a/tests/compile-pass/redefinition/macros.rs b/tests/compile-pass/redefinition/macros.rs --- a/tests/compile-pass/redefinition/macros.rs +++ b/tests/compile-pass/redefinition/macros.rs @@ -20,5 +21,5 @@ bitflags! { fn main() { // Just make sure we don't call the redefined `stringify` or `write` macro - assert_eq!(format!("{:?}", unsafe { Test::from_bits_unchecked(0b11) }), "A | 0x2"); + assert_eq!(format!("{:?}", Test::from_bits_retain(0b11)), "Test(A | 0x2)"); } diff --git a/tests/compile-pass/visibility/bits_field.rs b/tests/compile-pass/visibility/bits_field.rs --- a/tests/compile-pass/visibility/bits_field.rs +++ b/tests/compile-pass/visibility/bits_field.rs @@ -7,5 +7,5 @@ bitflags! { } fn main() { - assert_eq!(0b00000001, Flags1::FLAG_A.bits); + assert_eq!(0b00000001, Flags1::FLAG_A.bits()); } diff --git /dev/null b/tests/smoke-test/src/main.rs new file mode 100644 --- /dev/null +++ b/tests/smoke-test/src/main.rs @@ -0,0 +1,15 @@ +use bitflags::bitflags; + +bitflags! { + #[derive(Debug)] + pub struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + const ABC = Flags::A.bits() | Flags::B.bits() | Flags::C.bits(); + } +} + +fn main() { + println!("{:?}", Flags::ABC); +}
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
Implement Hex, Octal, and Binary These formatting options should be available.
bitflags__bitflags-86
[ "82" ]
7acacb4e869a6a0c8b427c25ade53086e5f024a1
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -529,6 +549,12 @@ mod tests { } } + bitflags! { + flags LongFlags: u32 { + const LongFlagA = 0b1111111111111111, + } + } + #[test] fn test_bits(){ assert_eq!(Flags::empty().bits(), 0b00000000); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -768,6 +794,30 @@ mod tests { assert_eq!(format!("{:?}", FlagABC), "FlagA | FlagB | FlagC | FlagABC"); } + #[test] + fn test_binary() { + assert_eq!(format!("{:b}", FlagABC), "111"); + assert_eq!(format!("{:#b}", FlagABC), "0b111"); + } + + #[test] + fn test_octal() { + assert_eq!(format!("{:o}", LongFlagA), "177777"); + assert_eq!(format!("{:#o}", LongFlagA), "0o177777"); + } + + #[test] + fn test_lowerhex() { + assert_eq!(format!("{:x}", LongFlagA), "ffff"); + assert_eq!(format!("{:#x}", LongFlagA), "0xffff"); + } + + #[test] + fn test_upperhex() { + assert_eq!(format!("{:X}", LongFlagA), "FFFF"); + assert_eq!(format!("{:#X}", LongFlagA), "0xFFFF"); + } + mod submodule { bitflags! { pub flags PublicFlags: i8 {
0.8
86
2017-03-22T15:50:46Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -139,8 +139,8 @@ pub use core as __core; /// too: `Extend` adds the union of the instances of the `struct` iterated over, /// while `FromIterator` calculates the union. /// -/// The `Debug` trait is also implemented by displaying the bits value of the -/// internal struct. +/// The `Binary`, `Debug`, `LowerExp`, `Octal` and `UpperExp` trait is also +/// implemented by displaying the bits value of the internal struct. /// /// ## Operators /// diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -258,6 +258,26 @@ macro_rules! bitflags { Ok(()) } } + impl $crate::__core::fmt::Binary for $BitFlags { + fn fmt(&self, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { + self.bits.fmt(f) + } + } + impl $crate::__core::fmt::Octal for $BitFlags { + fn fmt(&self, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { + self.bits.fmt(f) + } + } + impl $crate::__core::fmt::LowerHex for $BitFlags { + fn fmt(&self, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { + self.bits.fmt(f) + } + } + impl $crate::__core::fmt::UpperHex for $BitFlags { + fn fmt(&self, f: &mut $crate::__core::fmt::Formatter) -> $crate::__core::fmt::Result { + self.bits.fmt(f) + } + } #[allow(dead_code)] impl $BitFlags {
7acacb4e869a6a0c8b427c25ade53086e5f024a1
bitflags/bitflags
Allow namespaced flags It would be nice to have `FlagType::FlagName` be the pattern rather than dumping the flag values into the top-level namespace. Is this possible? associated constants This crate really wants to use associated constants (see https://github.com/rust-lang/rust/pull/24921) but the tricks introduced in #14 are incompatible with associated constants (because associated constants can't be `use`d to shadow locally scoped constants). What do?
bitflags__bitflags-24
[ "20", "21" ]
d0884fa853eadd800fef198d9e71c8758b292db5
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -723,71 +717,71 @@ mod tests { #[doc = "> "] #[doc = "> - Richard Feynman"] struct Flags: u32 { - const FlagA = 0b00000001; + const FLAG_A = 0b00000001; #[doc = "<pcwalton> macros are way better at generating code than trans is"] - const FlagB = 0b00000010; - const FlagC = 0b00000100; + const FLAG_B = 0b00000010; + const FLAG_C = 0b00000100; #[doc = "* cmr bed"] #[doc = "* strcat table"] #[doc = "<strcat> wait what?"] - const FlagABC = FlagA.bits - | FlagB.bits - | FlagC.bits; + const FLAG_ABC = Self::FLAG_A.bits + | Self::FLAG_B.bits + | Self::FLAG_C.bits; } } bitflags! { struct _CfgFlags: u32 { #[cfg(windows)] - const _CfgA = 0b01; + const _CFG_A = 0b01; #[cfg(unix)] - const _CfgB = 0b01; + const _CFG_B = 0b01; #[cfg(windows)] - const _CfgC = _CfgA.bits | 0b10; + const _CFG_C = _CFG_A.bits | 0b10; } } bitflags! { struct AnotherSetOfFlags: i8 { - const AnotherFlag = -1_i8; + const ANOTHER_FLAG = -1_i8; } } bitflags! { struct LongFlags: u32 { - const LongFlagA = 0b1111111111111111; + const LONG_FLAG_A = 0b1111111111111111; } } #[test] fn test_bits(){ assert_eq!(Flags::empty().bits(), 0b00000000); - assert_eq!(FlagA.bits(), 0b00000001); - assert_eq!(FlagABC.bits(), 0b00000111); + assert_eq!(Flags::FLAG_A.bits(), 0b00000001); + assert_eq!(Flags::FLAG_ABC.bits(), 0b00000111); assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00); - assert_eq!(AnotherFlag.bits(), !0_i8); + assert_eq!(AnotherSetOfFlags::ANOTHER_FLAG.bits(), !0_i8); } #[test] fn test_from_bits() { assert_eq!(Flags::from_bits(0), Some(Flags::empty())); - assert_eq!(Flags::from_bits(0b1), Some(FlagA)); - assert_eq!(Flags::from_bits(0b10), Some(FlagB)); - assert_eq!(Flags::from_bits(0b11), Some(FlagA | FlagB)); + assert_eq!(Flags::from_bits(0b1), Some(Flags::FLAG_A)); + assert_eq!(Flags::from_bits(0b10), Some(Flags::FLAG_B)); + assert_eq!(Flags::from_bits(0b11), Some(Flags::FLAG_A | Flags::FLAG_B)); assert_eq!(Flags::from_bits(0b1000), None); - assert_eq!(AnotherSetOfFlags::from_bits(!0_i8), Some(AnotherFlag)); + assert_eq!(AnotherSetOfFlags::from_bits(!0_i8), Some(AnotherSetOfFlags::ANOTHER_FLAG)); } #[test] fn test_from_bits_truncate() { assert_eq!(Flags::from_bits_truncate(0), Flags::empty()); - assert_eq!(Flags::from_bits_truncate(0b1), FlagA); - assert_eq!(Flags::from_bits_truncate(0b10), FlagB); - assert_eq!(Flags::from_bits_truncate(0b11), (FlagA | FlagB)); + assert_eq!(Flags::from_bits_truncate(0b1), Flags::FLAG_A); + assert_eq!(Flags::from_bits_truncate(0b10), Flags::FLAG_B); + assert_eq!(Flags::from_bits_truncate(0b11), (Flags::FLAG_A | Flags::FLAG_B)); assert_eq!(Flags::from_bits_truncate(0b1000), Flags::empty()); - assert_eq!(Flags::from_bits_truncate(0b1001), FlagA); + assert_eq!(Flags::from_bits_truncate(0b1001), Flags::FLAG_A); assert_eq!(AnotherSetOfFlags::from_bits_truncate(0_i8), AnotherSetOfFlags::empty()); } diff --git a/tests/conflicting_trait_impls.rs b/tests/conflicting_trait_impls.rs --- a/tests/conflicting_trait_impls.rs +++ b/tests/conflicting_trait_impls.rs @@ -1,4 +1,3 @@ -#![allow(dead_code)] #![no_std] #[macro_use] diff --git a/tests/external.rs b/tests/external.rs --- a/tests/external.rs +++ b/tests/external.rs @@ -1,5 +1,3 @@ -#![allow(dead_code)] - #[macro_use] extern crate bitflags; diff --git a/tests/external.rs b/tests/external.rs --- a/tests/external.rs +++ b/tests/external.rs @@ -11,11 +9,11 @@ bitflags! { const B = 0b00000010; const C = 0b00000100; #[doc = "foo"] - const ABC = A.bits | B.bits | C.bits; + const ABC = Flags::A.bits | Flags::B.bits | Flags::C.bits; } } #[test] fn smoke() { - assert_eq!(ABC, A | B | C); + assert_eq!(Flags::ABC, Flags::A | Flags::B | Flags::C); } diff --git a/tests/external_no_std.rs b/tests/external_no_std.rs --- a/tests/external_no_std.rs +++ b/tests/external_no_std.rs @@ -1,4 +1,3 @@ -#![allow(dead_code)] #![no_std] #[macro_use] diff --git a/tests/external_no_std.rs b/tests/external_no_std.rs --- a/tests/external_no_std.rs +++ b/tests/external_no_std.rs @@ -12,11 +11,11 @@ bitflags! { const B = 0b00000010; const C = 0b00000100; #[doc = "foo"] - const ABC = A.bits | B.bits | C.bits; + const ABC = Flags::A.bits | Flags::B.bits | Flags::C.bits; } } #[test] fn smoke() { - assert_eq!(ABC, A | B | C); + assert_eq!(Flags::ABC, Flags::A | Flags::B | Flags::C); } diff --git a/tests/i128_bitflags.rs b/tests/i128_bitflags.rs --- a/tests/i128_bitflags.rs +++ b/tests/i128_bitflags.rs @@ -1,6 +1,5 @@ #![cfg(feature = "unstable_testing")] -#![allow(dead_code, unused_imports)] #![feature(i128_type)] #[macro_use] diff --git a/tests/i128_bitflags.rs b/tests/i128_bitflags.rs --- a/tests/i128_bitflags.rs +++ b/tests/i128_bitflags.rs @@ -12,19 +11,19 @@ bitflags! { 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 = A.bits | B.bits | C.bits; + const ABC = Self::A.bits | Self::B.bits | Self::C.bits; } } #[test] fn test_i128_bitflags() { - assert_eq!(ABC, A | B | C); - assert_eq!(A.bits, 0x0000_0000_0000_0000_0000_0000_0000_0001); - assert_eq!(B.bits, 0x0000_0000_0000_1000_0000_0000_0000_0000); - assert_eq!(C.bits, 0x8000_0000_0000_0000_0000_0000_0000_0000); - assert_eq!(ABC.bits, 0x8000_0000_0000_1000_0000_0000_0000_0001); - assert_eq!(format!("{:?}", A), "A"); - assert_eq!(format!("{:?}", B), "B"); - assert_eq!(format!("{:?}", C), "C"); - assert_eq!(format!("{:?}", ABC), "A | B | C | ABC"); + assert_eq!(Flags128::ABC, Flags128::A | Flags128::B | Flags128::C); + assert_eq!(Flags128::A.bits, 0x0000_0000_0000_0000_0000_0000_0000_0001); + assert_eq!(Flags128::B.bits, 0x0000_0000_0000_1000_0000_0000_0000_0000); + assert_eq!(Flags128::C.bits, 0x8000_0000_0000_0000_0000_0000_0000_0000); + assert_eq!(Flags128::ABC.bits, 0x8000_0000_0000_1000_0000_0000_0000_0001); + assert_eq!(format!("{:?}", Flags128::A), "A"); + assert_eq!(format!("{:?}", Flags128::B), "B"); + assert_eq!(format!("{:?}", Flags128::C), "C"); + assert_eq!(format!("{:?}", Flags128::ABC), "A | B | C | ABC"); }
0.9
24
2015-11-28T01:15:59Z
diff --git a/src/example_generated.rs b/src/example_generated.rs --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -9,8 +9,8 @@ bitflags! { const FLAG_A = 0b00000001; const FLAG_B = 0b00000010; const FLAG_C = 0b00000100; - const FLAG_ABC = FLAG_A.bits - | FLAG_B.bits - | FLAG_C.bits; + const FLAG_ABC = Self::FLAG_A.bits + | Self::FLAG_B.bits + | Self::FLAG_C.bits; } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -26,19 +26,19 @@ //! const FLAG_A = 0b00000001; //! const FLAG_B = 0b00000010; //! const FLAG_C = 0b00000100; -//! const FLAG_ABC = FLAG_A.bits -//! | FLAG_B.bits -//! | FLAG_C.bits; +//! const FLAG_ABC = Self::FLAG_A.bits +//! | Self::FLAG_B.bits +//! | Self::FLAG_C.bits; //! } //! } //! //! fn main() { -//! let e1 = FLAG_A | FLAG_C; -//! let e2 = FLAG_B | FLAG_C; -//! assert_eq!((e1 | e2), FLAG_ABC); // union -//! assert_eq!((e1 & e2), FLAG_C); // intersection -//! assert_eq!((e1 - e2), FLAG_A); // set difference -//! assert_eq!(!e2, FLAG_A); // set complement +//! let e1 = Flags::FLAG_A | Flags::FLAG_C; +//! let e2 = Flags::FLAG_B | Flags::FLAG_C; +//! assert_eq!((e1 | e2), Flags::FLAG_ABC); // union +//! assert_eq!((e1 & e2), Flags::FLAG_C); // intersection +//! assert_eq!((e1 - e2), Flags::FLAG_A); // set difference +//! assert_eq!(!e2, Flags::FLAG_A); // set complement //! } //! ``` //! diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -75,12 +75,12 @@ //! } //! //! fn main() { -//! let mut flags = FLAG_A | FLAG_B; +//! let mut flags = Flags::FLAG_A | Flags::FLAG_B; //! flags.clear(); //! assert!(flags.is_empty()); //! assert_eq!(format!("{}", flags), "hi!"); -//! assert_eq!(format!("{:?}", FLAG_A | FLAG_B), "FLAG_A | FLAG_B"); -//! assert_eq!(format!("{:?}", FLAG_B), "FLAG_B"); +//! assert_eq!(format!("{:?}", Flags::FLAG_A | Flags::FLAG_B), "FLAG_A | FLAG_B"); +//! assert_eq!(format!("{:?}", Flags::FLAG_B), "FLAG_B"); //! } //! ``` //! diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -108,8 +108,8 @@ //! } //! //! fn main() { -//! let flag1 = example::FLAG_A; -//! let flag2 = example::FLAG_B; // error: const `FLAG_B` is private +//! let flag1 = example::Flags1::FLAG_A; +//! let flag2 = example::Flags2::FLAG_B; // error: const `FLAG_B` is private //! } //! ``` //! diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -207,13 +207,13 @@ //! // explicit `Default` implementation //! impl Default for Flags { //! fn default() -> Flags { -//! FLAG_A | FLAG_C +//! Flags::FLAG_A | Flags::FLAG_C //! } //! } //! //! fn main() { //! let implemented_default: Flags = Default::default(); -//! assert_eq!(implemented_default, (FLAG_A | FLAG_C)); +//! assert_eq!(implemented_default, (Flags::FLAG_A | Flags::FLAG_C)); //! } //! ``` diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -249,19 +249,19 @@ pub extern crate core as _core; /// const FLAG_A = 0b00000001; /// const FLAG_B = 0b00000010; /// const FLAG_C = 0b00000100; -/// const FLAG_ABC = FLAG_A.bits -/// | FLAG_B.bits -/// | FLAG_C.bits; +/// const FLAG_ABC = Self::FLAG_A.bits +/// | Self::FLAG_B.bits +/// | Self::FLAG_C.bits; /// } /// } /// /// fn main() { -/// let e1 = FLAG_A | FLAG_C; -/// let e2 = FLAG_B | FLAG_C; -/// assert_eq!((e1 | e2), FLAG_ABC); // union -/// assert_eq!((e1 & e2), FLAG_C); // intersection -/// assert_eq!((e1 - e2), FLAG_A); // set difference -/// assert_eq!(!e2, FLAG_A); // set complement +/// let e1 = Flags::FLAG_A | Flags::FLAG_C; +/// let e2 = Flags::FLAG_B | Flags::FLAG_C; +/// assert_eq!((e1 | e2), Flags::FLAG_ABC); // union +/// assert_eq!((e1 & e2), Flags::FLAG_C); // intersection +/// assert_eq!((e1 - e2), Flags::FLAG_A); // set difference +/// assert_eq!(!e2, Flags::FLAG_A); // set complement /// } /// ``` /// diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -295,12 +295,12 @@ pub extern crate core as _core; /// } /// /// fn main() { -/// let mut flags = FLAG_A | FLAG_B; +/// let mut flags = Flags::FLAG_A | Flags::FLAG_B; /// flags.clear(); /// assert!(flags.is_empty()); /// assert_eq!(format!("{}", flags), "hi!"); -/// assert_eq!(format!("{:?}", FLAG_A | FLAG_B), "FLAG_A | FLAG_B"); -/// assert_eq!(format!("{:?}", FLAG_B), "FLAG_B"); +/// assert_eq!(format!("{:?}", Flags::FLAG_A | Flags::FLAG_B), "FLAG_A | FLAG_B"); +/// assert_eq!(format!("{:?}", Flags::FLAG_B), "FLAG_B"); /// } /// ``` #[macro_export] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -320,11 +320,6 @@ macro_rules! bitflags { bits: $T, } - $( - $(#[$inner $($args)*])* - pub const $Flag: $BitFlags = $BitFlags { bits: $value }; - )+ - __impl_bitflags! { struct $BitFlags: $T { $( diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -349,11 +344,6 @@ macro_rules! bitflags { bits: $T, } - $( - $(#[$inner $($args)*])* - const $Flag: $BitFlags = $BitFlags { bits: $value }; - )+ - __impl_bitflags! { struct $BitFlags: $T { $( diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -401,7 +391,7 @@ macro_rules! __impl_bitflags { #[allow(deprecated)] $(? #[$attr $($args)*])* fn $Flag(&self) -> bool { - self.bits & $Flag.bits == $Flag.bits + self.bits & Self::$Flag.bits == Self::$Flag.bits } } )+ diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -446,6 +436,11 @@ macro_rules! __impl_bitflags { #[allow(dead_code)] impl $BitFlags { + $( + $(#[$attr $($args)*])* + pub const $Flag: $BitFlags = $BitFlags { bits: $value }; + )+ + /// Returns an empty set of flags. #[inline] pub fn empty() -> $BitFlags { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -467,7 +462,7 @@ macro_rules! __impl_bitflags { __impl_bitflags! { #[allow(deprecated)] $(? #[$attr $($args)*])* - fn $Flag() -> $T { $Flag.bits } + fn $Flag() -> $T { Self::$Flag.bits } } )+ } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -712,7 +707,6 @@ macro_rules! __impl_bitflags { pub mod example_generated; #[cfg(test)] -#[allow(non_upper_case_globals, dead_code)] mod tests { use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -795,19 +789,19 @@ mod tests { #[test] fn test_is_empty(){ assert!(Flags::empty().is_empty()); - assert!(!FlagA.is_empty()); - assert!(!FlagABC.is_empty()); + assert!(!Flags::FLAG_A.is_empty()); + assert!(!Flags::FLAG_ABC.is_empty()); - assert!(!AnotherFlag.is_empty()); + assert!(!AnotherSetOfFlags::ANOTHER_FLAG.is_empty()); } #[test] fn test_is_all() { assert!(Flags::all().is_all()); - assert!(!FlagA.is_all()); - assert!(FlagABC.is_all()); + assert!(!Flags::FLAG_A.is_all()); + assert!(Flags::FLAG_ABC.is_all()); - assert!(AnotherFlag.is_all()); + assert!(AnotherSetOfFlags::ANOTHER_FLAG.is_all()); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -816,77 +810,77 @@ mod tests { let e2 = Flags::empty(); assert!(!e1.intersects(e2)); - assert!(AnotherFlag.intersects(AnotherFlag)); + assert!(AnotherSetOfFlags::ANOTHER_FLAG.intersects(AnotherSetOfFlags::ANOTHER_FLAG)); } #[test] fn test_empty_does_not_intersect_with_full() { let e1 = Flags::empty(); - let e2 = FlagABC; + let e2 = Flags::FLAG_ABC; assert!(!e1.intersects(e2)); } #[test] fn test_disjoint_intersects() { - let e1 = FlagA; - let e2 = FlagB; + let e1 = Flags::FLAG_A; + let e2 = Flags::FLAG_B; assert!(!e1.intersects(e2)); } #[test] fn test_overlapping_intersects() { - let e1 = FlagA; - let e2 = FlagA | FlagB; + let e1 = Flags::FLAG_A; + let e2 = Flags::FLAG_A | Flags::FLAG_B; assert!(e1.intersects(e2)); } #[test] fn test_contains() { - let e1 = FlagA; - let e2 = FlagA | FlagB; + let e1 = Flags::FLAG_A; + let e2 = Flags::FLAG_A | Flags::FLAG_B; assert!(!e1.contains(e2)); assert!(e2.contains(e1)); - assert!(FlagABC.contains(e2)); + assert!(Flags::FLAG_ABC.contains(e2)); - assert!(AnotherFlag.contains(AnotherFlag)); + assert!(AnotherSetOfFlags::ANOTHER_FLAG.contains(AnotherSetOfFlags::ANOTHER_FLAG)); } #[test] fn test_insert(){ - let mut e1 = FlagA; - let e2 = FlagA | FlagB; + let mut e1 = Flags::FLAG_A; + let e2 = Flags::FLAG_A | Flags::FLAG_B; e1.insert(e2); assert_eq!(e1, e2); let mut e3 = AnotherSetOfFlags::empty(); - e3.insert(AnotherFlag); - assert_eq!(e3, AnotherFlag); + e3.insert(AnotherSetOfFlags::ANOTHER_FLAG); + assert_eq!(e3, AnotherSetOfFlags::ANOTHER_FLAG); } #[test] fn test_remove(){ - let mut e1 = FlagA | FlagB; - let e2 = FlagA | FlagC; + let mut e1 = Flags::FLAG_A | Flags::FLAG_B; + let e2 = Flags::FLAG_A | Flags::FLAG_C; e1.remove(e2); - assert_eq!(e1, FlagB); + assert_eq!(e1, Flags::FLAG_B); - let mut e3 = AnotherFlag; - e3.remove(AnotherFlag); + let mut e3 = AnotherSetOfFlags::ANOTHER_FLAG; + e3.remove(AnotherSetOfFlags::ANOTHER_FLAG); assert_eq!(e3, AnotherSetOfFlags::empty()); } #[test] fn test_operators() { - let e1 = FlagA | FlagC; - let e2 = FlagB | FlagC; - assert_eq!((e1 | e2), FlagABC); // union - assert_eq!((e1 & e2), FlagC); // intersection - assert_eq!((e1 - e2), FlagA); // set difference - assert_eq!(!e2, FlagA); // set complement - assert_eq!(e1 ^ e2, FlagA | FlagB); // toggle + let e1 = Flags::FLAG_A | Flags::FLAG_C; + let e2 = Flags::FLAG_B | Flags::FLAG_C; + assert_eq!((e1 | e2), Flags::FLAG_ABC); // union + assert_eq!((e1 & e2), Flags::FLAG_C); // intersection + assert_eq!((e1 - e2), Flags::FLAG_A); // set difference + assert_eq!(!e2, Flags::FLAG_A); // set complement + assert_eq!(e1 ^ e2, Flags::FLAG_A | Flags::FLAG_B); // toggle let mut e3 = e1; e3.toggle(e2); - assert_eq!(e3, FlagA | FlagB); + assert_eq!(e3, Flags::FLAG_A | Flags::FLAG_B); let mut m4 = AnotherSetOfFlags::empty(); m4.toggle(AnotherSetOfFlags::empty()); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -895,23 +889,23 @@ mod tests { #[test] fn test_set() { - let mut e1 = FlagA | FlagC; - e1.set(FlagB, true); - e1.set(FlagC, false); + let mut e1 = Flags::FLAG_A | Flags::FLAG_C; + e1.set(Flags::FLAG_B, true); + e1.set(Flags::FLAG_C, false); - assert_eq!(e1, FlagA | FlagB); + assert_eq!(e1, Flags::FLAG_A | Flags::FLAG_B); } #[test] fn test_assignment_operators() { let mut m1 = Flags::empty(); - let e1 = FlagA | FlagC; + let e1 = Flags::FLAG_A | Flags::FLAG_C; // union - m1 |= FlagA; - assert_eq!(m1, FlagA); + m1 |= Flags::FLAG_A; + assert_eq!(m1, Flags::FLAG_A); // intersection m1 &= e1; - assert_eq!(m1, FlagA); + assert_eq!(m1, Flags::FLAG_A); // set difference m1 -= m1; assert_eq!(m1, Flags::empty()); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -929,23 +923,25 @@ mod tests { assert_eq!(flags, Flags::empty()); flags = Flags::empty(); - flags.extend([FlagA, FlagB].iter().cloned()); - assert_eq!(flags, FlagA | FlagB); + flags.extend([Flags::FLAG_A, Flags::FLAG_B].iter().cloned()); + assert_eq!(flags, Flags::FLAG_A | Flags::FLAG_B); - flags = FlagA; - flags.extend([FlagA, FlagB].iter().cloned()); - assert_eq!(flags, FlagA | FlagB); + flags = Flags::FLAG_A; + flags.extend([Flags::FLAG_A, Flags::FLAG_B].iter().cloned()); + assert_eq!(flags, Flags::FLAG_A | Flags::FLAG_B); - flags = FlagB; - flags.extend([FlagA, FlagABC].iter().cloned()); - assert_eq!(flags, FlagABC); + flags = Flags::FLAG_B; + flags.extend([Flags::FLAG_A, Flags::FLAG_ABC].iter().cloned()); + assert_eq!(flags, Flags::FLAG_ABC); } #[test] fn test_from_iterator() { assert_eq!([].iter().cloned().collect::<Flags>(), Flags::empty()); - assert_eq!([FlagA, FlagB].iter().cloned().collect::<Flags>(), FlagA | FlagB); - assert_eq!([FlagA, FlagABC].iter().cloned().collect::<Flags>(), FlagABC); + assert_eq!([Flags::FLAG_A, Flags::FLAG_B].iter().cloned().collect::<Flags>(), + Flags::FLAG_A | Flags::FLAG_B); + assert_eq!([Flags::FLAG_A, Flags::FLAG_ABC].iter().cloned().collect::<Flags>(), + Flags::FLAG_ABC); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -954,11 +950,11 @@ mod tests { let mut b = Flags::empty(); assert!(!(a < b) && !(b < a)); - b = FlagB; + b = Flags::FLAG_B; assert!(a < b); - a = FlagC; + a = Flags::FLAG_C; assert!(!(a < b) && b < a); - b = FlagC | FlagB; + b = Flags::FLAG_C | Flags::FLAG_B; assert!(a < b); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -968,10 +964,10 @@ mod tests { let mut b = Flags::empty(); assert!(a <= b && a >= b); - a = FlagA; + a = Flags::FLAG_A; assert!(a > b && a >= b); assert!(b < a && b <= a); - b = FlagB; + b = Flags::FLAG_B; assert!(b > a && b >= a); assert!(a < b && a <= b); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -988,62 +984,63 @@ mod tests { let mut y = Flags::empty(); assert_eq!(hash(&x), hash(&y)); x = Flags::all(); - y = FlagABC; + y = Flags::FLAG_ABC; assert_eq!(hash(&x), hash(&y)); } #[test] fn test_debug() { - assert_eq!(format!("{:?}", FlagA | FlagB), "FlagA | FlagB"); + assert_eq!(format!("{:?}", Flags::FLAG_A | Flags::FLAG_B), "FLAG_A | FLAG_B"); assert_eq!(format!("{:?}", Flags::empty()), "(empty)"); - assert_eq!(format!("{:?}", FlagABC), "FlagA | FlagB | FlagC | FlagABC"); + assert_eq!(format!("{:?}", Flags::FLAG_ABC), "FLAG_A | FLAG_B | FLAG_C | FLAG_ABC"); } #[test] fn test_binary() { - assert_eq!(format!("{:b}", FlagABC), "111"); - assert_eq!(format!("{:#b}", FlagABC), "0b111"); + assert_eq!(format!("{:b}", Flags::FLAG_ABC), "111"); + assert_eq!(format!("{:#b}", Flags::FLAG_ABC), "0b111"); } #[test] fn test_octal() { - assert_eq!(format!("{:o}", LongFlagA), "177777"); - assert_eq!(format!("{:#o}", LongFlagA), "0o177777"); + assert_eq!(format!("{:o}", LongFlags::LONG_FLAG_A), "177777"); + assert_eq!(format!("{:#o}", LongFlags::LONG_FLAG_A), "0o177777"); } #[test] fn test_lowerhex() { - assert_eq!(format!("{:x}", LongFlagA), "ffff"); - assert_eq!(format!("{:#x}", LongFlagA), "0xffff"); + assert_eq!(format!("{:x}", LongFlags::LONG_FLAG_A), "ffff"); + assert_eq!(format!("{:#x}", LongFlags::LONG_FLAG_A), "0xffff"); } #[test] fn test_upperhex() { - assert_eq!(format!("{:X}", LongFlagA), "FFFF"); - assert_eq!(format!("{:#X}", LongFlagA), "0xFFFF"); + assert_eq!(format!("{:X}", LongFlags::LONG_FLAG_A), "FFFF"); + assert_eq!(format!("{:#X}", LongFlags::LONG_FLAG_A), "0xFFFF"); } mod submodule { bitflags! { pub struct PublicFlags: i8 { - const FlagX = 0; + const FLAG_X = 0; } } bitflags! { struct PrivateFlags: i8 { - const FlagY = 0; + const FLAG_Y = 0; } } #[test] fn test_private() { - let _ = FlagY; + + let _ = PrivateFlags::FLAG_Y; } } #[test] fn test_public() { - let _ = submodule::FlagX; + let _ = submodule::PublicFlags::FLAG_X; } mod t1 { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1072,8 +1069,8 @@ mod tests { const B = 2; } } - assert_eq!(Flags::all(), A); - assert_eq!(format!("{:?}", A), "A"); + assert_eq!(Flags::all(), Flags::A); + assert_eq!(format!("{:?}", Flags::A), "A"); } #[test]
8ee624463bb29c3a749ef134fda7cc0fa1192552
bitflags/bitflags
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.
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.
bitflags__bitflags-366
[ "364" ]
09f71f492d0f76d63cd286c3869c70676297e204
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, + ); + } +}
2.3
366
2023-06-26T07:21:41Z
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/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/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 @@ -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 @@ -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()) 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)
09f71f492d0f76d63cd286c3869c70676297e204