repo
stringclasses
1 value
pull_number
int64
24
411
instance_id
stringlengths
21
22
issue_numbers
listlengths
1
2
base_commit
stringlengths
40
40
patch
stringlengths
348
114k
test_patch
stringlengths
393
86.1k
problem_statement
stringlengths
285
2.62k
hints_text
stringlengths
0
2.14k
created_at
stringlengths
20
20
version
stringclasses
10 values
bitflags/bitflags
411
bitflags__bitflags-411
[ "406" ]
9c4b93c931e34a5104f50e20be1bdd15bc593b0e
diff --git a/src/lib.rs b/src/lib.rs index 8f722591..b5e8911b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,7 +38,7 @@ bitflags! { See the docs for the `bitflags` macro for the full syntax. -Also see the [`example_generated`] module for an example of what the `bitflags` macro generates for a flags type. +Also see the [`example_generated`](./example_generated/index.html) module for an example of what the `bitflags` macro generates for a flags type. ### Externally defined flags @@ -530,6 +530,7 @@ macro_rules! bitflags { } }; ( + $(#[$outer:meta])* impl $BitFlags:ident: $T:ty { $( $(#[$inner:ident $($args:tt)*])* @@ -561,6 +562,7 @@ macro_rules! bitflags { )] const _: () = { $crate::__impl_public_bitflags! { + $(#[$outer])* $BitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* @@ -593,6 +595,7 @@ macro_rules! bitflags { #[doc(hidden)] macro_rules! __impl_bitflags { ( + $(#[$outer:meta])* $PublicBitFlags:ident: $T:ty { fn empty() $empty:block fn all() $all:block @@ -617,6 +620,7 @@ macro_rules! __impl_bitflags { } ) => { #[allow(dead_code, deprecated, unused_attributes)] + $(#[$outer])* impl $PublicBitFlags { /// Get a flags value with all bits unset. #[inline] diff --git a/src/public.rs b/src/public.rs index dc2d7267..feecdd67 100644 --- a/src/public.rs +++ b/src/public.rs @@ -26,9 +26,11 @@ macro_rules! __declare_public_bitflags { #[doc(hidden)] macro_rules! __impl_public_bitflags_forward { ( + $(#[$outer:meta])* $PublicBitFlags:ident: $T:ty, $InternalBitFlags:ident ) => { $crate::__impl_bitflags! { + $(#[$outer])* $PublicBitFlags: $T { fn empty() { Self($InternalBitFlags::empty()) @@ -128,6 +130,7 @@ macro_rules! __impl_public_bitflags_forward { #[doc(hidden)] macro_rules! __impl_public_bitflags { ( + $(#[$outer:meta])* $BitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$inner:ident $($args:tt)*])* @@ -136,6 +139,7 @@ macro_rules! __impl_public_bitflags { } ) => { $crate::__impl_bitflags! { + $(#[$outer])* $BitFlags: $T { fn empty() { Self(<$T as $crate::Bits>::EMPTY) @@ -271,7 +275,11 @@ macro_rules! __impl_public_bitflags { #[macro_export] #[doc(hidden)] macro_rules! __impl_public_bitflags_iter { - ($BitFlags:ident: $T:ty, $PublicBitFlags:ident) => { + ( + $(#[$outer:meta])* + $BitFlags:ident: $T:ty, $PublicBitFlags:ident + ) => { + $(#[$outer])* impl $BitFlags { /// Yield a set of contained flags values. /// @@ -300,6 +308,7 @@ macro_rules! __impl_public_bitflags_iter { } } + $(#[$outer:meta])* impl $crate::__private::core::iter::IntoIterator for $BitFlags { type Item = $PublicBitFlags; type IntoIter = $crate::iter::Iter<$PublicBitFlags>; @@ -315,7 +324,12 @@ macro_rules! __impl_public_bitflags_iter { #[macro_export] #[doc(hidden)] macro_rules! __impl_public_bitflags_ops { - ($PublicBitFlags:ident) => { + ( + $(#[$outer:meta])* + $PublicBitFlags:ident + ) => { + + $(#[$outer])* impl $crate::__private::core::fmt::Binary for $PublicBitFlags { fn fmt( &self, @@ -326,6 +340,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::fmt::Octal for $PublicBitFlags { fn fmt( &self, @@ -336,6 +351,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::fmt::LowerHex for $PublicBitFlags { fn fmt( &self, @@ -346,6 +362,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::fmt::UpperHex for $PublicBitFlags { fn fmt( &self, @@ -356,6 +373,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitOr for $PublicBitFlags { type Output = Self; @@ -366,6 +384,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitOrAssign for $PublicBitFlags { /// The bitwise or (`|`) of the bits in two flags values. #[inline] @@ -374,6 +393,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitXor for $PublicBitFlags { type Output = Self; @@ -384,6 +404,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitXorAssign for $PublicBitFlags { /// The bitwise exclusive-or (`^`) of the bits in two flags values. #[inline] @@ -392,6 +413,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitAnd for $PublicBitFlags { type Output = Self; @@ -402,6 +424,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::BitAndAssign for $PublicBitFlags { /// The bitwise and (`&`) of the bits in two flags values. #[inline] @@ -410,6 +433,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::Sub for $PublicBitFlags { type Output = Self; @@ -423,6 +447,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::SubAssign for $PublicBitFlags { /// The intersection of a source flags value with the complement of a target flags value (`&!`). /// @@ -434,6 +459,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::ops::Not for $PublicBitFlags { type Output = Self; @@ -444,6 +470,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::iter::Extend<$PublicBitFlags> for $PublicBitFlags { /// The bitwise or (`|`) of the bits in each flags value. fn extend<T: $crate::__private::core::iter::IntoIterator<Item = Self>>( @@ -456,6 +483,7 @@ macro_rules! __impl_public_bitflags_ops { } } + $(#[$outer])* impl $crate::__private::core::iter::FromIterator<$PublicBitFlags> for $PublicBitFlags { /// The bitwise or (`|`) of the bits in each flags value. fn from_iter<T: $crate::__private::core::iter::IntoIterator<Item = Self>>( @@ -476,6 +504,7 @@ macro_rules! __impl_public_bitflags_ops { #[doc(hidden)] macro_rules! __impl_public_bitflags_consts { ( + $(#[$outer:meta])* $PublicBitFlags:ident: $T:ty { $( $(#[$inner:ident $($args:tt)*])* @@ -483,6 +512,7 @@ macro_rules! __impl_public_bitflags_consts { )* } ) => { + $(#[$outer])* impl $PublicBitFlags { $( $crate::__bitflags_flag!({ @@ -500,6 +530,7 @@ macro_rules! __impl_public_bitflags_consts { )* } + $(#[$outer])* impl $crate::Flags for $PublicBitFlags { const FLAGS: &'static [$crate::Flag<$PublicBitFlags>] = &[ $(
diff --git a/tests/compile-pass/bitflags_impl_attrs.rs b/tests/compile-pass/bitflags_impl_attrs.rs new file mode 100644 index 00000000..91d89823 --- /dev/null +++ b/tests/compile-pass/bitflags_impl_attrs.rs @@ -0,0 +1,13 @@ +extern crate bitflags; + +struct Example(u64); + +bitflags::bitflags! { + /// Docs on the `impl` block. + #[allow(dead_code)] + impl Example: u64 { + const flag = 0b01; + } +} + +fn main() {}
Allow specifying attributes in `impl` mode I'm considering `cfg`-gating the use of `bitflags!` in my libraries, and to that end it would be nice if it was possible to apply attributes to the generated `impl`s as well. The naive solution would be: ```rust pub struct Flags(u8); #[cfg(feature = "bitflags")] bitflags! { impl Flags: u8 { // ... } } ``` However, that works poorly with the `doc_cfg` (and `doc_auto_cfg`) feature, as the attribute is only applied to the macro, and isn't passed down to each output item. Instead, I would like to be able to do the following: ```rust #![feature(doc_cfg)] pub struct Flags(u8); #[cfg(feature = "bitflags")] bitflags! { #[doc(cfg(feature = "bitflags"))] impl Flags: u8 { // ... } } ```
Thanks for the report @madsmtm! Anywhere attributes are allowed to be specified we should support in the macros as much as possible. I think this is just a missing piece of functionality for the impl mode.
2024-06-24T23:17:40Z
2.5
bitflags/bitflags
380
bitflags__bitflags-380
[ "378" ]
472e392c0d082c0894b18fb31f4e68e0b145e29c
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index e5edec86..4f4c6c1d 100644 --- 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 index 39224533..11e32fc4 100644 --- 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 index 3d5377b8..352622d5 100644 --- 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 @@ -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! {
diff --git a/src/tests/iter.rs b/src/tests/iter.rs index 889ebcb7..54b1d27d 100644 --- 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 index 67d5337c..b370785c 100644 --- 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 index def7bbe3..7daee0bf 100644 --- 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 a/tests/compile-pass/missing_docs.rs b/tests/compile-pass/missing_docs.rs new file mode 100644 index 00000000..e757dbfe --- /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 index 7127acee..de0da54c 100644 --- 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() { @@ -9,6 +10,7 @@ fn fail() { t.compile_fail("tests/compile-fail/**/*.rs"); } +#[cfg(not(miri))] #[test] fn pass() { let t = trybuild::TestCases::new();
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 🤔
2023-10-09T04:48:32Z
2.4
bitflags/bitflags
366
bitflags__bitflags-366
[ "364" ]
09f71f492d0f76d63cd286c3869c70676297e204
diff --git a/examples/custom_bits_type.rs b/examples/custom_bits_type.rs index 0364a2bd..8924bfdf 100644 --- 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!` @@ -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], + ]) } } @@ -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], + ]) } } @@ -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 index ec3a8cb5..75633790 100644 --- 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); @@ -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 index 7f8a5c5d..3586e3f0 100644 --- 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 index 103b5d1e..94bd2000 100644 --- 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) } @@ -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 index ae59677a..715ba251 100644 --- 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 index 5ab109e0..a0cd68c9 100644 --- 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 index bc1f2ece..1d501db8 100644 --- 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, { @@ -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 index c4fb6533..824cdde4 100644 --- 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`, @@ -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 index 4b6210e2..761124f1 100644 --- 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. /// @@ -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, } } @@ -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 } @@ -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> { @@ -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()), } } @@ -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, } } @@ -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; } @@ -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 index 3d0869ac..c9ed1c28 100644 --- 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; @@ -623,6 +624,10 @@ macro_rules! bitflags { $BitFlags: $T, InternalBitFlags } + __impl_public_bitflags_ops! { + $BitFlags + } + __impl_public_bitflags_iter! { $BitFlags: $T, $BitFlags } @@ -671,6 +676,10 @@ macro_rules! bitflags { } } + __impl_public_bitflags_ops! { + $BitFlags + } + __impl_public_bitflags_iter! { $BitFlags: $T, $BitFlags } @@ -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] @@ -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; @@ -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; @@ -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; @@ -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 { @@ -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 { @@ -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 { @@ -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 { @@ -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 { @@ -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 a/src/parser.rs b/src/parser.rs index aac9042f..1f5a42fd 100644 --- 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. /// @@ -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 { @@ -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 index 57ab0ea8..eb8e4c5d 100644 --- a/src/public.rs +++ b/src/public.rs @@ -117,8 +117,6 @@ macro_rules! __impl_public_bitflags_forward { } } } - - __impl_public_bitflags_ops!($PublicBitFlags); }; } @@ -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) { @@ -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); }; } @@ -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()), + ) } } @@ -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) } } @@ -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); } } @@ -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); } } @@ -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); } } @@ -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); } } @@ -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) } @@ -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 index f8fc7572..1e44645c 100644 --- 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> { @@ -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())); } } @@ -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, @@ -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, @@ -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, @@ -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/src/tests.rs b/src/tests.rs new file mode 100644 index 00000000..cb41f75a --- /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 a/src/tests/all.rs b/src/tests/all.rs new file mode 100644 index 00000000..66e4f9d6 --- /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 a/src/tests/bits.rs b/src/tests/bits.rs new file mode 100644 index 00000000..65184e50 --- /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 a/src/tests/complement.rs b/src/tests/complement.rs new file mode 100644 index 00000000..057aaf16 --- /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 a/src/tests/contains.rs b/src/tests/contains.rs new file mode 100644 index 00000000..6067e050 --- /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 a/src/tests/difference.rs b/src/tests/difference.rs new file mode 100644 index 00000000..556bf13e --- /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 a/src/tests/empty.rs b/src/tests/empty.rs new file mode 100644 index 00000000..9cf73eb1 --- /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 a/src/tests/eq.rs b/src/tests/eq.rs new file mode 100644 index 00000000..9779af76 --- /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 a/src/tests/extend.rs b/src/tests/extend.rs new file mode 100644 index 00000000..ed0fe03c --- /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 a/src/tests/flags.rs b/src/tests/flags.rs new file mode 100644 index 00000000..bd0c0a94 --- /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 a/src/tests/fmt.rs b/src/tests/fmt.rs new file mode 100644 index 00000000..eb36c17f --- /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 a/src/tests/from_bits.rs b/src/tests/from_bits.rs new file mode 100644 index 00000000..b0f4edea --- /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 a/src/tests/from_bits_retain.rs b/src/tests/from_bits_retain.rs new file mode 100644 index 00000000..4fc77267 --- /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 a/src/tests/from_bits_truncate.rs b/src/tests/from_bits_truncate.rs new file mode 100644 index 00000000..7f4372a4 --- /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 a/src/tests/from_name.rs b/src/tests/from_name.rs new file mode 100644 index 00000000..11bba431 --- /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 a/src/tests/insert.rs b/src/tests/insert.rs new file mode 100644 index 00000000..b18cd172 --- /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 a/src/tests/intersection.rs b/src/tests/intersection.rs new file mode 100644 index 00000000..10a8ae9f --- /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 a/src/tests/intersects.rs b/src/tests/intersects.rs new file mode 100644 index 00000000..fe907981 --- /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 a/src/tests/is_all.rs b/src/tests/is_all.rs new file mode 100644 index 00000000..382a458f --- /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 a/src/tests/is_empty.rs b/src/tests/is_empty.rs new file mode 100644 index 00000000..92165f18 --- /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 a/src/tests/iter.rs b/src/tests/iter.rs new file mode 100644 index 00000000..b16d37f5 --- /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 a/src/tests/parser.rs b/src/tests/parser.rs new file mode 100644 index 00000000..67d5337c --- /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 a/src/tests/remove.rs b/src/tests/remove.rs new file mode 100644 index 00000000..574b1edb --- /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 a/src/tests/symmetric_difference.rs b/src/tests/symmetric_difference.rs new file mode 100644 index 00000000..75e9123a --- /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 a/src/tests/union.rs b/src/tests/union.rs new file mode 100644 index 00000000..61906819 --- /dev/null +++ b/src/tests/union.rs @@ -0,0 +1,71 @@ +use super::*; + +use crate::Flags; + +#[test] +fn cases() { + case( + TestFlags::empty(), + &[ + (TestFlags::A, 1), + (TestFlags::all(), 1 | 1 << 1 | 1 << 2), + (TestFlags::empty(), 0), + (TestFlags::from_bits_retain(1 << 3), 1 << 3), + ], + TestFlags::union, + ); + + case( + TestFlags::A | TestFlags::C, + &[ + (TestFlags::A | TestFlags::B, 1 | 1 << 1 | 1 << 2), + (TestFlags::A, 1 | 1 << 2), + ], + TestFlags::union, + ); +} + +#[track_caller] +fn case<T: Flags + std::fmt::Debug + std::ops::BitOr<Output = T> + std::ops::BitOrAssign + Copy>( + value: T, + inputs: &[(T, T::Bits)], + mut inherent: impl FnMut(T, T) -> T, +) where + T::Bits: std::fmt::Debug + PartialEq + Copy, +{ + for (input, expected) in inputs { + assert_eq!( + *expected, + inherent(value, *input).bits(), + "{:?}.union({:?})", + value, + input + ); + assert_eq!( + *expected, + Flags::union(value, *input).bits(), + "Flags::union({:?}, {:?})", + value, + input + ); + assert_eq!( + *expected, + (value | *input).bits(), + "{:?} | {:?}", + value, + input + ); + assert_eq!( + *expected, + { + let mut value = value; + value |= *input; + value + } + .bits(), + "{:?} |= {:?}", + value, + input, + ); + } +} diff --git a/tests/basic.rs b/tests/basic.rs index 790ec41c..a14ccc91 100644 --- 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 index 86e0392b..799461ea 100644 --- 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)
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.
2023-06-26T07:21:41Z
2.3
bitflags/bitflags
355
bitflags__bitflags-355
[ "357" ]
31d3e4afefc964045156d7fe3622733f48511353
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 6ebd5a74..15d1f950 100644 --- 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 index 0fda40c0..7f8a5c5d 100644 --- 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 index f3fbac0d..103b5d1e 100644 --- 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; @@ -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; @@ -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; @@ -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; @@ -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 { @@ -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, ) } @@ -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) } } }; @@ -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; - )* + )* } ) => {}; } @@ -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; @@ -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) } } }; @@ -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; + )* + } ) => {}; } @@ -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, @@ -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 index 8347b03f..c4fb6533 100644 --- 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; @@ -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 { @@ -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 index ab278406..9a0059f8 100644 --- 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 @@ -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; @@ -623,7 +624,7 @@ macro_rules! bitflags { } __impl_public_bitflags_iter! { - $BitFlags + $BitFlags: $T, $BitFlags } }; @@ -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; @@ -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 index d650fc43..57ab0ea8 100644 --- 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, @@ -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; @@ -138,7 +138,7 @@ macro_rules! __impl_public_bitflags { } ) => { __impl_bitflags! { - $PublicBitFlags: $T { + $BitFlags: $T { fn empty() { Self(<$T as $crate::Bits>::EMPTY) } @@ -260,7 +260,7 @@ macro_rules! __impl_public_bitflags { } } - __impl_public_bitflags_ops!($PublicBitFlags); + __impl_public_bitflags_ops!($BitFlags); }; } @@ -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> { @@ -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 {
diff --git a/tests/compile-fail/bitflags_custom_bits.rs b/tests/compile-fail/bitflags_custom_bits.rs index 46fde469..b719de4f 100644 --- 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 @@ -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 index c74c27f0..86e0392b 100644 --- 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`: @@ -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 a/tests/compile-pass/bitflags_self_in_value.rs b/tests/compile-pass/bitflags_self_in_value.rs new file mode 100644 index 00000000..2a9a4a56 --- /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 index 9ff4305d..6f84ff33 100644 --- a/tests/smoke-test/src/main.rs +++ b/tests/smoke-test/src/main.rs @@ -1,3 +1,5 @@ +#![deny(warnings)] + use bitflags::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!
2023-05-17T11:22:15Z
2.3
bitflags/bitflags
351
bitflags__bitflags-351
[ "348" ]
1d8388bf4ce18afde846d220ad8b6e0dc40aae94
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a32e1d55..6ebd5a74 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -10,40 +10,21 @@ permissions: jobs: check: - name: "Tests / OS: ${{ matrix.os }} - ${{ matrix.channel }}-${{ matrix.rust_target }}" - runs-on: ${{ matrix.os }} + name: "Tests" + runs-on: ubuntu-latest strategy: matrix: - exclude: - - os: macos-10.15 - rust_target: x86_64-gnu - - os: macos-10.15 - rust_target: x86_64-msvc - - os: windows-2019 - rust_target: x86_64-apple-darwin - - os: ubuntu-20.04 - rust_target: x86_64-msvc - - os: ubuntu-20.04 - rust_target: x86_64-apple-darwin channel: - stable - beta - nightly - os: - - macos-10.15 - - windows-2019 - - ubuntu-20.04 - rust_target: - - x86_64-gnu - - x86_64-msvc - - x86_64-apple-darwin steps: - name: Checkout repository uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - name: Install Rust Toolchain - run: rustup default ${{ matrix.channel }}-${{ matrix.rust_target }} + run: rustup default ${{ matrix.channel }} - name: Install cargo-hack run: cargo install cargo-hack @@ -87,6 +68,19 @@ jobs: cd ./tests/smoke-test cargo +$msrv build + mips: + name: Tests / MIPS (Big Endian) + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab + + - name: Install Cross + run: cargo install cross + + - name: Default features + run: cross test --target mips-unknown-linux-gnu + embedded: name: Build (embedded) runs-on: ubuntu-latest diff --git a/Cargo.toml b/Cargo.toml index a2391324..5ff8cf23 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ rustversion = "1.0" serde_derive = "1.0" serde_json = "1.0" serde_test = "1.0" +zerocopy = "0.6" arbitrary = { version = "1.0", features = ["derive"] } bytemuck = { version = "1.0", features = ["derive"] } diff --git a/examples/custom_bits_type.rs b/examples/custom_bits_type.rs new file mode 100644 index 00000000..0364a2bd --- /dev/null +++ b/examples/custom_bits_type.rs @@ -0,0 +1,85 @@ +use std::ops::{BitAnd, BitOr, BitXor, Not}; + +use bitflags::{Flags, Flag, Bits}; + +// Define a custom container that can be used in flags types +// Note custom bits types can't be used in `bitflags!` +// without making the trait impls `const`. This is currently +// unstable +#[derive(Clone, Copy, Debug)] +pub struct CustomBits([bool; 3]); + +impl Bits for CustomBits { + const EMPTY: Self = CustomBits([false; 3]); + + const ALL: Self = CustomBits([true; 3]); +} + +impl PartialEq for CustomBits { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} + +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]]) + } +} + +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]]) + } +} + +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]]) + } +} + +impl Not for CustomBits { + type Output = Self; + + fn not(self) -> Self { + CustomBits([!self.0[0], !self.0[1], !self.0[2]]) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct CustomFlags(CustomBits); + +impl CustomFlags { + pub const A: Self = CustomFlags(CustomBits([true, false, false])); + pub const B: Self = CustomFlags(CustomBits([false, true, false])); + pub const C: Self = CustomFlags(CustomBits([false, false, true])); +} + +impl Flags for CustomFlags { + const FLAGS: &'static [Flag<Self>] = &[ + Flag::new("A", Self::A), + Flag::new("B", Self::B), + Flag::new("C", Self::C), + ]; + + type Bits = CustomBits; + + fn bits(&self) -> Self::Bits { + self.0 + } + + fn from_bits_retain(bits: Self::Bits) -> Self { + CustomFlags(bits) + } +} + +fn main() { + println!("{:?}", CustomFlags::A.union(CustomFlags::C)); +} diff --git a/examples/custom_derive.rs b/examples/custom_derive.rs new file mode 100644 index 00000000..5a85afb9 --- /dev/null +++ b/examples/custom_derive.rs @@ -0,0 +1,23 @@ +//! An example of implementing the `BitFlags` trait manually for a flags type. + +use std::str; + +use bitflags::bitflags; + +// Define a flags type outside of the `bitflags` macro as a newtype +// It can accept custom derives for libaries `bitflags` doesn't support natively +#[derive(zerocopy::AsBytes, zerocopy::FromBytes)] +#[repr(transparent)] +pub struct ManualFlags(u32); + +// Next: use `impl Flags` instead of `struct Flags` +bitflags! { + impl ManualFlags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); + } +} + +fn main() {} diff --git a/examples/fmt.rs b/examples/fmt.rs index 3bb9b8c4..724b2074 100644 --- a/examples/fmt.rs +++ b/examples/fmt.rs @@ -2,40 +2,40 @@ use core::{fmt, str}; -fn main() -> Result<(), bitflags::parser::ParseError> { - bitflags::bitflags! { - // You can `#[derive]` the `Debug` trait, but implementing it manually - // can produce output like `A | B` instead of `Flags(A | B)`. - // #[derive(Debug)] - #[derive(PartialEq, Eq)] - pub struct Flags: u32 { - const A = 1; - const B = 2; - const C = 4; - const D = 8; - } +bitflags::bitflags! { + // You can `#[derive]` the `Debug` trait, but implementing it manually + // can produce output like `A | B` instead of `Flags(A | B)`. + // #[derive(Debug)] + #[derive(PartialEq, Eq)] + pub struct Flags: u32 { + const A = 1; + const B = 2; + const C = 4; + const D = 8; } +} - impl fmt::Debug for Flags { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&self.0, f) - } +impl fmt::Debug for Flags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + bitflags::parser::to_writer(self, f) } +} - impl fmt::Display for Flags { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } +impl fmt::Display for Flags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + bitflags::parser::to_writer(self, f) } +} - impl str::FromStr for Flags { - type Err = bitflags::parser::ParseError; +impl str::FromStr for Flags { + type Err = bitflags::parser::ParseError; - fn from_str(flags: &str) -> Result<Self, Self::Err> { - Ok(Self(flags.parse()?)) - } + fn from_str(flags: &str) -> Result<Self, Self::Err> { + bitflags::parser::from_str(flags) } +} +fn main() -> Result<(), bitflags::parser::ParseError> { let flags = Flags::A | Flags::B; println!("{}", flags); diff --git a/examples/macro_free.rs b/examples/macro_free.rs new file mode 100644 index 00000000..ec3a8cb5 --- /dev/null +++ b/examples/macro_free.rs @@ -0,0 +1,58 @@ +//! An example of implementing the `BitFlags` trait manually for a flags type. +//! +//! This example doesn't use any macros. + +use std::{fmt, str}; + +use bitflags::{Flags, Flag}; + +// First: Define your flags type. It just needs to be `Sized + 'static`. +pub struct ManualFlags(u32); + +// Not required: Define some constants for valid flags +impl ManualFlags { + pub const A: ManualFlags = ManualFlags(0b00000001); + pub const B: ManualFlags = ManualFlags(0b00000010); + pub const C: ManualFlags = ManualFlags(0b00000100); + pub const ABC: ManualFlags = ManualFlags(0b00000111); +} + +// Next: Implement the `BitFlags` trait, specifying your set of valid flags +// and iterators +impl Flags for ManualFlags { + const FLAGS: &'static [Flag<Self>] = &[ + Flag::new("A", Self::A), + Flag::new("B", Self::B), + Flag::new("C", Self::C), + ]; + + type Bits = u32; + + fn bits(&self) -> u32 { + self.0 + } + + fn from_bits_retain(bits: u32) -> Self { + Self(bits) + } +} + +// Not required: Add parsing support +impl str::FromStr for ManualFlags { + type Err = bitflags::parser::ParseError; + + fn from_str(input: &str) -> Result<Self, Self::Err> { + bitflags::parser::from_str(input) + } +} + +// Not required: Add formatting support +impl fmt::Display for ManualFlags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + bitflags::parser::to_writer(self, f) + } +} + +fn main() { + println!("{}", ManualFlags::A.union(ManualFlags::B).union(ManualFlags::C)); +} diff --git a/src/example_generated.rs b/src/example_generated.rs index b7589014..0fda40c0 100644 --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -9,30 +9,41 @@ __declare_public_bitflags! { /// This is the same `Flags` struct defined in the [crate level example](../index.html#example). /// Note that this struct is just for documentation purposes only, it must not be used outside /// this crate. - pub struct Flags; + pub struct Flags } __declare_internal_bitflags! { - pub struct Field0: u32; - pub struct Iter; - pub struct IterRaw; + pub struct Field0: u32 } __impl_internal_bitflags! { - Field0: u32, Flags, Iter, IterRaw { - A; - B; - C; - ABC; + Field0: u32, 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(); } } -__impl_public_bitflags! { - Flags: u32, Field0, Iter, IterRaw; +__impl_public_bitflags_forward! { + Flags: u32, Field0 +} + +__impl_public_bitflags_iter! { + Flags } __impl_public_bitflags_consts! { - Flags { + Flags: u32 { /// Field `A`. /// /// This flag has the value `0b00000001`. diff --git a/src/external.rs b/src/external.rs index 6b07ff64..f3fbac0d 100644 --- a/src/external.rs +++ b/src/external.rs @@ -5,7 +5,13 @@ 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: +First, we create a module under `external`, like `serde` with any specialized code. +Ideally, any utilities in here should just work off the `Flags` trait and maybe a +few other assumed bounds. + +Next, re-export the library from the `__private` module here. + +Next, define a macro like so: ```rust #[macro_export(local_inner_macros)] @@ -57,27 +63,78 @@ __impl_external_bitflags_my_library! { } } ``` +*/ -What about libraries that _must_ be supported through `#[derive]`? +pub(crate) mod __private { + #[cfg(feature = "serde")] + pub use serde; -In these cases, the attributes will need to be added to the `__declare_internal_bitflags` macro when -the internal type is declared. -*/ + #[cfg(feature = "arbitrary")] + pub use arbitrary; + + #[cfg(feature = "bytemuck")] + pub use bytemuck; +} #[cfg(feature = "serde")] -pub mod serde_support; +pub mod serde; + +/// Implement `Serialize` and `Deserialize` for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] #[cfg(feature = "serde")] -pub use serde; +macro_rules! __impl_external_bitflags_serde { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + 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::serialize( + self, + 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> { + $crate::serde::deserialize( + deserializer, + ) + } + } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "serde"))] +macro_rules! __impl_external_bitflags_serde { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => {}; +} #[cfg(feature = "arbitrary")] -pub mod arbitrary_support; -#[cfg(feature = "arbitrary")] -pub use arbitrary; +pub mod arbitrary; #[cfg(feature = "bytemuck")] -pub mod bytemuck_support; -#[cfg(feature = "bytemuck")] -pub use bytemuck; +mod bytemuck; /// Implements traits from external libraries for the internal bitflags type. #[macro_export(local_inner_macros)] @@ -124,57 +181,6 @@ macro_rules! __impl_external_bitflags { }; } -/// Implement `Serialize` and `Deserialize` for the internal bitflags type. -#[macro_export(local_inner_macros)] -#[doc(hidden)] -#[cfg(feature = "serde")] -macro_rules! __impl_external_bitflags_serde { - ( - $InternalBitFlags:ident: $T:ty { - $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* - } - ) => { - 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::__private::serde_support::serialize_bits_default::<$InternalBitFlags, $T, S>( - &self, - 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> { - $crate::__private::serde_support::deserialize_bits_default::<$InternalBitFlags, $T, D>( - deserializer, - ) - } - } - }; -} - -#[macro_export(local_inner_macros)] -#[doc(hidden)] -#[cfg(not(feature = "serde"))] -macro_rules! __impl_external_bitflags_serde { - ( - $InternalBitFlags:ident: $T:ty { - $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* - } - ) => {}; -} - /// Implement `Arbitrary` for the internal bitflags type. #[macro_export(local_inner_macros)] #[doc(hidden)] @@ -192,7 +198,7 @@ macro_rules! __impl_external_bitflags_arbitrary { 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) + $crate::arbitrary::arbitrary(u) } } }; diff --git a/src/external/arbitrary_support.rs b/src/external/arbitrary.rs similarity index 54% rename from src/external/arbitrary_support.rs rename to src/external/arbitrary.rs index 56708f01..ae59677a 100644 --- a/src/external/arbitrary_support.rs +++ b/src/external/arbitrary.rs @@ -1,3 +1,17 @@ +//! Specialized fuzzing for flags types using `arbitrary`. + +use crate::Flags; + +/// Get a random known flags value. +pub fn arbitrary<'a, B: Flags>( + u: &mut arbitrary::Unstructured<'a>, +) -> arbitrary::Result<B> +where + B::Bits: arbitrary::Arbitrary<'a> +{ + B::from_bits(u.arbitrary()?).ok_or_else(|| arbitrary::Error::IncorrectFormat) +} + #[cfg(test)] mod tests { use arbitrary::Arbitrary; diff --git a/src/external/bytemuck_support.rs b/src/external/bytemuck.rs similarity index 100% rename from src/external/bytemuck_support.rs rename to src/external/bytemuck.rs diff --git a/src/external/serde_support.rs b/src/external/serde.rs similarity index 64% rename from src/external/serde_support.rs rename to src/external/serde.rs index 7c202a29..bc1f2ece 100644 --- a/src/external/serde_support.rs +++ b/src/external/serde.rs @@ -1,59 +1,66 @@ +//! Specialized serialization for flags types using `serde`. + use core::{fmt, str}; +use crate::{Flags, parser::{self, ParseHex, WriteHex}}; use serde::{ de::{Error, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }; -pub fn serialize_bits_default<T: fmt::Display + AsRef<B>, B: Serialize, S: Serializer>( - flags: &T, +/// 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> { +) -> Result<S::Ok, S::Error> +where + B::Bits: WriteHex + Serialize, +{ // Serialize human-readable flags as a string like `"A | B"` if serializer.is_human_readable() { - serializer.collect_str(flags) + serializer.collect_str(&parser::AsDisplay(flags)) } // Serialize non-human-readable flags directly as the underlying bits else { - flags.as_ref().serialize(serializer) + flags.bits().serialize(serializer) } } -pub fn deserialize_bits_default< +/// Deserialize a set of flags from a human-readable string or their underlying bits. +pub fn deserialize< 'de, - T: str::FromStr + From<B>, - B: Deserialize<'de>, + B: Flags, D: Deserializer<'de>, >( deserializer: D, -) -> Result<T, D::Error> +) -> Result<B, D::Error> where - <T as str::FromStr>::Err: fmt::Display, + B::Bits: ParseHex + Deserialize<'de>, { if deserializer.is_human_readable() { // Deserialize human-readable flags by parsing them from strings like `"A | B"` - struct FlagsVisitor<T>(core::marker::PhantomData<T>); + struct FlagsVisitor<B>(core::marker::PhantomData<B>); - impl<'de, T: str::FromStr> Visitor<'de> for FlagsVisitor<T> + impl<'de, B: Flags> Visitor<'de> for FlagsVisitor<B> where - <T as str::FromStr>::Err: fmt::Display, + B::Bits: ParseHex, { - type Value = T; + type Value = B; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a string value of `|` separated flags") } fn visit_str<E: Error>(self, flags: &str) -> Result<Self::Value, E> { - flags.parse().map_err(|e| E::custom(e)) + parser::from_str(flags).map_err(|e| E::custom(e)) } } deserializer.deserialize_str(FlagsVisitor(Default::default())) } else { // Deserialize non-human-readable flags directly from the underlying bits - let bits = B::deserialize(deserializer)?; + let bits = B::Bits::deserialize(deserializer)?; - Ok(bits.into()) + Ok(B::from_bits_retain(bits)) } } diff --git a/src/internal.rs b/src/internal.rs index eca0a304..8347b03f 100644 --- a/src/internal.rs +++ b/src/internal.rs @@ -10,29 +10,14 @@ #[doc(hidden)] macro_rules! __declare_internal_bitflags { ( - $vis:vis struct $InternalBitFlags:ident: $T:ty; - $iter_vis:vis struct $Iter:ident; - $iter_names_vis:vis struct $IterNames:ident; + $vis:vis struct $InternalBitFlags:ident: $T:ty ) => { // 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 { - bits: $T, - } - - $iter_vis struct $Iter { - inner: $IterNames, - done: bool, - } - - $iter_names_vis struct $IterNames { - idx: usize, - source: $InternalBitFlags, - state: $InternalBitFlags, - } + $vis struct $InternalBitFlags($T); }; } @@ -44,14 +29,18 @@ macro_rules! __declare_internal_bitflags { #[doc(hidden)] macro_rules! __impl_internal_bitflags { ( - $InternalBitFlags:ident: $T:ty, $BitFlags:ident, $Iter:ident, $IterNames:ident { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* - $Flag:ident; + $Flag:ident = $value:expr; )* } ) => { - impl $crate::__private::PublicFlags for $BitFlags { + // NOTE: This impl is also used to prevent using bits types from non-primitive types + // in the `bitflags` macro. If this approach is changed, this guard will need to be + // retained somehow + impl $crate::__private::PublicFlags for $PublicBitFlags { + type Primitive = $T; type Internal = $InternalBitFlags; } @@ -73,7 +62,7 @@ macro_rules! __impl_internal_bitflags { // We can remove this `0x0` and remain compatible with `FromStr`, // because an empty string will still parse to an empty set of flags, // just like `0x0` does. - $crate::__private::core::write!(f, "{:#x}", <$T as $crate::__private::Bits>::EMPTY) + $crate::__private::core::write!(f, "{:#x}", <$T as $crate::Bits>::EMPTY) } else { $crate::__private::core::fmt::Display::fmt(self, f) } @@ -82,489 +71,74 @@ macro_rules! __impl_internal_bitflags { impl $crate::__private::core::fmt::Display for $InternalBitFlags { fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter<'_>) -> $crate::__private::core::fmt::Result { - // A formatter for bitflags that produces text output like: - // - // A | B | 0xf6 - // - // The names of set flags are written in a bar-separated-format, - // followed by a hex number of any remaining bits that are set - // but don't correspond to any flags. - - // Iterate over the valid flags - let mut first = true; - let mut iter = self.iter_names(); - for (name, _) in &mut 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 = iter.state.bits(); - if extra_bits != <$T as $crate::__private::Bits>::EMPTY { - if !first { - f.write_str(" | ")?; - } - - $crate::__private::core::write!(f, "{:#x}", extra_bits)?; - } - - $crate::__private::core::fmt::Result::Ok(()) + $crate::parser::to_writer(&$PublicBitFlags(*self), f) } } - // The impl for `FromStr` should parse anything produced by `Display` impl $crate::__private::core::str::FromStr for $InternalBitFlags { type Err = $crate::parser::ParseError; fn from_str(s: &str) -> $crate::__private::core::result::Result<Self, Self::Err> { - let s = s.trim(); - - let mut parsed_flags = Self::empty(); - - // If the input is empty then return an empty set of flags - if s.is_empty() { - return $crate::__private::core::result::Result::Ok(parsed_flags); - } - - for flag in s.split('|') { - let flag = flag.trim(); - - // If the flag is empty then we've got missing input - if flag.is_empty() { - return $crate::__private::core::result::Result::Err($crate::parser::ParseError::empty_flag()); - } - - // 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 $crate::__private::core::option::Option::Some(flag) = flag.strip_prefix("0x") { - let bits = <$T>::from_str_radix(flag, 16).map_err(|_| $crate::parser::ParseError::invalid_hex_flag(flag))?; - - Self::from_bits_retain(bits) - } - // Otherwise the flag is a name - // The generated flags type will determine whether - // or not it's a valid identifier - else { - Self::from_name(flag).ok_or_else(|| $crate::parser::ParseError::invalid_named_flag(flag))? - }; - - parsed_flags.insert(parsed_flag); - } - - $crate::__private::core::result::Result::Ok(parsed_flags) - } - } - - 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) + $crate::parser::from_str::<$PublicBitFlags>(s).map(|flags| flags.0) } } - 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::convert::AsRef<$T> for $InternalBitFlags { + fn as_ref(&self) -> &$T { + &self.0 } } - 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) + impl $crate::__private::core::convert::From<$T> for $InternalBitFlags { + fn from(bits: $T) -> Self { + Self::from_bits_retain(bits) } } - 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; + // The internal flags type offers a similar API to the public one + __impl_public_bitflags! { + $InternalBitFlags: $T { $( - __expr_safe_flags!( - $(#[$attr $($args)*])* - { - if bits & $BitFlags::$Flag.bits() == $BitFlags::$Flag.bits() { - truncated |= $BitFlags::$Flag.bits() - } - } - ); + $(#[$attr $($args)*])* + $Flag; )* - - Self { bits: truncated } - } - - #[inline] - pub const fn from_bits_retain(bits: $T) -> Self { - Self { bits } } + } - #[inline] - pub fn from_name(name: &str) -> $crate::__private::core::option::Option<Self> { + __impl_public_bitflags_consts! { + $InternalBitFlags: $T { $( - __expr_safe_flags!( - $(#[$attr $($args)*])* - { - if name == $crate::__private::core::stringify!($Flag) { - return $crate::__private::core::option::Option::Some(Self { bits: $BitFlags::$Flag.bits() }); - } - } - ); + $(#[$attr $($args)*])* + #[allow( + dead_code, + deprecated, + unused_attributes, + non_upper_case_globals + )] + $Flag = $value; )* - - let _ = name; - $crate::__private::core::option::Option::None - } - - #[inline] - pub const fn iter(&self) -> $Iter { - $Iter { - inner: self.iter_names(), - done: false, - } - } - - #[inline] - pub const fn iter_names(&self) -> $IterNames { - $IterNames { - idx: 0, - source: *self, - state: *self, - } - } - - #[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 } } + } + impl $InternalBitFlags { + /// Returns a mutable reference to the raw value of the flags currently stored. #[inline] - #[must_use] - pub const fn difference(self, other: Self) -> Self { - Self { bits: self.bits & !other.bits } + pub fn bits_mut(&mut self) -> &mut $T { + &mut self.0 } + /// Iterate over enabled flag values. #[inline] - #[must_use] - pub const fn symmetric_difference(self, other: Self) -> Self { - Self { bits: self.bits ^ other.bits } + 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] - #[must_use] - pub const fn complement(self) -> Self { - Self::from_bits_truncate(!self.bits) - } - } - - impl $crate::__private::core::convert::AsRef<$T> for $InternalBitFlags { - fn as_ref(&self) -> &$T { - &self.bits - } - } - - impl $crate::__private::core::convert::From<$T> for $InternalBitFlags { - fn from(bits: $T) -> Self { - Self::from_bits_retain(bits) - } - } - - impl $crate::__private::core::iter::Iterator for $Iter { - type Item = $BitFlags; - - fn next(&mut self) -> $crate::__private::core::option::Option<Self::Item> { - match self.inner.next().map(|(_, value)| value) { - $crate::__private::core::option::Option::Some(value) => $crate::__private::core::option::Option::Some(value), - $crate::__private::core::option::Option::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.state != $InternalBitFlags::empty() { - $crate::__private::core::option::Option::Some($BitFlags::from_bits_retain(self.inner.state.bits())) - } else { - $crate::__private::core::option::Option::None - } - }, - _ => $crate::__private::core::option::Option::None, - } - } - } - - impl $crate::__private::core::iter::Iterator for $IterNames { - type Item = (&'static str, $BitFlags); - - fn next(&mut self) -> $crate::__private::core::option::Option<Self::Item> { - const NUM_FLAGS: usize = { - let mut num_flags = 0; - - $( - __expr_safe_flags!( - $(#[$attr $($args)*])* - { - { num_flags += 1; } - } - ); - )* - - num_flags - }; - - const OPTIONS: [$T; NUM_FLAGS] = [ - $( - __expr_safe_flags!( - $(#[$attr $($args)*])* - { - $BitFlags::$Flag.bits() - } - ), - )* - ]; - - const OPTIONS_NAMES: [&'static str; NUM_FLAGS] = [ - $( - __expr_safe_flags!( - $(#[$attr $($args)*])* - { - $crate::__private::core::stringify!($Flag) - } - ), - )* - ]; - - if self.state.is_empty() || NUM_FLAGS == 0 { - $crate::__private::core::option::Option::None - } else { - #[allow(clippy::indexing_slicing)] - for (flag, flag_name) in OPTIONS[self.idx..NUM_FLAGS].iter().copied() - .zip(OPTIONS_NAMES[self.idx..NUM_FLAGS].iter().copied()) - { - self.idx += 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.source.contains($InternalBitFlags { bits: flag }) { - self.state.remove($InternalBitFlags { bits: flag }); - - return $crate::__private::core::option::Option::Some((flag_name, $BitFlags::from_bits_retain(flag))) - } - } - - $crate::__private::core::option::Option::None - } + 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)) } } }; } - -/// 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/iter.rs b/src/iter.rs new file mode 100644 index 00000000..4b6210e2 --- /dev/null +++ b/src/iter.rs @@ -0,0 +1,133 @@ +//! Iterating over set flag values. + +use crate::{Flags, Flag}; + +/// An iterator over a set of flags. +/// +/// Any bits that don't correspond to a valid flag will be yielded +/// as a final item from the iterator. +pub struct Iter<B: 'static> { + inner: IterNames<B>, + done: bool, +} + +impl<B: Flags> Iter<B> { + /// Create a new iterator over the given set of flags. + pub(crate) fn new(flags: &B) -> Self { + Iter { + inner: IterNames::new(flags), + done: false, + } + } +} + +impl<B: 'static> Iter<B> { + #[doc(hidden)] + pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, state: B) -> Self { + Iter { + inner: IterNames::__private_const_new(flags, source, state), + done: false, + } + } +} + +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())) + } else { + None + } + } + None => None, + } + } +} + +/// An iterator over a set of flags and their names. +/// +/// Any bits that don't correspond to a valid flag will be ignored. +pub struct IterNames<B: 'static> { + flags: &'static [Flag<B>], + idx: usize, + source: B, + state: B, +} + +impl<B: Flags> IterNames<B> { + /// Create a new iterator over the given set of flags. + pub(crate) fn new(flags: &B) -> Self { + IterNames { + flags: B::FLAGS, + idx: 0, + state: B::from_bits_retain(flags.bits()), + source: B::from_bits_retain(flags.bits()), + } + } +} + +impl<B: 'static> IterNames<B> { + #[doc(hidden)] + pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, state: B) -> Self { + IterNames { + flags, + idx: 0, + state, + source, + } + } + + /// Get the remaining (unyielded) flags. + /// + /// Once the iterator has finished, this method can be used to + /// check whether or not there are any bits that didn't correspond + /// to a valid flag remaining. + pub fn remaining(&self) -> &B { + &self.state + } +} + +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() { + return None; + } + + self.idx += 1; + + 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: + // + // 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)); + + return Some((flag.name(), B::from_bits_retain(bits))); + } + } + + None + } +} diff --git a/src/lib.rs b/src/lib.rs index d28fd87f..2c29b64a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -374,16 +374,16 @@ //! } //! ``` //! -//! [`from_bits`]: BitFlags::from_bits -//! [`from_bits_truncate`]: BitFlags::from_bits_truncate +//! [`from_bits`]: Flags::from_bits +//! [`from_bits_truncate`]: Flags::from_bits_truncate //! -//! # The `BitFlags` trait +//! # The `Flags` trait //! -//! This library defines a `BitFlags` trait that's implemented by all generated flags types. +//! This library defines a `Flags` trait that's implemented by all generated flags types. //! The trait makes it possible to work with flags types generically: //! //! ``` -//! fn count_unset_flags<F: bitflags::BitFlags>(flags: &F) -> usize { +//! fn count_unset_flags<F: bitflags::Flags>(flags: &F) -> usize { //! // Find out how many flags there are in total //! let total = F::all().iter().count(); //! @@ -422,22 +422,29 @@ #![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.2.1")] #[doc(inline)] -pub use traits::BitFlags; +pub use traits::{Flags, Flag, Bits}; +pub mod iter; pub mod parser; + mod traits; #[doc(hidden)] pub mod __private { - pub use crate::{external::*, traits::*}; + pub use crate::{external::__private::*, traits::__private::*}; pub use core; } +#[allow(unused_imports)] +pub use external::*; + +#[allow(deprecated)] +pub use traits::BitFlags; + /* How does the bitflags crate work? @@ -563,20 +570,14 @@ macro_rules! bitflags { // This type appears in the end-user's API __declare_public_bitflags! { $(#[$outer])* - $vis struct $BitFlags; + $vis struct $BitFlags } // Workaround for: https://github.com/bitflags/bitflags/issues/320 __impl_public_bitflags_consts! { - $BitFlags { + $BitFlags: $T { $( $(#[$inner $($args)*])* - #[allow( - dead_code, - deprecated, - unused_attributes, - non_upper_case_globals - )] $Flag = $value; )* } @@ -595,16 +596,14 @@ macro_rules! bitflags { // Declared in a "hidden" scope that can't be reached directly // These types don't appear in the end-user's API __declare_internal_bitflags! { - $vis struct InternalBitFlags: $T; - $vis struct Iter; - $vis struct IterRaw; + $vis struct InternalBitFlags: $T } __impl_internal_bitflags! { - InternalBitFlags: $T, $BitFlags, Iter, IterRaw { + InternalBitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* - $Flag; + $Flag = $value; )* } } @@ -619,8 +618,59 @@ macro_rules! bitflags { } } + __impl_public_bitflags_forward! { + $BitFlags: $T, InternalBitFlags + } + + __impl_public_bitflags_iter! { + $BitFlags + } + }; + + bitflags! { + $($t)* + } + }; + ( + impl $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )* + } + + $($t:tt)* + ) => { + __impl_public_bitflags_consts! { + $BitFlags: $T { + $( + $(#[$inner $($args)*])* + $Flag = $value; + )* + } + } + + #[allow( + dead_code, + deprecated, + unused_doc_comments, + unused_attributes, + unused_mut, + unused_imports, + non_upper_case_globals + )] + const _: () = { __impl_public_bitflags! { - $BitFlags: $T, InternalBitFlags, Iter, IterRaw; + $BitFlags: $T { + $( + $(#[$inner $($args)*])* + $Flag; + )* + } + } + + __impl_public_bitflags_iter! { + $BitFlags } }; @@ -631,6 +681,357 @@ macro_rules! bitflags { () => {}; } +/// Implement functions on bitflags types. +/// +/// 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 { + ( + $PublicBitFlags:ident: $T:ty { + fn empty() $empty:block + fn all() $all:block + fn bits($bits0:ident) $bits:block + fn from_bits($from_bits0:ident) $from_bits:block + fn from_bits_truncate($from_bits_truncate0:ident) $from_bits_truncate:block + fn from_bits_retain($from_bits_retain0:ident) $from_bits_retain:block + fn from_name($from_name0:ident) $from_name:block + fn is_empty($is_empty0:ident) $is_empty:block + fn is_all($is_all0:ident) $is_all:block + fn intersects($intersects0:ident, $intersects1:ident) $intersects:block + fn contains($contains0:ident, $contains1:ident) $contains:block + fn insert($insert0:ident, $insert1:ident) $insert:block + fn remove($remove0:ident, $remove1:ident) $remove:block + fn toggle($toggle0:ident, $toggle1:ident) $toggle:block + fn set($set0:ident, $set1:ident, $set2:ident) $set:block + fn intersection($intersection0:ident, $intersection1:ident) $intersection:block + fn union($union0:ident, $union1:ident) $union:block + fn difference($difference0:ident, $difference1:ident) $difference:block + fn symmetric_difference($symmetric_difference0:ident, $symmetric_difference1:ident) $symmetric_difference:block + fn complement($complement0:ident) $complement:block + } + ) => { + #[allow( + dead_code, + deprecated, + unused_attributes + )] + impl $PublicBitFlags { + /// Returns an empty set of flags. + #[inline] + pub const fn empty() -> Self { + $empty + } + + /// Returns the set containing all flags. + #[inline] + pub const fn all() -> Self { + $all + } + + /// Returns the raw value of the flags currently stored. + #[inline] + pub const fn bits(&self) -> $T { + let $bits0 = self; + $bits + } + + /// Convert from underlying bit representation, unless that + /// representation contains bits that do not correspond to a flag. + #[inline] + pub const fn from_bits(bits: $T) -> $crate::__private::core::option::Option<Self> { + let $from_bits0 = bits; + $from_bits + } + + /// Convert from underlying bit representation, dropping any bits + /// that do not correspond to flags. + #[inline] + pub const fn from_bits_truncate(bits: $T) -> Self { + let $from_bits_truncate0 = bits; + $from_bits_truncate + } + + /// Convert from underlying bit representation, preserving all + /// bits (even those not corresponding to a defined flag). + #[inline] + pub const fn from_bits_retain(bits: $T) -> Self { + let $from_bits_retain0 = bits; + $from_bits_retain + } + + /// Get the value for a flag from its stringified name. + /// + /// Names are _case-sensitive_, so must correspond exactly to + /// the identifier given to the flag. + #[inline] + pub fn from_name(name: &str) -> $crate::__private::core::option::Option<Self> { + let $from_name0 = name; + $from_name + } + + /// Returns `true` if no flags are currently stored. + #[inline] + pub const fn is_empty(&self) -> bool { + let $is_empty0 = self; + $is_empty + } + + /// Returns `true` if all flags are currently set. + #[inline] + pub const fn is_all(&self) -> bool { + let $is_all0 = self; + $is_all + } + + /// Returns `true` if there are flags common to both `self` and `other`. + #[inline] + pub const fn intersects(&self, other: Self) -> bool { + let $intersects0 = self; + let $intersects1 = other; + $intersects + } + + /// Returns `true` if all of the flags in `other` are contained within `self`. + #[inline] + pub const fn contains(&self, other: Self) -> bool { + let $contains0 = self; + let $contains1 = other; + $contains + } + + /// Inserts the specified flags in-place. + #[inline] + pub fn insert(&mut self, other: Self) { + let $insert0 = self; + let $insert1 = other; + $insert + } + + /// Removes the specified flags in-place. + #[inline] + pub fn remove(&mut self, other: Self) { + let $remove0 = self; + let $remove1 = other; + $remove + } + + /// Toggles the specified flags in-place. + #[inline] + pub fn toggle(&mut self, other: Self) { + let $toggle0 = self; + let $toggle1 = other; + $toggle + } + + /// Inserts or removes the specified flags depending on the passed value. + #[inline] + pub fn set(&mut self, other: Self, value: bool) { + let $set0 = self; + let $set1 = other; + let $set2 = value; + $set + } + + /// Returns the intersection between the flags in `self` and + /// `other`. + /// + /// Specifically, the returned set contains only the flags which are + /// present in *both* `self` *and* `other`. + /// + /// This is equivalent to using the `&` operator (e.g. + /// [`ops::BitAnd`]), as in `flags & other`. + /// + /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html + #[inline] + #[must_use] + pub const fn intersection(self, other: Self) -> Self { + let $intersection0 = self; + let $intersection1 = other; + $intersection + } + + /// Returns the union of between the flags in `self` and `other`. + /// + /// Specifically, the returned set contains all flags which are + /// present in *either* `self` *or* `other`, including any which are + /// present in both (see [`Self::symmetric_difference`] if that + /// is undesirable). + /// + /// This is equivalent to using the `|` operator (e.g. + /// [`ops::BitOr`]), as in `flags | other`. + /// + /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html + #[inline] + #[must_use] + pub const fn union(self, other: Self) -> Self { + let $union0 = self; + let $union1 = other; + $union + } + + /// Returns the difference between the flags in `self` and `other`. + /// + /// Specifically, the returned set contains all flags present in + /// `self`, except for the ones present in `other`. + /// + /// It is also conceptually equivalent to the "bit-clear" operation: + /// `flags & !other` (and this syntax is also supported). + /// + /// This is equivalent to using the `-` operator (e.g. + /// [`ops::Sub`]), as in `flags - other`. + /// + /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html + #[inline] + #[must_use] + pub const fn difference(self, other: Self) -> Self { + let $difference0 = self; + let $difference1 = other; + $difference + } + + /// Returns the [symmetric difference][sym-diff] between the flags + /// in `self` and `other`. + /// + /// Specifically, the returned set contains the flags present which + /// are present in `self` or `other`, but that are not present in + /// both. Equivalently, it contains the flags present in *exactly + /// one* of the sets `self` and `other`. + /// + /// This is equivalent to using the `^` operator (e.g. + /// [`ops::BitXor`]), as in `flags ^ other`. + /// + /// [sym-diff]: https://en.wikipedia.org/wiki/Symmetric_difference + /// [`ops::BitXor`]: https://doc.rust-lang.org/std/ops/trait.BitXor.html + #[inline] + #[must_use] + pub const fn symmetric_difference(self, other: Self) -> Self { + let $symmetric_difference0 = self; + let $symmetric_difference1 = other; + $symmetric_difference + } + + /// Returns the complement of this set of flags. + /// + /// Specifically, the returned set contains all the flags which are + /// not set in `self`, but which are allowed for this type. + /// + /// Alternatively, it can be thought of as the set difference + /// between [`Self::all()`] and `self` (e.g. `Self::all() - self`) + /// + /// This is equivalent to using the `!` operator (e.g. + /// [`ops::Not`]), as in `!flags`. + /// + /// [`Self::all()`]: Self::all + /// [`ops::Not`]: https://doc.rust-lang.org/std/ops/trait.Not.html + #[inline] + #[must_use] + pub const fn complement(self) -> Self { + let $complement0 = self; + $complement + } + } + }; +} + +/// 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! __bitflags_expr_safe_attrs { + // 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 } + ) => { + __bitflags_expr_safe_attrs! { + expr: { $e }, + attrs: { + // All attributes start here + unprocessed: [$(#[$inner $($args)*])*], + // Attributes that are safe on expressions go 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 + ( + expr: { $e:expr }, + attrs: { + unprocessed: [ + // cfg matched here + #[cfg $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: [$($expr:tt)*], + }, + ) => { + __bitflags_expr_safe_attrs! { + expr: { $e }, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: [ + $($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:tt)*], + }, + ) => { + __bitflags_expr_safe_attrs! { + expr: { $e }, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: [ + // $other not added here + $($expr)* + ], + }, + } + }; + // Once all attributes on all flags are processed, generate the actual code + ( + expr: { $e:expr }, + attrs: { + unprocessed: [], + processed: [$(#[$expr:ident $($exprargs:tt)*])*], + }, + ) => { + $(#[$expr $($exprargs)*])* + { $e } + } +} + #[macro_use] mod public; #[macro_use] @@ -650,6 +1051,9 @@ mod tests { 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."] @@ -686,6 +1090,17 @@ mod tests { 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! { @@ -724,6 +1139,8 @@ mod tests { 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); @@ -738,6 +1155,8 @@ mod tests { 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) @@ -756,6 +1175,8 @@ mod tests { 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() @@ -776,6 +1197,8 @@ mod tests { 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), @@ -789,6 +1212,8 @@ mod tests { 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()); @@ -806,6 +1231,8 @@ mod tests { 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()); @@ -818,6 +1245,8 @@ mod tests { let e2 = Flags::empty(); assert!(!e1.intersects(e2)); + assert!(!<Flags as crate::Flags>::intersects(&e1, e2)); + assert!(AnotherSetOfFlags::ANOTHER_FLAG.intersects(AnotherSetOfFlags::ANOTHER_FLAG)); } @@ -826,6 +1255,8 @@ mod tests { let e1 = Flags::empty(); let e2 = Flags::ABC; assert!(!e1.intersects(e2)); + + assert!(!<Flags as crate::Flags>::intersects(&e1, e2)); } #[test] @@ -833,6 +1264,8 @@ mod tests { let e1 = Flags::A; let e2 = Flags::B; assert!(!e1.intersects(e2)); + + assert!(!<Flags as crate::Flags>::intersects(&e1, e2)); } #[test] @@ -840,6 +1273,8 @@ mod tests { let e1 = Flags::A; let e2 = Flags::A | Flags::B; assert!(e1.intersects(e2)); + + assert!(<Flags as crate::Flags>::intersects(&e1, e2)); } #[test] @@ -850,6 +1285,8 @@ mod tests { 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())); @@ -862,6 +1299,11 @@ mod tests { 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); @@ -874,6 +1316,11 @@ mod tests { 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()); @@ -926,6 +1373,8 @@ mod tests { 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); @@ -941,15 +1390,24 @@ mod tests { 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] @@ -1287,7 +1745,6 @@ mod tests { parse_case(FmtFlags::empty(), ""); parse_case(FmtFlags::empty(), " \r\n\t"); parse_case(FmtFlags::empty(), "0x0"); - parse_case(FmtFlags::empty(), "0x0"); parse_case(FmtFlags::고양이, "고양이"); parse_case(FmtFlags::고양이, " 고양이 "); diff --git a/src/parser.rs b/src/parser.rs index 48f3c610..aac9042f 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -28,7 +28,118 @@ #![allow(clippy::let_unit_value)] -use core::fmt; +use core::fmt::{self, Write}; + +use crate::{Flags, Bits}; + +/// Write a set of flags to a writer. +/// +/// Any bits that don't correspond to a valid flag will be formatted +/// as a hex number. +pub fn to_writer<B: Flags>(flags: &B, mut writer: impl Write) -> Result<(), fmt::Error> +where + B::Bits: WriteHex, +{ + // A formatter for bitflags that produces text output like: + // + // A | B | 0xf6 + // + // The names of set flags are written in a bar-separated-format, + // followed by a hex number of any remaining bits that are set + // but don't correspond to any flags. + + // Iterate over the valid flags + let mut first = true; + let mut iter = flags.iter_names(); + for (name, _) in &mut iter { + if !first { + writer.write_str(" | ")?; + } + + first = false; + writer.write_str(name)?; + } + + // Append any extra bits that correspond to flags to the end of the format + let remaining = iter.remaining().bits(); + if remaining != B::Bits::EMPTY { + if !first { + writer.write_str(" | ")?; + } + + writer.write_str("0x")?; + remaining.write_hex(writer)?; + } + + fmt::Result::Ok(()) +} + +pub(crate) struct AsDisplay<'a, B>(pub(crate) &'a B); + +impl<'a, B: Flags> fmt::Display for AsDisplay<'a, B> +where + B::Bits: WriteHex, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + to_writer(self.0, f) + } +} + +/// Parse a set of flags from text. +/// +/// This function will fail on unknown flags rather than ignore them. +pub fn from_str<B: Flags>(input: &str) -> Result<B, ParseError> +where + B::Bits: ParseHex, +{ + let mut parsed_flags = B::empty(); + + // If the input is empty then return an empty set of flags + if input.trim().is_empty() { + return Ok(parsed_flags); + } + + for flag in input.split('|') { + let flag = flag.trim(); + + // If the flag is empty then we've got missing input + if flag.is_empty() { + return Err(ParseError::empty_flag()); + } + + // 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))?; + + B::from_bits_retain(bits) + } + // Otherwise the flag is a name + // The generated flags type will determine whether + // or not it's a valid identifier + else { + B::from_name(flag).ok_or_else(|| ParseError::invalid_named_flag(flag))? + }; + + parsed_flags.insert(parsed_flag); + } + + Ok(parsed_flags) +} + +/// Encode a value as a hex number. +pub trait WriteHex { + /// Write the value as hex. + fn write_hex<W: fmt::Write>(&self, writer: W) -> fmt::Result; +} + +/// Parse a value from a number encoded as a hex string. +pub trait ParseHex { + /// Parse the value from hex. + fn parse_hex(input: &str) -> Result<Self, ParseError> + where + Self: Sized; +} /// An error encountered while parsing flags from text. #[derive(Debug)] diff --git a/src/public.rs b/src/public.rs index 643f8438..d650fc43 100644 --- a/src/public.rs +++ b/src/public.rs @@ -11,10 +11,10 @@ macro_rules! __declare_public_bitflags { ( $(#[$outer:meta])* - $vis:vis struct $BitFlags:ident; + $vis:vis struct $PublicBitFlags:ident ) => { $(#[$outer])* - $vis struct $BitFlags(<$BitFlags as $crate::__private::PublicFlags>::Internal); + $vis struct $PublicBitFlags(<$PublicBitFlags as $crate::__private::PublicFlags>::Internal); }; } @@ -24,236 +24,302 @@ macro_rules! __declare_public_bitflags { /// could conflict with items added by the end-user. #[macro_export(local_inner_macros)] #[doc(hidden)] -macro_rules! __impl_public_bitflags { +macro_rules! __impl_public_bitflags_forward { ( - $PublicBitFlags:ident: $T:ty, $InternalBitFlags:ident, $Iter:ident, $IterNames:ident; + $PublicBitFlags:ident: $T:ty, $InternalBitFlags:ident ) => { - impl $crate::__private::core::fmt::Binary for $PublicBitFlags { - 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_bitflags! { + $PublicBitFlags: $T { + fn empty() { + Self($InternalBitFlags::empty()) + } - 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.0, f) - } - } + fn all() { + Self($InternalBitFlags::all()) + } - 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.0, f) + fn bits(f) { + f.0.bits() + } + + fn from_bits(bits) { + match $InternalBitFlags::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, + } + } + + fn from_bits_truncate(bits) { + Self($InternalBitFlags::from_bits_truncate(bits)) + } + + fn from_bits_retain(bits) { + Self($InternalBitFlags::from_bits_retain(bits)) + } + + 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, + } + } + + fn is_empty(f) { + f.0.is_empty() + } + + fn is_all(f) { + f.0.is_all() + } + + fn intersects(f, other) { + f.0.intersects(other.0) + } + + fn contains(f, other) { + f.0.contains(other.0) + } + + fn insert(f, other) { + f.0.insert(other.0) + } + + fn remove(f, other) { + f.0.remove(other.0) + } + + fn toggle(f, other) { + f.0.toggle(other.0) + } + + fn set(f, other, value) { + f.0.set(other.0, value) + } + + fn intersection(f, other) { + Self(f.0.intersection(other.0)) + } + + fn union(f, other) { + Self(f.0.union(other.0)) + } + + fn difference(f, other) { + Self(f.0.difference(other.0)) + } + + fn symmetric_difference(f, other) { + Self(f.0.symmetric_difference(other.0)) + } + + fn complement(f) { + Self(f.0.complement()) + } } } - 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.0, f) - } + __impl_public_bitflags_ops!($PublicBitFlags); + }; +} + +/// 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_public_bitflags { + ( + $PublicBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* } + ) => { + __impl_bitflags! { + $PublicBitFlags: $T { + fn empty() { + Self(<$T as $crate::Bits>::EMPTY) + } - impl $PublicBitFlags { - /// Returns an empty set of flags. - #[inline] - pub const fn empty() -> Self { - Self($InternalBitFlags::empty()) - } + fn all() { + Self::from_bits_truncate(<$T as $crate::Bits>::ALL) + } - /// Returns the set containing all flags. - #[inline] - pub const fn all() -> Self { - Self($InternalBitFlags::all()) - } + fn bits(f) { + f.0 + } - /// Returns the raw value of the flags currently stored. - #[inline] - pub const fn bits(&self) -> $T { - self.0.bits() - } + fn from_bits(bits) { + let truncated = Self::from_bits_truncate(bits).0; - /// 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> { - match $InternalBitFlags::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, + if truncated == bits { + $crate::__private::core::option::Option::Some(Self(bits)) + } else { + $crate::__private::core::option::Option::None + } } - } - /// Convert from underlying bit representation, dropping any bits - /// that do not correspond to flags. - #[inline] - pub const fn from_bits_truncate(bits: $T) -> Self { - Self($InternalBitFlags::from_bits_truncate(bits)) - } + fn from_bits_truncate(bits) { + if bits == <$T as $crate::Bits>::EMPTY { + return Self(bits) + } + + let mut truncated = <$T as $crate::Bits>::EMPTY; + + $( + __bitflags_expr_safe_attrs!( + $(#[$attr $($args)*])* + { + if bits & $PublicBitFlags::$Flag.bits() == $PublicBitFlags::$Flag.bits() { + truncated = truncated | $PublicBitFlags::$Flag.bits() + } + } + ); + )* + + Self(truncated) + } - /// Convert from underlying bit representation, preserving all - /// bits (even those not corresponding to a defined flag). - #[inline] - pub const fn from_bits_retain(bits: $T) -> Self { - Self($InternalBitFlags::from_bits_retain(bits)) - } + fn from_bits_retain(bits) { + Self(bits) + } - /// Get the value for a flag from its stringified name. - /// - /// Names are _case-sensitive_, so must correspond exactly to - /// the identifier given to the flag. - #[inline] - pub fn from_name(name: &str) -> $crate::__private::core::option::Option<Self> { - 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, + fn from_name(name) { + $( + __bitflags_expr_safe_attrs!( + $(#[$attr $($args)*])* + { + if name == $crate::__private::core::stringify!($Flag) { + return $crate::__private::core::option::Option::Some(Self($PublicBitFlags::$Flag.bits())); + } + } + ); + )* + + let _ = name; + $crate::__private::core::option::Option::None } - } - /// Iterate over enabled flag values. - #[inline] - pub const fn iter(&self) -> $Iter { - self.0.iter() - } + fn is_empty(f) { + f.0 == Self::empty().0 + } - /// Iterate over enabled flag values with their stringified names. - #[inline] - pub const fn iter_names(&self) -> $IterNames { - self.0.iter_names() - } + fn is_all(f) { + Self::all().0 | f.0 == f.0 + } - /// Returns `true` if no flags are currently stored. - #[inline] - pub const fn is_empty(&self) -> bool { - self.0.is_empty() - } + fn intersects(f, other) { + !(Self(f.0 & other.0)).is_empty() + } - /// Returns `true` if all flags are currently set. - #[inline] - pub const fn is_all(&self) -> bool { - self.0.is_all() - } + fn contains(f, other) { + (f.0 & other.0) == other.0 + } - /// Returns `true` if there are flags common to both `self` and `other`. - #[inline] - pub const fn intersects(&self, other: Self) -> bool { - self.0.intersects(other.0) - } + fn insert(f, other) { + f.0 = f.0 | 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.0.contains(other.0) - } + fn remove(f, other) { + f.0 = f.0 & !other.0; + } - /// Inserts the specified flags in-place. - #[inline] - pub fn insert(&mut self, other: Self) { - self.0.insert(other.0) - } + fn toggle(f, other) { + f.0 = f.0 ^ other.0; + } - /// Removes the specified flags in-place. - #[inline] - pub fn remove(&mut self, other: Self) { - self.0.remove(other.0) + fn set(f, other, value) { + if value { + f.insert(other); + } else { + f.remove(other); + } + } + + fn intersection(f, other) { + Self(f.0 & other.0) + } + + fn union(f, other) { + Self(f.0 | other.0) + } + + fn difference(f, other) { + Self(f.0 & !other.0) + } + + fn symmetric_difference(f, other) { + Self(f.0 ^ other.0) + } + + fn complement(f) { + Self::from_bits_truncate(!f.0) + } } + } + + __impl_public_bitflags_ops!($PublicBitFlags); + }; +} - /// Toggles the specified flags in-place. +/// Implement iterators on the public (user-facing) bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_public_bitflags_iter { + ($PublicBitFlags:ident) => { + impl $PublicBitFlags { + /// Iterate over enabled flag values. #[inline] - pub fn toggle(&mut self, other: Self) { - self.0.toggle(other.0) + 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())) } - /// Inserts or removes the specified flags depending on the passed value. + /// Iterate over enabled flag values with their stringified names. #[inline] - pub fn set(&mut self, other: Self, value: bool) { - self.0.set(other.0, value) + 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())) } + } - /// Returns the intersection between the flags in `self` and - /// `other`. - /// - /// Specifically, the returned set contains only the flags which are - /// present in *both* `self` *and* `other`. - /// - /// This is equivalent to using the `&` operator (e.g. - /// [`ops::BitAnd`]), as in `flags & other`. - /// - /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html - #[inline] - #[must_use] - pub const fn intersection(self, other: Self) -> Self { - Self(self.0.intersection(other.0)) + impl $crate::__private::core::iter::IntoIterator for $PublicBitFlags { + type Item = Self; + type IntoIter = $crate::iter::Iter<$PublicBitFlags>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() } + } + }; +} - /// Returns the union of between the flags in `self` and `other`. - /// - /// Specifically, the returned set contains all flags which are - /// present in *either* `self` *or* `other`, including any which are - /// present in both (see [`Self::symmetric_difference`] if that - /// is undesirable). - /// - /// This is equivalent to using the `|` operator (e.g. - /// [`ops::BitOr`]), as in `flags | other`. - /// - /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html - #[inline] - #[must_use] - pub const fn union(self, other: Self) -> Self { - Self(self.0.union(other.0)) +/// Implement traits on the public (user-facing) bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +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 { + $crate::__private::core::fmt::Binary::fmt(&self.0, f) } + } - /// Returns the difference between the flags in `self` and `other`. - /// - /// Specifically, the returned set contains all flags present in - /// `self`, except for the ones present in `other`. - /// - /// It is also conceptually equivalent to the "bit-clear" operation: - /// `flags & !other` (and this syntax is also supported). - /// - /// This is equivalent to using the `-` operator (e.g. - /// [`ops::Sub`]), as in `flags - other`. - /// - /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html - #[inline] - #[must_use] - pub const fn difference(self, other: Self) -> Self { - Self(self.0.difference(other.0)) + 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.0, f) } + } - /// Returns the [symmetric difference][sym-diff] between the flags - /// in `self` and `other`. - /// - /// Specifically, the returned set contains the flags present which - /// are present in `self` or `other`, but that are not present in - /// both. Equivalently, it contains the flags present in *exactly - /// one* of the sets `self` and `other`. - /// - /// This is equivalent to using the `^` operator (e.g. - /// [`ops::BitXor`]), as in `flags ^ other`. - /// - /// [sym-diff]: https://en.wikipedia.org/wiki/Symmetric_difference - /// [`ops::BitXor`]: https://doc.rust-lang.org/std/ops/trait.BitXor.html - #[inline] - #[must_use] - pub const fn symmetric_difference(self, other: Self) -> Self { - Self(self.0.symmetric_difference(other.0)) + 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.0, f) } + } - /// Returns the complement of this set of flags. - /// - /// Specifically, the returned set contains all the flags which are - /// not set in `self`, but which are allowed for this type. - /// - /// Alternatively, it can be thought of as the set difference - /// between [`Self::all()`] and `self` (e.g. `Self::all() - self`) - /// - /// This is equivalent to using the `!` operator (e.g. - /// [`ops::Not`]), as in `!flags`. - /// - /// [`Self::all()`]: Self::all - /// [`ops::Not`]: https://doc.rust-lang.org/std/ops/trait.Not.html - #[inline] - #[must_use] - pub const fn complement(self) -> Self { - Self(self.0.complement()) + 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.0, f) } } @@ -271,7 +337,7 @@ macro_rules! __impl_public_bitflags { /// Adds the set of flags. #[inline] fn bitor_assign(&mut self, other: Self) { - self.0 = self.0.union(other.0); + self.0 = self.0 | other.0; } } @@ -289,7 +355,7 @@ macro_rules! __impl_public_bitflags { /// Toggles the set of flags. #[inline] fn bitxor_assign(&mut self, other: Self) { - self.0 = self.0.symmetric_difference(other.0); + self.0 = self.0 ^ other.0 } } @@ -307,7 +373,7 @@ macro_rules! __impl_public_bitflags { /// Disables all flags disabled in the set. #[inline] fn bitand_assign(&mut self, other: Self) { - self.0 = self.0.intersection(other.0); + self.0 = self.0 & other.0; } } @@ -325,7 +391,7 @@ macro_rules! __impl_public_bitflags { /// Disables all flags enabled in the set. #[inline] fn sub_assign(&mut self, other: Self) { - self.0 = self.0.difference(other.0); + self.0 = self.0 & !other.0; } } @@ -356,92 +422,6 @@ macro_rules! __impl_public_bitflags { result } } - - impl $crate::__private::core::iter::IntoIterator for $PublicBitFlags { - type Item = Self; - type IntoIter = $Iter; - - fn into_iter(self) -> Self::IntoIter { - self.0.iter() - } - } - - impl $crate::BitFlags for $PublicBitFlags { - type Bits = $T; - - type Iter = $Iter; - type IterNames = $IterNames; - - fn empty() -> Self { - $PublicBitFlags::empty() - } - - fn all() -> Self { - $PublicBitFlags::all() - } - - fn bits(&self) -> $T { - $PublicBitFlags::bits(self) - } - - fn from_bits(bits: $T) -> $crate::__private::core::option::Option<$PublicBitFlags> { - $PublicBitFlags::from_bits(bits) - } - - fn from_bits_truncate(bits: $T) -> $PublicBitFlags { - $PublicBitFlags::from_bits_truncate(bits) - } - - fn from_bits_retain(bits: $T) -> $PublicBitFlags { - $PublicBitFlags::from_bits_retain(bits) - } - - fn from_name(name: &str) -> $crate::__private::core::option::Option<$PublicBitFlags> { - $PublicBitFlags::from_name(name) - } - - fn iter(&self) -> Self::Iter { - $PublicBitFlags::iter(self) - } - - fn iter_names(&self) -> Self::IterNames { - $PublicBitFlags::iter_names(self) - } - - fn is_empty(&self) -> bool { - $PublicBitFlags::is_empty(self) - } - - fn is_all(&self) -> bool { - $PublicBitFlags::is_all(self) - } - - fn intersects(&self, other: $PublicBitFlags) -> bool { - $PublicBitFlags::intersects(self, other) - } - - fn contains(&self, other: $PublicBitFlags) -> bool { - $PublicBitFlags::contains(self, other) - } - - fn insert(&mut self, other: $PublicBitFlags) { - $PublicBitFlags::insert(self, other) - } - - fn remove(&mut self, other: $PublicBitFlags) { - $PublicBitFlags::remove(self, other) - } - - fn toggle(&mut self, other: $PublicBitFlags) { - $PublicBitFlags::toggle(self, other) - } - - fn set(&mut self, other: $PublicBitFlags, value: bool) { - $PublicBitFlags::set(self, other, value) - } - } - - impl $crate::__private::ImplementedByBitFlagsMacro for $PublicBitFlags {} }; } @@ -450,7 +430,7 @@ macro_rules! __impl_public_bitflags { #[doc(hidden)] macro_rules! __impl_public_bitflags_consts { ( - $PublicBitFlags:ident { + $PublicBitFlags:ident: $T:ty { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident = $value:expr; @@ -460,8 +440,39 @@ macro_rules! __impl_public_bitflags_consts { impl $PublicBitFlags { $( $(#[$attr $($args)*])* + #[allow( + deprecated, + non_upper_case_globals, + )] pub const $Flag: Self = Self::from_bits_retain($value); )* } + + impl $crate::Flags for $PublicBitFlags { + const FLAGS: &'static [$crate::Flag<$PublicBitFlags>] = &[ + $( + __bitflags_expr_safe_attrs!( + $(#[$attr $($args)*])* + { + #[allow( + deprecated, + non_upper_case_globals, + )] + $crate::Flag::new($crate::__private::core::stringify!($Flag), $PublicBitFlags::$Flag) + } + ), + )* + ]; + + type Bits = $T; + + fn bits(&self) -> $T { + $PublicBitFlags::bits(self) + } + + fn from_bits_retain(bits: $T) -> $PublicBitFlags { + $PublicBitFlags::from_bits_retain(bits) + } + } }; } diff --git a/src/traits.rs b/src/traits.rs index 85503e64..f8fc7572 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -1,23 +1,50 @@ -use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not}; +use core::{fmt, ops::{BitAnd, BitOr, BitXor, Not}}; -/// A trait that is automatically implemented for all bitflags. -/// -/// It should not be implemented manually. -pub trait BitFlags: ImplementedByBitFlagsMacro { - /// The underlying integer type. - type Bits: Bits; +use crate::{parser::{ParseError, ParseHex, WriteHex}, iter}; - /// An iterator over enabled flags in an instance of the type. - type Iter: Iterator<Item = Self>; +/// Metadata for an individual flag. +pub struct Flag<B> { + name: &'static str, + value: B, +} - /// An iterator over the raw names and bits for enabled flags in an instance of the type. - type IterNames: Iterator<Item = (&'static str, Self)>; +impl<B> Flag<B> { + /// Create a new flag with the given name and value. + pub const fn new(name: &'static str, value: B) -> Self { + Flag { name, value } + } + + /// Get the name of this flag. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Get the value of this flag. + pub const fn value(&self) -> &B { + &self.value + } +} + +/// A set of flags. +/// +/// This trait is automatically implemented for flags types defined using the `bitflags!` macro. +/// It can also be implemented manually for custom flags types. +pub trait Flags: Sized + 'static { + /// The set of available flags and their names. + const FLAGS: &'static [Flag<Self>]; + + /// The underlying storage type. + type Bits: Bits; /// Returns an empty set of flags. - fn empty() -> Self; + fn empty() -> Self { + Self::from_bits_retain(Self::Bits::EMPTY) + } /// Returns the set containing all flags. - fn all() -> Self; + fn all() -> Self { + Self::from_bits_truncate(Self::Bits::ALL) + } /// Returns the raw value of the flags currently stored. fn bits(&self) -> Self::Bits; @@ -28,9 +55,15 @@ pub trait BitFlags: ImplementedByBitFlagsMacro { /// Note that each [multi-bit flag] is treated as a unit for this comparison. /// /// [multi-bit flag]: index.html#multi-bit-flags - fn from_bits(bits: Self::Bits) -> Option<Self> - where - Self: Sized; + fn from_bits(bits: Self::Bits) -> Option<Self> { + let truncated = Self::from_bits_truncate(bits); + + if truncated.bits() == bits { + Some(truncated) + } else { + None + } + } /// Convert from underlying bit representation, dropping any bits /// that do not correspond to flags. @@ -38,81 +71,181 @@ pub trait BitFlags: ImplementedByBitFlagsMacro { /// Note that each [multi-bit flag] is treated as a unit for this comparison. /// /// [multi-bit flag]: index.html#multi-bit-flags - fn from_bits_truncate(bits: Self::Bits) -> Self; + fn from_bits_truncate(bits: Self::Bits) -> Self { + if bits == Self::Bits::EMPTY { + return Self::empty(); + } + + let mut truncated = Self::Bits::EMPTY; + + for flag in Self::FLAGS.iter() { + let flag = flag.value(); + + if bits & flag.bits() == flag.bits() { + truncated = truncated | flag.bits(); + } + } + + Self::from_bits_retain(truncated) + } /// Convert from underlying bit representation, preserving all /// bits (even those not corresponding to a defined flag). fn from_bits_retain(bits: Self::Bits) -> Self; /// Get the flag for a particular name. - fn from_name(name: &str) -> Option<Self> - where - Self: Sized; + 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())) + } + } + + None + } /// Iterate over enabled flag values. - fn iter(&self) -> Self::Iter; + fn iter(&self) -> iter::Iter<Self> { + iter::Iter::new(self) + } /// Iterate over the raw names and bits for enabled flag values. - fn iter_names(&self) -> Self::IterNames; + fn iter_names(&self) -> iter::IterNames<Self> { + iter::IterNames::new(self) + } /// Returns `true` if no flags are currently stored. - fn is_empty(&self) -> bool; + fn is_empty(&self) -> bool { + self.bits() == Self::Bits::EMPTY + } /// Returns `true` if all flags are currently set. - fn is_all(&self) -> bool; + fn is_all(&self) -> bool { + // NOTE: We check against `Self::all` here, not `Self::Bits::ALL` + // because the set of all flags may not use all bits + Self::all().bits() | self.bits() == self.bits() + } /// Returns `true` if there are flags common to both `self` and `other`. - fn intersects(&self, other: Self) -> bool; + fn intersects(&self, other: Self) -> bool + where + Self: Sized, + { + self.bits() & other.bits() != Self::Bits::EMPTY + } /// Returns `true` if all of the flags in `other` are contained within `self`. - fn contains(&self, other: Self) -> bool; + fn contains(&self, other: Self) -> bool + where + Self: Sized, + { + self.bits() & other.bits() == other.bits() + } /// Inserts the specified flags in-place. - fn insert(&mut self, other: Self); + fn insert(&mut self, other: Self) + where + Self: Sized, + { + *self = Self::from_bits_retain(self.bits() | other.bits()); + } /// Removes the specified flags in-place. - fn remove(&mut self, other: Self); + fn remove(&mut self, other: Self) + where + Self: Sized, + { + *self = Self::from_bits_retain(self.bits() & !other.bits()); + } /// Toggles the specified flags in-place. - fn toggle(&mut self, other: Self); + fn toggle(&mut self, other: Self) + where + Self: Sized, + { + *self = Self::from_bits_retain(self.bits() ^ other.bits()); + } /// Inserts or removes the specified flags depending on the passed value. - fn set(&mut self, other: Self, value: bool); -} + fn set(&mut self, other: Self, value: bool) + where + Self: Sized, + { + if value { + self.insert(other); + } else { + self.remove(other); + } + } -/// 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 {} + /// 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`. + #[must_use] + fn intersection(self, other: Self) -> Self { + Self::from_bits_retain(self.bits() & other.bits()) + } -// Not re-exported -pub trait Sealed {} + /// 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()) + } -// 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. + /// 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()) + } -/// 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)] + /// Returns the [symmetric difference][sym-diff] between the flags + /// in `self` and `other`. + /// + /// Specifically, the returned set contains the flags present which + /// are present in `self` or `other`, but that are not present in + /// both. Equivalently, it contains the flags present in *exactly + /// one* of the sets `self` and `other`. + /// + /// [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()) + } +} + +/// Underlying storage for a flags type. pub trait Bits: Clone + Copy - + BitAnd - + BitAndAssign - + BitOr - + BitOrAssign - + BitXor - + BitXorAssign - + Not + + PartialEq + + BitAnd<Output = Self> + + BitOr<Output = Self> + + BitXor<Output = Self> + + Not<Output = Self> + Sized - + Sealed + + 'static { /// The value of `Self` where no bits are set. const EMPTY: Self; @@ -121,6 +254,10 @@ pub trait Bits: const ALL: Self; } +// Not re-exported: prevent custom `Bits` impls being used in the `bitflags!` macro, +// or they may fail to compile based on crate features +pub trait Primitive {} + macro_rules! impl_bits { ($($u:ty, $i:ty,)*) => { $( @@ -134,8 +271,32 @@ macro_rules! impl_bits { const ALL: $i = <$u>::MAX as $i; } - impl Sealed for $u {} - impl Sealed for $i {} + impl ParseHex for $u { + fn parse_hex(input: &str) -> Result<Self, ParseError> { + <$u>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input)) + } + } + + impl ParseHex for $i { + fn parse_hex(input: &str) -> Result<Self, ParseError> { + <$i>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input)) + } + } + + impl WriteHex for $u { + fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result { + write!(writer, "{:x}", self) + } + } + + impl WriteHex for $i { + fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result { + write!(writer, "{:x}", self) + } + } + + impl Primitive for $i {} + impl Primitive for $u {} )* } } @@ -152,6 +313,37 @@ impl_bits! { /// A trait for referencing the `bitflags`-owned internal type /// without exposing it publicly. pub trait PublicFlags { + /// The type of the underlying storage. + type Primitive: Primitive; + /// The type of the internal field on the generated flags type. type Internal; } + +#[deprecated(note = "use the `Flags` trait instead")] +pub trait BitFlags: ImplementedByBitFlagsMacro + Flags { + /// An iterator over enabled flags in an instance of the type. + type Iter: Iterator<Item = Self>; + + /// An iterator over the raw names and bits for enabled flags in an instance of the type. + type IterNames: Iterator<Item = (&'static str, Self)>; +} + +#[allow(deprecated)] +impl<B: Flags> BitFlags for B { + type Iter = iter::Iter<Self>; + type IterNames = iter::IterNames<Self>; +} + +impl<B: Flags> ImplementedByBitFlagsMacro for B {} + +/// 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 {} + +pub(crate) mod __private { + pub use super::{ImplementedByBitFlagsMacro, PublicFlags}; +}
diff --git a/tests/compile-fail/visibility/private_flags.rs b/tests/compile-fail/access_outside_visibility.rs similarity index 100% rename from tests/compile-fail/visibility/private_flags.rs rename to tests/compile-fail/access_outside_visibility.rs diff --git a/tests/compile-fail/visibility/private_flags.stderr b/tests/compile-fail/access_outside_visibility.stderr similarity index 54% rename from tests/compile-fail/visibility/private_flags.stderr rename to tests/compile-fail/access_outside_visibility.stderr index 47a53c25..3106b9a2 100644 --- a/tests/compile-fail/visibility/private_flags.stderr +++ b/tests/compile-fail/access_outside_visibility.stderr @@ -1,11 +1,11 @@ error[E0603]: struct `Flags2` is private - --> tests/compile-fail/visibility/private_flags.rs:17:22 + --> tests/compile-fail/access_outside_visibility.rs:17:22 | 17 | let _ = example::Flags2::FLAG_B; | ^^^^^^ private struct | note: the struct `Flags2` is defined here - --> tests/compile-fail/visibility/private_flags.rs:4:5 + --> tests/compile-fail/access_outside_visibility.rs:4:5 | 4 | / bitflags! { 5 | | pub struct Flags1: u32 { @@ -15,4 +15,4 @@ note: the struct `Flags2` is defined here 11 | | } 12 | | } | |_____^ - = note: this error originates in the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `__declare_public_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_defined.rs b/tests/compile-fail/bitflags_custom_bits.rs similarity index 86% rename from tests/compile-fail/non_integer_base/all_defined.rs rename to tests/compile-fail/bitflags_custom_bits.rs index c2856b10..46fde469 100644 --- a/tests/compile-fail/non_integer_base/all_defined.rs +++ b/tests/compile-fail/bitflags_custom_bits.rs @@ -19,13 +19,18 @@ use std::{ }, }; -use bitflags::bitflags; +use bitflags::{bitflags, Bits, parser::{ParseError, FromHex}}; // 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 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] struct MyInt(u8); +impl Bits for MyInt { + const EMPTY: Self = MyInt(u8::MIN); + const ALL: Self = MyInt(u8::MAX); +} + impl BitAnd for MyInt { type Output = Self; @@ -68,6 +73,14 @@ impl BitXorAssign for MyInt { } } +impl Not for MyInt { + type Output = MyInt; + + fn not(self) -> Self { + MyInt(!self.0) + } +} + impl Debug for MyInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.0, f) @@ -104,11 +117,9 @@ impl Binary for MyInt { } } -impl Not for MyInt { - type Output = MyInt; - - fn not(self) -> Self { - MyInt(!self.0) +impl FromHex for MyInt { + fn from_hex(input: &str) -> Result<Self, ParseError> { + Ok(MyInt(u8::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))?)) } } diff --git a/tests/compile-fail/bitflags_custom_bits.stderr b/tests/compile-fail/bitflags_custom_bits.stderr new file mode 100644 index 00000000..c74c27f0 --- /dev/null +++ b/tests/compile-fail/bitflags_custom_bits.stderr @@ -0,0 +1,461 @@ +error[E0277]: the trait bound `MyInt: bitflags::traits::Primitive` is not satisfied + --> tests/compile-fail/bitflags_custom_bits.rs:127:22 + | +127 | struct Flags128: MyInt { + | ^^^^^ the trait `bitflags::traits::Primitive` is not implemented for `MyInt` + | + = help: the following other types implement trait `bitflags::traits::Primitive`: + i128 + i16 + i32 + i64 + i8 + isize + u128 + u16 + and $N others +note: required by a bound in `PublicFlags::Primitive` + --> src/traits.rs + | + | type Primitive: Primitive; + | ^^^^^^^^^ required by this bound in `PublicFlags::Primitive` + +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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 | | } + | |_^ 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 | | } + | |_^ + = 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 a/tests/compile-fail/syntax/missing_type.rs b/tests/compile-fail/bitflags_missing_type.rs similarity index 100% rename from tests/compile-fail/syntax/missing_type.rs rename to tests/compile-fail/bitflags_missing_type.rs diff --git a/tests/compile-fail/bitflags_missing_type.stderr b/tests/compile-fail/bitflags_missing_type.stderr new file mode 100644 index 00000000..dd9805b8 --- /dev/null +++ b/tests/compile-fail/bitflags_missing_type.stderr @@ -0,0 +1,17 @@ +error: no rules expected the token `{` + --> tests/compile-fail/bitflags_missing_type.rs:5:23 + | +5 | pub struct Flags1 { + | ^ no rules expected this token in macro call + | +note: while trying to match `:` + --> src/lib.rs + | + | $vis:vis struct $BitFlags:ident: $T:ty { + | ^ + +error[E0601]: `main` function not found in crate `$CRATE` + --> tests/compile-fail/bitflags_missing_type.rs:8:2 + | +8 | } + | ^ consider adding a `main` function to `$DIR/tests/compile-fail/bitflags_missing_type.rs` diff --git a/tests/compile-fail/syntax/missing_value.rs b/tests/compile-fail/bitflags_missing_value.rs similarity index 71% rename from tests/compile-fail/syntax/missing_value.rs rename to tests/compile-fail/bitflags_missing_value.rs index c1221035..3e6c557b 100644 --- a/tests/compile-fail/syntax/missing_value.rs +++ b/tests/compile-fail/bitflags_missing_value.rs @@ -2,7 +2,7 @@ extern crate bitflags; bitflags! { - pub struct Flags1 { + pub struct Flags1: u32 { const A; } } diff --git a/tests/compile-fail/bitflags_missing_value.stderr b/tests/compile-fail/bitflags_missing_value.stderr new file mode 100644 index 00000000..8c17c97d --- /dev/null +++ b/tests/compile-fail/bitflags_missing_value.stderr @@ -0,0 +1,17 @@ +error: no rules expected the token `;` + --> tests/compile-fail/bitflags_missing_value.rs:6:16 + | +6 | const A; + | ^ no rules expected this token in macro call + | +note: while trying to match `=` + --> src/lib.rs + | + | const $Flag:ident = $value:expr; + | ^ + +error[E0601]: `main` function not found in crate `$CRATE` + --> tests/compile-fail/bitflags_missing_value.rs:8:2 + | +8 | } + | ^ consider adding a `main` function to `$DIR/tests/compile-fail/bitflags_missing_value.rs` diff --git a/tests/compile-fail/visibility/pub_const.rs b/tests/compile-fail/bitflags_pub_const.rs similarity index 100% rename from tests/compile-fail/visibility/pub_const.rs rename to tests/compile-fail/bitflags_pub_const.rs diff --git a/tests/compile-fail/visibility/pub_const.stderr b/tests/compile-fail/bitflags_pub_const.stderr similarity index 52% rename from tests/compile-fail/visibility/pub_const.stderr rename to tests/compile-fail/bitflags_pub_const.stderr index b01122c7..3e5cedb8 100644 --- a/tests/compile-fail/visibility/pub_const.stderr +++ b/tests/compile-fail/bitflags_pub_const.stderr @@ -1,5 +1,11 @@ error: no rules expected the token `pub` - --> $DIR/pub_const.rs:5:9 + --> tests/compile-fail/bitflags_pub_const.rs:5:9 | 5 | pub const FLAG_A = 0b00000001; | ^^^ no rules expected this token in macro call + | +note: while trying to match `}` + --> src/lib.rs + | + | } + | ^ diff --git a/tests/compile-fail/redefined.rs b/tests/compile-fail/bitflags_redefined.rs similarity index 67% rename from tests/compile-fail/redefined.rs rename to tests/compile-fail/bitflags_redefined.rs index 6d194d6c..07941f36 100644 --- a/tests/compile-fail/redefined.rs +++ b/tests/compile-fail/bitflags_redefined.rs @@ -2,13 +2,13 @@ extern crate bitflags; bitflags! { - pub struct Flags1 { + pub struct Flags1: u32 { const A = 1; } } bitflags! { - pub struct Flags1 { + pub struct Flags1: u32 { const A = 1; } } diff --git a/tests/compile-fail/bitflags_redefined.stderr b/tests/compile-fail/bitflags_redefined.stderr new file mode 100644 index 00000000..a1611a1c --- /dev/null +++ b/tests/compile-fail/bitflags_redefined.stderr @@ -0,0 +1,804 @@ +error[E0428]: the name `Flags1` is defined multiple times + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ `Flags1` redefined here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- previous definition of the type `Flags1` here + | + = note: `Flags1` must be defined only once in the type namespace of this module + = note: this error originates in the macro `__declare_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0601]: `main` function not found in crate `$CRATE` + --> tests/compile-fail/bitflags_redefined.rs:14:2 + | +14 | } + | ^ consider adding a `main` function to `$DIR/tests/compile-fail/bitflags_redefined.rs` + +error[E0119]: conflicting implementations of trait `Flags` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_consts` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `PublicFlags` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = 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[E0119]: conflicting implementations of trait `Binary` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `Octal` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `LowerHex` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `UpperHex` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `BitOr` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `BitOrAssign` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `BitXor` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `BitXorAssign` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `BitAnd` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `BitAndAssign` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `Sub` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `SubAssign` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `Not` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `Extend<Flags1>` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `FromIterator<Flags1>` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_ops` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IntoIterator` for type `Flags1` + --> tests/compile-fail/bitflags_redefined.rs:10:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_- first implementation here +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_^ conflicting implementation for `Flags1` + | + = note: this error originates in the macro `__impl_public_bitflags_iter` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `A` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `A` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `A` + | + = note: this error originates in the macro `__impl_public_bitflags_consts` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `empty` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `empty` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `empty` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `all` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `all` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `all` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `bits` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `bits` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `bits` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `from_bits` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `from_bits` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `from_bits` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `from_bits_truncate` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `from_bits_truncate` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `from_bits_truncate` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `from_bits_retain` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `from_bits_retain` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `from_bits_retain` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `from_name` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `from_name` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `from_name` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `is_empty` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `is_empty` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `is_empty` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `is_all` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `is_all` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `is_all` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `intersects` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `intersects` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `intersects` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `contains` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `contains` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `contains` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `insert` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `insert` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `insert` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `remove` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `remove` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `remove` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `toggle` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `toggle` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `toggle` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `set` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `set` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `set` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `intersection` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `intersection` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `intersection` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `union` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `union` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `union` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `difference` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `difference` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `difference` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `symmetric_difference` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `symmetric_difference` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `symmetric_difference` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `complement` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `complement` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `complement` + | + = note: this error originates in the macro `__impl_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `iter` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `iter` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `iter` + | + = note: this error originates in the macro `__impl_public_bitflags_iter` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0592]: duplicate definitions with name `iter_names` + --> tests/compile-fail/bitflags_redefined.rs:4:1 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const A = 1; +7 | | } +8 | | } + | |_^ duplicate definitions for `iter_names` +9 | +10 | / bitflags! { +11 | | pub struct Flags1: u32 { +12 | | const A = 1; +13 | | } +14 | | } + | |_- other definition for `iter_names` + | + = note: this error originates in the macro `__impl_public_bitflags_iter` 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/bitflags_trait_custom.rs b/tests/compile-fail/bitflags_trait_custom.rs new file mode 100644 index 00000000..945419c1 --- /dev/null +++ b/tests/compile-fail/bitflags_trait_custom.rs @@ -0,0 +1,9 @@ +use bitflags::BitFlags; + +pub struct BootlegFlags(u32); + +impl BitFlags for BootlegFlags { + type Bits = u32; +} + +fn main() {} diff --git a/tests/compile-fail/bitflags_trait_custom.stderr b/tests/compile-fail/bitflags_trait_custom.stderr new file mode 100644 index 00000000..b42f471d --- /dev/null +++ b/tests/compile-fail/bitflags_trait_custom.stderr @@ -0,0 +1,31 @@ +error[E0437]: type `Bits` is not a member of trait `BitFlags` + --> tests/compile-fail/bitflags_trait_custom.rs:6:5 + | +6 | type Bits = u32; + | ^^^^^^^^^^^^^^^^ not a member of trait `BitFlags` + +warning: use of deprecated trait `bitflags::BitFlags`: use the `Flags` trait instead + --> tests/compile-fail/bitflags_trait_custom.rs:1:15 + | +1 | use bitflags::BitFlags; + | ^^^^^^^^ + | + = note: `#[warn(deprecated)]` on by default + +warning: use of deprecated trait `bitflags::BitFlags`: use the `Flags` trait instead + --> tests/compile-fail/bitflags_trait_custom.rs:5:6 + | +5 | impl BitFlags for BootlegFlags { + | ^^^^^^^^ + +error[E0277]: the trait bound `BootlegFlags: Flags` is not satisfied + --> tests/compile-fail/bitflags_trait_custom.rs:5:19 + | +5 | impl BitFlags for BootlegFlags { + | ^^^^^^^^^^^^ the trait `Flags` is not implemented for `BootlegFlags` + | +note: required by a bound in `BitFlags` + --> src/traits.rs + | + | pub trait BitFlags: ImplementedByBitFlagsMacro + Flags { + | ^^^^^ required by this bound in `BitFlags` diff --git a/tests/compile-fail/bitflags_trait_deprecated.rs b/tests/compile-fail/bitflags_trait_deprecated.rs new file mode 100644 index 00000000..d17464e5 --- /dev/null +++ b/tests/compile-fail/bitflags_trait_deprecated.rs @@ -0,0 +1,5 @@ +#![deny(warnings)] + +pub use bitflags::BitFlags; + +fn main() {} diff --git a/tests/compile-fail/bitflags_trait_deprecated.stderr b/tests/compile-fail/bitflags_trait_deprecated.stderr new file mode 100644 index 00000000..1c81656c --- /dev/null +++ b/tests/compile-fail/bitflags_trait_deprecated.stderr @@ -0,0 +1,12 @@ +error: use of deprecated trait `bitflags::BitFlags`: use the `Flags` trait instead + --> tests/compile-fail/bitflags_trait_deprecated.rs:3:19 + | +3 | pub use bitflags::BitFlags; + | ^^^^^^^^ + | +note: the lint level is defined here + --> tests/compile-fail/bitflags_trait_deprecated.rs:1:9 + | +1 | #![deny(warnings)] + | ^^^^^^^^ + = note: `#[deny(deprecated)]` implied by `#[deny(warnings)]` diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr b/tests/compile-fail/non_integer_base/all_defined.stderr deleted file mode 100644 index e477281c..00000000 --- a/tests/compile-fail/non_integer_base/all_defined.stderr +++ /dev/null @@ -1,297 +0,0 @@ -error[E0277]: the trait bound `MyInt: Bits` is not satisfied - --> tests/compile-fail/non_integer_base/all_defined.rs:116:22 - | -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 - | - | type Bits: Bits; - | ^^^^ required by this bound in `bitflags::BitFlags::Bits` - -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]: 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]: 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]: 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]: 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.rs b/tests/compile-fail/non_integer_base/all_missing.rs deleted file mode 100644 index fff6b2cc..00000000 --- a/tests/compile-fail/non_integer_base/all_missing.rs +++ /dev/null @@ -1,13 +0,0 @@ -use bitflags::bitflags; - -struct MyInt(u8); - -bitflags! { - struct Flags128: MyInt { - const A = MyInt(0b0000_0001); - const B = MyInt(0b0000_0010); - const C = MyInt(0b0000_0100); - } -} - -fn main() {} diff --git a/tests/compile-fail/non_integer_base/all_missing.stderr b/tests/compile-fail/non_integer_base/all_missing.stderr deleted file mode 100644 index 7f047c68..00000000 --- a/tests/compile-fail/non_integer_base/all_missing.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0204]: the trait `Copy` may not be implemented for this type - --> tests/compile-fail/non_integer_base/all_missing.rs:5:1 - | -5 | / bitflags! { -6 | | struct Flags128: MyInt { -7 | | const A = MyInt(0b0000_0001); -8 | | const B = MyInt(0b0000_0010); -9 | | const C = MyInt(0b0000_0100); -10 | | } -11 | | } - | |_^ this field does not implement `Copy` - | - = 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 a/tests/compile-fail/redefined.stderr b/tests/compile-fail/redefined.stderr deleted file mode 100644 index 85bc7f10..00000000 --- a/tests/compile-fail/redefined.stderr +++ /dev/null @@ -1,17 +0,0 @@ -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 a/tests/compile-fail/syntax/missing_type.stderr b/tests/compile-fail/syntax/missing_type.stderr deleted file mode 100644 index ed8c8ac4..00000000 --- a/tests/compile-fail/syntax/missing_type.stderr +++ /dev/null @@ -1,11 +0,0 @@ -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 a/tests/compile-fail/syntax/missing_value.stderr b/tests/compile-fail/syntax/missing_value.stderr deleted file mode 100644 index 6b1b46a1..00000000 --- a/tests/compile-fail/syntax/missing_value.stderr +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 55dd929d..00000000 --- a/tests/compile-fail/trait/custom_impl.rs +++ /dev/null @@ -1,65 +0,0 @@ -use bitflags::BitFlags; - -pub struct BootlegFlags(u32); - -impl BitFlags for BootlegFlags { - type Bits = u32; - - fn empty() -> Self { - unimplemented!() - } - - fn all() -> Self { - unimplemented!() - } - - fn bits(&self) -> u32 { - unimplemented!() - } - - fn from_bits(_: u32) -> Option<BootlegFlags> { - unimplemented!() - } - - fn from_bits_truncate(_: u32) -> BootlegFlags { - unimplemented!() - } - - fn from_bits_retain(_: u32) -> BootlegFlags { - unimplemented!() - } - - fn is_empty(&self) -> bool { - unimplemented!() - } - - fn is_all(&self) -> bool { - unimplemented!() - } - - fn intersects(&self, _: BootlegFlags) -> bool { - unimplemented!() - } - - fn contains(&self, _: BootlegFlags) -> bool { - unimplemented!() - } - - fn insert(&mut self, _: BootlegFlags) { - unimplemented!() - } - - fn remove(&mut self, _: BootlegFlags) { - unimplemented!() - } - - fn toggle(&mut self, _: BootlegFlags) { - unimplemented!() - } - - fn set(&mut self, _: BootlegFlags, value: bool) { - unimplemented!() - } -} - -fn main() {} diff --git a/tests/compile-fail/trait/custom_impl.stderr b/tests/compile-fail/trait/custom_impl.stderr deleted file mode 100644 index d7e8d494..00000000 --- a/tests/compile-fail/trait/custom_impl.stderr +++ /dev/null @@ -1,11 +0,0 @@ -error[E0277]: the trait bound `BootlegFlags: ImplementedByBitFlagsMacro` is not satisfied - --> 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` - --> src/bitflags_trait.rs - | - | pub trait BitFlags: ImplementedByBitFlagsMacro { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `BitFlags` diff --git a/tests/compile-pass/cfg/nested-value.rs b/tests/compile-pass/bitflags_nested_value.rs similarity index 100% rename from tests/compile-pass/cfg/nested-value.rs rename to tests/compile-pass/bitflags_nested_value.rs diff --git a/tests/compile-pass/cfg/redefined-value.rs b/tests/compile-pass/bitflags_redefined_value.rs similarity index 100% rename from tests/compile-pass/cfg/redefined-value.rs rename to tests/compile-pass/bitflags_redefined_value.rs diff --git a/tests/compile-pass/bitflags_trait_bound_flags.rs b/tests/compile-pass/bitflags_trait_bound_flags.rs new file mode 100644 index 00000000..7a4d204a --- /dev/null +++ b/tests/compile-pass/bitflags_trait_bound_flags.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +use bitflags::{BitFlags, Flags}; + +pub trait MyCustomFlagsTrait { + fn uses_flags<B: BitFlags>(flags: B); +} + +pub struct MyCustomFlags; + +impl MyCustomFlagsTrait for MyCustomFlags { + fn uses_flags<B: Flags>(_: B) { + + } +} + +fn main() { + +} diff --git a/tests/compile-pass/trait/generic_iter.rs b/tests/compile-pass/bitflags_trait_generic_iter.rs similarity index 92% rename from tests/compile-pass/trait/generic_iter.rs rename to tests/compile-pass/bitflags_trait_generic_iter.rs index 686a303f..1310bd01 100644 --- a/tests/compile-pass/trait/generic_iter.rs +++ b/tests/compile-pass/bitflags_trait_generic_iter.rs @@ -1,3 +1,5 @@ +#![allow(deprecated)] + use bitflags::{bitflags, BitFlags}; bitflags! { diff --git a/tests/compile-pass/trait/precedence.rs b/tests/compile-pass/bitflags_trait_precedence.rs similarity index 93% rename from tests/compile-pass/trait/precedence.rs rename to tests/compile-pass/bitflags_trait_precedence.rs index f61db85d..a603233e 100644 --- a/tests/compile-pass/trait/precedence.rs +++ b/tests/compile-pass/bitflags_trait_precedence.rs @@ -1,3 +1,5 @@ +#![allow(deprecated)] + use bitflags::{bitflags, BitFlags}; bitflags! { diff --git a/tests/compile-pass/bitflags_trait_supertrait.rs b/tests/compile-pass/bitflags_trait_supertrait.rs new file mode 100644 index 00000000..5f87dd91 --- /dev/null +++ b/tests/compile-pass/bitflags_trait_supertrait.rs @@ -0,0 +1,80 @@ +#![allow(deprecated)] + +// From: https://github.com/bitflags/bitflags/issues/293#issuecomment-1493296383 +use core::{ + fmt::{Binary, LowerHex, Octal, UpperHex}, + ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, + } +}; + +use bitflags::{bitflags, BitFlags}; + +pub trait BitFlagsExt { + fn complement_retain(self) -> Self; + fn has_uncorresponding_bits(self) -> bool; +} +impl<T, U> BitFlagsExt for T +where + T: BitFlags<Bits = U> + + BitAnd<Output = T> + + BitAndAssign + + BitOr<Output = T> + + BitOrAssign + + BitXor<Output = T> + + BitXorAssign + + Not<Output = T> + + Sub<Output = T> + + SubAssign + + Extend<T> + + FromIterator<T> + + IntoIterator + + Binary + + LowerHex + + Octal + + UpperHex, + U: BitAnd<Output = U> + + BitAndAssign + + BitOr<Output = U> + + BitOrAssign + + BitXor<Output = U> + + BitXorAssign + + Not<Output = U> + + Shl<Output = U> + + ShlAssign + + Shr<Output = U> + + ShrAssign + + Add<Output = U> + + AddAssign + + Div<Output = U> + + DivAssign + + Mul<Output = U> + + MulAssign + + Rem<Output = U> + + RemAssign + + Sub<Output = U> + + SubAssign, +{ + fn complement_retain(self) -> Self { + Self::from_bits_retain(!self.bits()) + } + + fn has_uncorresponding_bits(self) -> bool { + !(self & Self::all().complement_retain()).is_empty() + } +} + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + } +} + +fn has_uncorresponding_bits<B: BitFlagsExt>(flags: B) -> bool { + flags.has_uncorresponding_bits() +} + +fn main() { + has_uncorresponding_bits(Flags::A); +} diff --git a/tests/compile-pass/bitflags_trait_to_flags.rs b/tests/compile-pass/bitflags_trait_to_flags.rs new file mode 100644 index 00000000..6a69d2d8 --- /dev/null +++ b/tests/compile-pass/bitflags_trait_to_flags.rs @@ -0,0 +1,31 @@ +#![allow(deprecated)] + +use bitflags::{bitflags, Flags, BitFlags}; + +fn uses_flags1<B: Flags>(f: B) -> usize { + uses_bitflags2(f) +} + +fn uses_bitflags1<B: BitFlags>(f: B) -> usize { + uses_flags2(f) +} + +fn uses_flags2<B: Flags>(f: B) -> usize { + f.iter().count() +} + +fn uses_bitflags2<B: BitFlags>(f: B) -> usize { + f.iter().count() +} + +bitflags! { + pub struct MyFlags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + } +} + +fn main() { + assert_eq!(uses_flags1(MyFlags::A | MyFlags::B), uses_bitflags1(MyFlags::A | MyFlags::B)); +} diff --git a/tests/compile-pass/visibility/pub_in.rs b/tests/compile-pass/bitflags_visibility.rs similarity index 100% rename from tests/compile-pass/visibility/pub_in.rs rename to tests/compile-pass/bitflags_visibility.rs diff --git a/tests/compile-pass/flags_trait_bound_bitflags.rs b/tests/compile-pass/flags_trait_bound_bitflags.rs new file mode 100644 index 00000000..f0653b6a --- /dev/null +++ b/tests/compile-pass/flags_trait_bound_bitflags.rs @@ -0,0 +1,19 @@ +#![allow(deprecated)] + +use bitflags::{BitFlags, Flags}; + +pub trait MyCustomFlagsTrait { + fn uses_flags<B: Flags>(flags: B); +} + +pub struct MyCustomFlags; + +impl MyCustomFlagsTrait for MyCustomFlags { + fn uses_flags<B: BitFlags>(_: B) { + + } +} + +fn main() { + +} diff --git a/tests/compile-pass/flags_trait_generic_iter.rs b/tests/compile-pass/flags_trait_generic_iter.rs new file mode 100644 index 00000000..988db416 --- /dev/null +++ b/tests/compile-pass/flags_trait_generic_iter.rs @@ -0,0 +1,16 @@ +use bitflags::{bitflags, Flags}; + +bitflags! { + struct MyFlags: u32 { + const A = 0b00000001; + const B = 0b00000010; + } +} + +fn count_flags<F: Flags>(flags: &F) -> usize { + flags.iter().count() +} + +fn main() { + assert_eq!(2, count_flags(&(MyFlags::A | MyFlags::B))); +} diff --git a/tests/compile-pass/flags_trait_precedence.rs b/tests/compile-pass/flags_trait_precedence.rs new file mode 100644 index 00000000..08b44a0a --- /dev/null +++ b/tests/compile-pass/flags_trait_precedence.rs @@ -0,0 +1,16 @@ +use bitflags::{bitflags, Flags}; + +bitflags! { + struct MyFlags: u32 { + const A = 0b00000001; + } +} + +fn all_from_trait<F: Flags>() { + let _ = F::all(); +} + +fn main() { + all_from_trait::<MyFlags>(); + let _ = MyFlags::all(); +} diff --git a/tests/compile-pass/flags_trait_supertrait.rs b/tests/compile-pass/flags_trait_supertrait.rs new file mode 100644 index 00000000..b4b9d6ca --- /dev/null +++ b/tests/compile-pass/flags_trait_supertrait.rs @@ -0,0 +1,80 @@ +#![allow(deprecated)] + +// From: https://github.com/bitflags/bitflags/issues/293#issuecomment-1493296383 +use core::{ + fmt::{Binary, LowerHex, Octal, UpperHex}, + ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, + } +}; + +use bitflags::{bitflags, Flags}; + +pub trait FlagsExt { + fn complement_retain(self) -> Self; + fn has_uncorresponding_bits(self) -> bool; +} +impl<T, U> FlagsExt for T +where + T: Flags<Bits = U> + + BitAnd<Output = T> + + BitAndAssign + + BitOr<Output = T> + + BitOrAssign + + BitXor<Output = T> + + BitXorAssign + + Not<Output = T> + + Sub<Output = T> + + SubAssign + + Extend<T> + + FromIterator<T> + + IntoIterator + + Binary + + LowerHex + + Octal + + UpperHex, + U: BitAnd<Output = U> + + BitAndAssign + + BitOr<Output = U> + + BitOrAssign + + BitXor<Output = U> + + BitXorAssign + + Not<Output = U> + + Shl<Output = U> + + ShlAssign + + Shr<Output = U> + + ShrAssign + + Add<Output = U> + + AddAssign + + Div<Output = U> + + DivAssign + + Mul<Output = U> + + MulAssign + + Rem<Output = U> + + RemAssign + + Sub<Output = U> + + SubAssign, +{ + fn complement_retain(self) -> Self { + Self::from_bits_retain(!self.bits()) + } + + fn has_uncorresponding_bits(self) -> bool { + !(self & Self::all().complement_retain()).is_empty() + } +} + +bitflags! { + struct MyFlags: u32 { + const A = 0b00000001; + } +} + +fn has_uncorresponding_bits<B: FlagsExt>(flags: B) -> bool { + flags.has_uncorresponding_bits() +} + +fn main() { + has_uncorresponding_bits(MyFlags::A); +} diff --git a/tests/compile-pass/impls/convert.rs b/tests/compile-pass/impl_convert_from_bits.rs similarity index 100% rename from tests/compile-pass/impls/convert.rs rename to tests/compile-pass/impl_convert_from_bits.rs diff --git a/tests/compile-pass/impls/copy.rs b/tests/compile-pass/impl_copy.rs similarity index 100% rename from tests/compile-pass/impls/copy.rs rename to tests/compile-pass/impl_copy.rs diff --git a/tests/compile-pass/impls/default.rs b/tests/compile-pass/impl_default.rs similarity index 100% rename from tests/compile-pass/impls/default.rs rename to tests/compile-pass/impl_default.rs diff --git a/tests/compile-pass/impls/eq.rs b/tests/compile-pass/impl_eq.rs similarity index 100% rename from tests/compile-pass/impls/eq.rs rename to tests/compile-pass/impl_eq.rs diff --git a/tests/compile-pass/impls/fmt.rs b/tests/compile-pass/impl_fmt.rs similarity index 100% rename from tests/compile-pass/impls/fmt.rs rename to tests/compile-pass/impl_fmt.rs diff --git a/tests/compile-pass/impls/inherent_methods.rs b/tests/compile-pass/impl_new.rs similarity index 100% rename from tests/compile-pass/impls/inherent_methods.rs rename to tests/compile-pass/impl_new.rs diff --git a/tests/compile-pass/trait/wrapped_iter.rs b/tests/compile-pass/into_iter_trait_wrapped.rs similarity index 100% rename from tests/compile-pass/trait/wrapped_iter.rs rename to tests/compile-pass/into_iter_trait_wrapped.rs diff --git a/tests/compile-pass/repr/c.rs b/tests/compile-pass/repr_c.rs similarity index 100% rename from tests/compile-pass/repr/c.rs rename to tests/compile-pass/repr_c.rs diff --git a/tests/compile-pass/repr/transparent.rs b/tests/compile-pass/repr_transparent.rs similarity index 100% rename from tests/compile-pass/repr/transparent.rs rename to tests/compile-pass/repr_transparent.rs diff --git a/tests/compile-pass/redefinition/core.rs b/tests/compile-pass/shadow_core.rs similarity index 100% rename from tests/compile-pass/redefinition/core.rs rename to tests/compile-pass/shadow_core.rs diff --git a/tests/compile-pass/redefinition/macros.rs b/tests/compile-pass/shadow_macros.rs similarity index 100% rename from tests/compile-pass/redefinition/macros.rs rename to tests/compile-pass/shadow_macros.rs diff --git a/tests/compile-pass/redefinition/result.rs b/tests/compile-pass/shadow_result.rs similarity index 100% rename from tests/compile-pass/redefinition/result.rs rename to tests/compile-pass/shadow_result.rs diff --git a/tests/compile-pass/visibility/bits_field.rs b/tests/compile-pass/visibility/bits_field.rs deleted file mode 100644 index 5b0c6e43..00000000 --- a/tests/compile-pass/visibility/bits_field.rs +++ /dev/null @@ -1,11 +0,0 @@ -use bitflags::bitflags; - -bitflags! { - pub struct Flags1: u32 { - const FLAG_A = 0b00000001; - } -} - -fn main() { - assert_eq!(0b00000001, Flags1::FLAG_A.bits()); -} diff --git a/tests/smoke-test/Cargo.toml b/tests/smoke-test/Cargo.toml index f7265667..2d64659c 100644 --- a/tests/smoke-test/Cargo.toml +++ b/tests/smoke-test/Cargo.toml @@ -6,3 +6,4 @@ publish = false [dependencies.bitflags] path = "../../" +all-features = true
Allow external impls of Bits and BitFlags The `BitFlags` trait is currently sealed, and is only supported through the `bitflags!` macro. I think we should make this trait publicly implementable, and default most of its members. I spent some time hacking on this, and came up with this minimal implementation. Given a flags type like: ```rust bitflags! { pub struct MyFlags: u32 { const A = 0b0000_0001; const B = 0b0000_0010; const C = 0b0000_0100; } }; ``` You can implement it manually with: ```rust pub struct MyFlags { bits: u32, } impl BitFlags for MyFlags { const FLAGS: &'static [(&'static str, Self::Bits)] = &[ ("A", 0b0000_0001), ("B", 0b0000_0010), ("C", 0b0000_0100), ]; type Bits = u32; type Iter = bitflags::iter::Iter<Self>; type IterNames = bitflags::iter::IterNames<Self>; fn bits(&self) -> Self::Bits { self.bits } fn from_bits_retain(bits: Self::Bits) -> Self { Self { bits } } fn iter(&self) -> Self::Iter { bitflags::iter::Iter::new(self) } fn iter_names(&self) -> Self::IterNames { bitflags::iter::IterNames::new(self) } } ``` I'm proposing we _don't_ do #293, so that the implementation of `BitFlags` doesn't call for a host of supertraits. The `FLAGS` constant there is new, and drives the iteration-based methods like `from_bits_truncate`, `from_name`, and the implementations of `Iter` and `IterNames`. If you squint, it looks a lot like the body of the `bitflags` macro. I think doing this has a few benefits: 1. It makes the trait "real", so you can implement it and work with it yourself. 2. It moves most of the generated code out of macros where they don't need to use fully-qualified paths like `$crate::__private::core::option::Option::Some<T>`. 3. It gives us a starting point for #347 and #339, where you might not be able to use the `bitflags!` macro, but with a small amount of effort, can cook up your own flags type with whatever shape you want, and still get the benefits of generated code. For trait impls like `serde` and `arbitrary`, we can then expose utilities like that proposed `bitflags::iter` module that make manual impls of those traits with awareness that the type is a flags enum easy: ```rust impl Serialize for MyFlags { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { bitflags::serde::serialize(self, serializer) } } ``` I'm keen to hear what people think of this.
As for `Bits`, it can be reasonably reduced to: ```rust pub trait Bits: Clone + Copy + BitAnd<Output = Self> + BitOr<Output = Self> + BitXor<Output = Self> + Not<Output = Self> + PartialEq + Sized + 'static { /// The value of `Self` where no bits are set. const EMPTY: Self; /// The value of `Self` where all bits are set. const ALL: Self; } ``` The `Copy` and `'static` bounds are pretty limiting, but doesn't rule out _some_ more exotic backing storage like `[bool; N]`. The main thing you don't get from just the `BitFlags` macro right now, and what stops us being able to immediately replace a lot of generated code with it, is the const definitions, and const versions of those trait functions. We could consider a few utility macros that we transition `bitflags!` to, that will define costs and impl operators for you: ```rust impl_consts! { MyFlags: u32 { const A = 0b0000_0001; const B = 0b0000_0010; const C = 0b0000_0100; } } ``` would generate: ```rust impl MyFlags { const FLAGS: &'static [(&'static str, Self::Bits)] = &[ ("A", 0b0000_0001), ("B", 0b0000_0010), ("C", 0b0000_0100), ]; pub const A: Self = Self::from_bits_retain(0b0000_0001); pub const B: Self = Self::from_bits_retain(0b0000_0010); pub const C: Self = Self::from_bits_retain(0b0000_0100); } ``` you could then use `Self::FLAGS` as the basis for the const in the `BitFlags` trait, so there's still only a single definition of what those flags are. Some other open design questions are: 1. Should we use slices like `&[(&str, T)]`, or some wrapper type, like `Flags` that also implements indexing. 2. Should we use tuples like `(&str, T)`, or some flags type like `Flag`. Having a separate type would let us add metadata in the future, such as whether or not the flag is a composite of other flags. I'm happy with `&[(&str, T)]`, but open to trying a more encapsulated API if it doesn't affect ergonomics or create too many extra types. It's certainly more future proof.
2023-05-04T06:16:51Z
2.2
bitflags/bitflags
345
bitflags__bitflags-345
[ "344" ]
cbcafa710fc31172511e62efa06ad9eb214e4734
diff --git a/src/example_generated.rs b/src/example_generated.rs index 9c1ba46a..b7589014 100644 --- 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 index 2a6590fe..eca0a304 100644 --- 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 } @@ -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] @@ -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 @@ -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) + } + ), )* ]; @@ -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 index afc5b524..18138bf5 100644 --- 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 @@ -879,7 +570,7 @@ macro_rules! __declare_bitflags { __impl_public_bitflags_consts! { $BitFlags { $( - $(#[$decl $($declargs)*])* + $(#[$inner $($args)*])* #[allow( dead_code, deprecated, @@ -912,7 +603,7 @@ macro_rules! __declare_bitflags { __impl_internal_bitflags! { InternalBitFlags: $T, $BitFlags, Iter, IterRaw { $( - $(#[$expr $($exprargs)*])* + $(#[$inner $($args)*])* $Flag; )* } @@ -922,7 +613,7 @@ macro_rules! __declare_bitflags { __impl_external_bitflags! { InternalBitFlags: $T { $( - $(#[$expr $($exprargs)*])* + $(#[$inner $($args)*])* $Flag; )* } @@ -932,7 +623,12 @@ macro_rules! __declare_bitflags { $BitFlags: $T, InternalBitFlags, Iter, IterRaw; } }; - } + + bitflags! { + $($t)* + } + }; + () => {}; } #[macro_use]
diff --git a/tests/compile-pass/large.rs b/tests/compile-pass/large.rs new file mode 100644 index 00000000..a7519f2a --- /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() { + +}
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.
2023-04-24T04:29:26Z
2.2
bitflags/bitflags
341
bitflags__bitflags-341
[ "308" ]
dc971042c8132a5381ab3e2165983ee7f9d44c63
diff --git a/src/lib.rs b/src/lib.rs index 7ba784c5..a4a40467 100644 --- 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 @@ -570,7 +879,7 @@ macro_rules! bitflags { __impl_public_bitflags_consts! { $BitFlags { $( - $(#[$inner $($args)*])* + $(#[$decl $($declargs)*])* #[allow( dead_code, deprecated, @@ -603,7 +912,7 @@ macro_rules! bitflags { __impl_internal_bitflags! { InternalBitFlags: $T, $BitFlags, Iter, IterRaw { $( - $(#[$inner $($args)*])* + $(#[$expr $($exprargs)*])* $Flag; )* } @@ -613,7 +922,7 @@ macro_rules! bitflags { __impl_external_bitflags! { InternalBitFlags: $T { $( - $(#[$inner $($args)*])* + $(#[$expr $($exprargs)*])* $Flag; )* } @@ -623,12 +932,7 @@ macro_rules! bitflags { $BitFlags: $T, InternalBitFlags, Iter, IterRaw; } }; - - bitflags! { - $($t)* - } - }; - () => {}; + } } #[macro_use]
diff --git a/tests/compile-pass/doc_alias.rs b/tests/compile-pass/doc_alias.rs new file mode 100644 index 00000000..8fe1d900 --- /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() { + +}
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.
2023-04-18T00:36:26Z
2.1
bitflags/bitflags
282
bitflags__bitflags-282
[ "228" ]
810dc35aba3df7314de01b93c7aa137968e925d4
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index b7b2486e..f00ed6c2 100644 --- 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/Cargo.toml b/Cargo.toml index 9c7c7aa7..0ff60e1d 100644 --- 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 index 440d5274..fd0a913a 100644 --- 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. @@ -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. @@ -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 @@ -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 index cf188d99..18985c75 100644 --- 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 index 979ff918..fefac414 100644 --- 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(); //! } //! } //! @@ -51,6 +52,7 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; @@ -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; //! } //! } //! @@ -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)"); //! } //! ``` //! @@ -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; @@ -123,6 +119,7 @@ //! //! bitflags! { //! #[repr(transparent)] +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; @@ -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 @@ -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 @@ -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; @@ -224,6 +216,7 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const A = 0b00000001; //! const B = 0b00000010; @@ -252,6 +245,7 @@ //! use bitflags::bitflags; //! //! bitflags! { +//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] //! struct Flags: u32 { //! const NONE = 0b00000000; //! const SOME = 0b00000001; @@ -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. @@ -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(); /// } /// } /// @@ -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; @@ -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; /// } /// } /// @@ -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)] @@ -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)*])* @@ -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)* } @@ -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) } } @@ -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, } } @@ -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 @@ -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 @@ -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`. @@ -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`. @@ -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 @@ -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. @@ -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) @@ -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; @@ -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; @@ -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"] @@ -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 { } } @@ -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()) ); } @@ -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()); @@ -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 @@ -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)); @@ -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); @@ -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; @@ -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, ); @@ -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, @@ -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"); } @@ -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"); } @@ -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"); } @@ -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; } @@ -1659,6 +1862,7 @@ mod tests { bitflags! { /// baz + #[derive(Clone, Copy)] struct Flags: foo::Bar { const A = 0b00000001; #[cfg(foo)] @@ -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; @@ -1696,6 +1902,7 @@ mod tests { fn test_pub_crate() { mod module { bitflags! { + #[derive(Clone, Copy)] pub (crate) struct Test: u8 { const FOO = 1; } @@ -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; } @@ -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; @@ -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] @@ -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; @@ -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; @@ -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 a/src/serde_support.rs b/src/serde_support.rs new file mode 100644 index 00000000..41cf1128 --- /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/basic.rs b/tests/basic.rs index 73a52bec..790ec41c 100644 --- 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 a/tests/compile-fail/impls/copy.stderr b/tests/compile-fail/impls/copy.stderr deleted file mode 100644 index 966f3c9a..00000000 --- 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 b/tests/compile-fail/impls/eq.stderr deleted file mode 100644 index cb1d6a08..00000000 --- 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 index 69d89dc5..e477281c 100644 --- 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 | @@ -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 @@ -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 @@ -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 @@ -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 index ee95f836..7f047c68 100644 --- 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 { @@ -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 a/tests/compile-fail/redefined.rs b/tests/compile-fail/redefined.rs new file mode 100644 index 00000000..6d194d6c --- /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 a/tests/compile-fail/redefined.stderr b/tests/compile-fail/redefined.stderr new file mode 100644 index 00000000..85bc7f10 --- /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 a/tests/compile-fail/syntax/missing_type.rs b/tests/compile-fail/syntax/missing_type.rs new file mode 100644 index 00000000..323b8583 --- /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 a/tests/compile-fail/syntax/missing_type.stderr b/tests/compile-fail/syntax/missing_type.stderr new file mode 100644 index 00000000..ed8c8ac4 --- /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 a/tests/compile-fail/syntax/missing_value.rs b/tests/compile-fail/syntax/missing_value.rs new file mode 100644 index 00000000..c1221035 --- /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 a/tests/compile-fail/syntax/missing_value.stderr b/tests/compile-fail/syntax/missing_value.stderr new file mode 100644 index 00000000..6b1b46a1 --- /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 index 80be2f91..55dd929d 100644 --- 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 b/tests/compile-fail/visibility/private_field.rs deleted file mode 100644 index a6a3912a..00000000 --- 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 b/tests/compile-fail/visibility/private_field.stderr deleted file mode 100644 index e1146989..00000000 --- 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 index 85a5b186..a132d2f9 100644 --- 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 index d23f8320..47a53c25 100644 --- 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-fail/impls/copy.rs b/tests/compile-pass/impls/copy.rs similarity index 100% rename from tests/compile-fail/impls/copy.rs rename to tests/compile-pass/impls/copy.rs diff --git a/tests/compile-fail/impls/eq.rs b/tests/compile-pass/impls/eq.rs similarity index 100% rename from tests/compile-fail/impls/eq.rs rename to tests/compile-pass/impls/eq.rs diff --git a/tests/compile-pass/impls/fmt.rs b/tests/compile-pass/impls/fmt.rs index 567fd448..93dbf1b1 100644 --- 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; } @@ -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 a/tests/compile-pass/item_positions.rs b/tests/compile-pass/item_positions.rs new file mode 100644 index 00000000..def7bbe3 --- /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 index c54b7a31..b1c57dac 100644 --- 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 index a9835124..cfff19ab 100644 --- 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; } @@ -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 index 33a7967e..5b0c6e43 100644 --- 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 a/tests/smoke-test/Cargo.toml b/tests/smoke-test/Cargo.toml new file mode 100644 index 00000000..f7265667 --- /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 = "../../" diff --git a/tests/smoke-test/src/main.rs b/tests/smoke-test/src/main.rs new file mode 100644 index 00000000..9ff4305d --- /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); +}
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.
2022-05-25T04:14:38Z
1.3
bitflags/bitflags
281
bitflags__bitflags-281
[ "215" ]
f38ce72d11ef3e264d4b62f360bd8a5597b916d9
diff --git a/src/bitflags_trait.rs b/src/bitflags_trait.rs index 0ffee465..440d5274 100644 --- 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 {} @@ -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. @@ -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; @@ -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 index a2d3193b..979ff918 100644 --- 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. @@ -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 { @@ -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(" | ")?; } @@ -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)*])* @@ -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. @@ -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 } @@ -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 @@ -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; @@ -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)*])* @@ -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)) } @@ -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] @@ -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)"); @@ -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); } @@ -1854,7 +1828,6 @@ mod tests { } } - let flags = Flags::from_bits(0b00000100); assert_eq!(flags, None); let flags = Flags::from_bits(0b00000101); @@ -1875,7 +1848,7 @@ mod tests { let flags = Flags::from_bits_truncate(0b00000101); assert_eq!(flags, Flags::A); } - + #[test] fn test_iter() { bitflags! { @@ -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)); @@ -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(); @@ -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);
diff --git a/tests/compile-fail/cfg/multi.stderr b/tests/compile-fail/cfg/multi.stderr deleted file mode 100644 index be9ba21c..00000000 --- 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 index fb9c2867..69d89dc5 100644 --- 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! { @@ -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! { @@ -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! { @@ -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! { @@ -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 index 7f3b4b1e..d7e8d494 100644 --- 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 similarity index 70% rename from tests/compile-fail/cfg/multi.rs rename to tests/compile-pass/cfg/redefined-value.rs index 461db914..6bb2b651 100644 --- 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; } @@ -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 a/tests/compile-pass/deprecated.rs b/tests/compile-pass/deprecated.rs new file mode 100644 index 00000000..167ce44c --- /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 a/tests/compile-pass/non_snake_case.rs b/tests/compile-pass/non_snake_case.rs new file mode 100644 index 00000000..5a3b8103 --- /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() {}
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.
2022-05-03T06:59:46Z
1.3
bitflags/bitflags
276
bitflags__bitflags-276
[ "275" ]
0141a07e55184304857384b0093d00959f0acfa6
diff --git a/src/lib.rs b/src/lib.rs index ab7656e7..b9d77f7c 100644 --- 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 } } @@ -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 @@ -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! { @@ -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 index 6fada425..0607f234 100644 --- 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
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.
2022-04-19T09:54:30Z
1.3
bitflags/bitflags
268
bitflags__bitflags-268
[ "267" ]
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
diff --git a/src/lib.rs b/src/lib.rs index 617afea0..b24fb40b 100644 --- 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)")?;
diff --git a/tests/compile-fail/trait/custom_impl.rs b/tests/compile-fail/trait/custom_impl.rs index 66875898..80be2f91 100644 --- 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 index 1f02982a..393ed8f8 100644 --- 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 a/tests/compile-pass/impls/fmt.rs b/tests/compile-pass/impls/fmt.rs new file mode 100644 index 00000000..567fd448 --- /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 similarity index 52% rename from tests/compile-pass/redefinition/stringify.rs rename to tests/compile-pass/redefinition/macros.rs index b04f2f6a..a9835124 100644 --- 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; @@ -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"); }
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
2022-01-02T17:22:14Z
1.3
bitflags/bitflags
266
bitflags__bitflags-266
[ "265" ]
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
diff --git a/src/lib.rs b/src/lib.rs index 617afea0..a4ca8429 100644 --- 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 {
diff --git a/tests/compile-pass/redefinition/result.rs b/tests/compile-pass/redefinition/result.rs new file mode 100644 index 00000000..fe915d47 --- /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() {}
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(())`.
2021-12-16T09:38:14Z
1.3
bitflags/bitflags
199
bitflags__bitflags-199
[ "193" ]
dca4928b1a345b1c8b16edaf205b0f68cffd20d1
diff --git a/.travis.yml b/.travis.yml index 9dd45c47..79fdda26 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,7 @@ matrix: - LABEL="compiletest" script: - cargo test - - cargo test -p test_suite --features unstable + - cargo test -p test_suite - rust: stable - rust: stable os: osx
diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.toml index 2a02d80d..057a022c 100644 --- a/test_suite/Cargo.toml +++ b/test_suite/Cargo.toml @@ -2,12 +2,9 @@ name = "test_suite" version = "0.0.0" -[features] -unstable = ["compiletest_rs"] - [dependencies] bitflags = { path = "../" } -compiletest_rs = { version = "0.3.18", optional = true, features=["stable"] } +trybuild = "1.0" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" diff --git a/test_suite/tests/compile-fail/private_flags.rs b/test_suite/tests/compile-fail/private_flags.rs index d31c28d8..35089bc0 100644 --- a/test_suite/tests/compile-fail/private_flags.rs +++ b/test_suite/tests/compile-fail/private_flags.rs @@ -16,5 +16,5 @@ mod example { fn main() { let flag1 = example::Flags1::FLAG_A; - let flag2 = example::Flags2::FLAG_B; //~ ERROR struct `Flags2` is private + let flag2 = example::Flags2::FLAG_B; } diff --git a/test_suite/tests/compile-fail/private_flags.stderr b/test_suite/tests/compile-fail/private_flags.stderr new file mode 100644 index 00000000..63748191 --- /dev/null +++ b/test_suite/tests/compile-fail/private_flags.stderr @@ -0,0 +1,5 @@ +error[E0603]: struct `Flags2` is private + --> $DIR/private_flags.rs:19:26 + | +19 | let flag2 = example::Flags2::FLAG_B; + | ^^^^^^ diff --git a/test_suite/tests/compiletest.rs b/test_suite/tests/compiletest.rs index 2beeae01..db50dfda 100644 --- a/test_suite/tests/compiletest.rs +++ b/test_suite/tests/compiletest.rs @@ -1,33 +1,5 @@ -#![cfg(feature = "unstable")] - -extern crate compiletest_rs as compiletest; - -use std::fs; -use std::result::Result; - -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); +fn compile_fail() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/compile-fail/*.rs"); }
Ensure compile tests are running In #192 I tweaked our config to work around a build error in `compiletest_rs` (there's an open PR https://github.com/laumann/compiletest-rs/pull/187 that should fix it up). We could also consider migrating to something like [`libtest_mimic`](https://crates.io/crates/libtest-mimic), which is used in [`auto-impl`](https://github.com/auto-impl-rs/auto_impl).
We could also look at `trybuild` for this, which is nice and modern.
2019-11-01T08:52:06Z
1.2
bitflags/bitflags
127
bitflags__bitflags-127
[ "68" ]
862582d107bb74ce4c7b505b2490eb815bc3a8c2
diff --git a/.gitignore b/.gitignore index 4fffb2f8..a9d37c56 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -/target -/Cargo.lock +target +Cargo.lock diff --git a/.travis.yml b/.travis.yml index 5ada0712..d0de6756 100644 --- 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 @@ -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/Cargo.toml b/Cargo.toml index 750242aa..e29eeea1 100644 --- 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 b/compiletest/Cargo.toml deleted file mode 100644 index d0718acd..00000000 --- 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" } diff --git a/compiletest/tests/tests.rs b/compiletest/tests/tests.rs deleted file mode 100644 index 5826985c..00000000 --- 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 a/test_suite/Cargo.toml b/test_suite/Cargo.toml new file mode 100644 index 00000000..b084b8cf --- /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 a/compiletest/tests/compile-fail/private_flags.rs b/test_suite/tests/compile-fail/private_flags.rs similarity index 100% rename from compiletest/tests/compile-fail/private_flags.rs rename to test_suite/tests/compile-fail/private_flags.rs diff --git a/test_suite/tests/compiletest.rs b/test_suite/tests/compiletest.rs new file mode 100644 index 00000000..8825fc54 --- /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/conflicting_trait_impls.rs b/test_suite/tests/conflicting_trait_impls.rs similarity index 100% rename from tests/conflicting_trait_impls.rs rename to test_suite/tests/conflicting_trait_impls.rs diff --git a/tests/external.rs b/test_suite/tests/external.rs similarity index 100% rename from tests/external.rs rename to test_suite/tests/external.rs diff --git a/tests/external_no_std.rs b/test_suite/tests/external_no_std.rs similarity index 100% rename from tests/external_no_std.rs rename to test_suite/tests/external_no_std.rs diff --git a/tests/i128_bitflags.rs b/test_suite/tests/i128_bitflags.rs similarity index 96% rename from tests/i128_bitflags.rs rename to test_suite/tests/i128_bitflags.rs index 47bd06bf..737bc314 100644 --- 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)] diff --git a/tests/serde.rs b/test_suite/tests/serde.rs similarity index 100% rename from tests/serde.rs rename to test_suite/tests/serde.rs
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.
2017-10-17T16:27:59Z
1.0
bitflags/bitflags
125
bitflags__bitflags-125
[ "108" ]
29e60b23708123121a540fa9bde3254260952511
diff --git a/Cargo.toml b/Cargo.toml index 2686b9d2..750242aa 100644 --- 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]
diff --git a/tests/serde.rs b/tests/serde.rs new file mode 100644 index 00000000..0424af5f --- /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); +}
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.
2017-10-11T15:27:55Z
1.0
bitflags/bitflags
87
bitflags__bitflags-87
[ "65" ]
f02742c76022f4e19a461e8c05cec7f28aac1049
diff --git a/src/lib.rs b/src/lib.rs index f9c02ecb..2c76e198 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,12 +36,12 @@ pub use core as __core; /// /// bitflags! { /// struct Flags: u32 { -/// const FLAG_A = 0b00000001, -/// const FLAG_B = 0b00000010, -/// const FLAG_C = 0b00000100, +/// const FLAG_A = 0b00000001; +/// const FLAG_B = 0b00000010; +/// const FLAG_C = 0b00000100; /// const FLAG_ABC = FLAG_A.bits /// | FLAG_B.bits -/// | FLAG_C.bits, +/// | FLAG_C.bits; /// } /// } /// @@ -66,8 +66,8 @@ pub use core as __core; /// /// bitflags! { /// struct Flags: u32 { -/// const FLAG_A = 0b00000001, -/// const FLAG_B = 0b00000010, +/// const FLAG_A = 0b00000001; +/// const FLAG_B = 0b00000010; /// } /// } /// @@ -107,12 +107,12 @@ pub use core as __core; /// mod example { /// bitflags! { /// pub struct Flags1: u32 { -/// const FLAG_A = 0b00000001, +/// const FLAG_A = 0b00000001; /// } /// } /// bitflags! { /// struct Flags2: u32 { -/// const FLAG_B = 0b00000010, +/// const FLAG_B = 0b00000010; /// } /// } /// } @@ -177,7 +177,7 @@ pub use core as __core; #[macro_export] macro_rules! bitflags { ($(#[$attr:meta])* pub struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ }) => { #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] $(#[$attr])* @@ -189,12 +189,12 @@ macro_rules! bitflags { bitflags! { @_impl struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value),+ + $($(#[$Flag_attr])* const $Flag = $value;)+ } } }; ($(#[$attr:meta])* struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ }) => { #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] $(#[$attr])* @@ -206,12 +206,13 @@ macro_rules! bitflags { bitflags! { @_impl struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value),+ + $($(#[$Flag_attr])* const $Flag = $value;)+ } } + }; (@_impl struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+ + $($(#[$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 { @@ -484,26 +485,6 @@ macro_rules! bitflags { } } }; - ($(#[$attr:meta])* pub struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+, - }) => { - bitflags! { - $(#[$attr])* - pub struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value),+ - } - } - }; - ($(#[$attr:meta])* struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+, - }) => { - bitflags! { - $(#[$attr])* - struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value),+ - } - } - }; } #[cfg(test)] @@ -518,39 +499,39 @@ mod tests { #[doc = "> "] #[doc = "> - Richard Feynman"] struct Flags: u32 { - const FlagA = 0b00000001, + const FlagA = 0b00000001; #[doc = "<pcwalton> macros are way better at generating code than trans is"] - const FlagB = 0b00000010, - const FlagC = 0b00000100, + const FlagB = 0b00000010; + const FlagC = 0b00000100; #[doc = "* cmr bed"] #[doc = "* strcat table"] #[doc = "<strcat> wait what?"] const FlagABC = FlagA.bits | FlagB.bits - | FlagC.bits, + | FlagC.bits; } } bitflags! { struct _CfgFlags: u32 { #[cfg(windows)] - const _CfgA = 0b01, + const _CfgA = 0b01; #[cfg(unix)] - const _CfgB = 0b01, + const _CfgB = 0b01; #[cfg(windows)] - const _CfgC = _CfgA.bits | 0b10, + const _CfgC = _CfgA.bits | 0b10; } } bitflags! { struct AnotherSetOfFlags: i8 { - const AnotherFlag = -1_i8, + const AnotherFlag = -1_i8; } } bitflags! { struct LongFlags: u32 { - const LongFlagA = 0b1111111111111111, + const LongFlagA = 0b1111111111111111; } } @@ -821,12 +802,12 @@ mod tests { mod submodule { bitflags! { pub struct PublicFlags: i8 { - const FlagX = 0, + const FlagX = 0; } } bitflags! { struct PrivateFlags: i8 { - const FlagY = 0, + const FlagY = 0; } } @@ -849,11 +830,11 @@ mod tests { bitflags! { /// baz struct Flags: foo::Bar { - const A = 0b00000001, + const A = 0b00000001; #[cfg(foo)] - const B = 0b00000010, + const B = 0b00000010; #[cfg(foo)] - const C = 0b00000010, + const C = 0b00000010; } } } @@ -861,10 +842,10 @@ mod tests { #[test] fn test_in_function() { bitflags! { - struct Flags: u8 { - const A = 1, + struct Flags: u8 { + const A = 1; #[cfg(any())] // false - const B = 2, + const B = 2; } } assert_eq!(Flags::all(), A);
diff --git a/tests/external.rs b/tests/external.rs index e92b475b..fc1c3467 100644 --- a/tests/external.rs +++ b/tests/external.rs @@ -6,12 +6,12 @@ extern crate bitflags; bitflags! { /// baz struct Flags: u32 { - const A = 0b00000001, + const A = 0b00000001; #[doc = "bar"] - const B = 0b00000010, - const C = 0b00000100, + const B = 0b00000010; + const C = 0b00000100; #[doc = "foo"] - const ABC = A.bits | B.bits | C.bits, + const ABC = A.bits | B.bits | C.bits; } } diff --git a/tests/external_no_std.rs b/tests/external_no_std.rs index 11643e15..8b8c7067 100644 --- a/tests/external_no_std.rs +++ b/tests/external_no_std.rs @@ -7,12 +7,12 @@ extern crate bitflags; bitflags! { /// baz struct Flags: u32 { - const A = 0b00000001, + const A = 0b00000001; #[doc = "bar"] - const B = 0b00000010, - const C = 0b00000100, + const B = 0b00000010; + const C = 0b00000100; #[doc = "foo"] - const ABC = A.bits | B.bits | C.bits, + const ABC = A.bits | B.bits | C.bits; } } diff --git a/tests/i128_bitflags.rs b/tests/i128_bitflags.rs index f0ca5e9c..acbb9278 100644 --- a/tests/i128_bitflags.rs +++ b/tests/i128_bitflags.rs @@ -9,10 +9,10 @@ extern crate bitflags; bitflags! { /// baz struct Flags128: 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 = A.bits | B.bits | C.bits, + 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; } }
Semicolons It may be too late for such a change to make sense but typically "const" items are followed by a semicolon, not comma. Semicolon would be more consistent with lazy_static as well. ```rust bitflags! { flags Flags: u32 { const A = 0b00000001; const B = 0b00000010; } } const C: u32 = 0b00000100; const D: u32 = 0b00001000; lazy_static! { static ref E: u32 = 0b00010000; static ref F: u32 = 0b00100000; } ```
2017-03-22T16:19:50Z
0.8
bitflags/bitflags
24
bitflags__bitflags-24
[ "20", "21" ]
d0884fa853eadd800fef198d9e71c8758b292db5
diff --git a/src/example_generated.rs b/src/example_generated.rs index 05b99e8f..ee5b59b1 100644 --- 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 index 8d4f704b..9c6c5ac4 100644 --- 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 //! } //! ``` //! @@ -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"); //! } //! ``` //! @@ -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 //! } //! ``` //! @@ -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)); //! } //! ``` @@ -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 /// } /// ``` /// @@ -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] @@ -320,11 +320,6 @@ macro_rules! bitflags { bits: $T, } - $( - $(#[$inner $($args)*])* - pub const $Flag: $BitFlags = $BitFlags { bits: $value }; - )+ - __impl_bitflags! { struct $BitFlags: $T { $( @@ -349,11 +344,6 @@ macro_rules! bitflags { bits: $T, } - $( - $(#[$inner $($args)*])* - const $Flag: $BitFlags = $BitFlags { bits: $value }; - )+ - __impl_bitflags! { struct $BitFlags: $T { $( @@ -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 } } )+ @@ -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 { @@ -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 } } )+ } @@ -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; @@ -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()); } @@ -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] @@ -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()); @@ -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()); @@ -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] @@ -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); } @@ -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); } @@ -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 { @@ -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]
diff --git a/tests/conflicting_trait_impls.rs b/tests/conflicting_trait_impls.rs index 4704dfaa..933e31c9 100644 --- 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 index fc1c3467..b3937782 100644 --- a/tests/external.rs +++ b/tests/external.rs @@ -1,5 +1,3 @@ -#![allow(dead_code)] - #[macro_use] extern crate bitflags; @@ -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 index 8b8c7067..7c5c9e0d 100644 --- a/tests/external_no_std.rs +++ b/tests/external_no_std.rs @@ -1,4 +1,3 @@ -#![allow(dead_code)] #![no_std] #[macro_use] @@ -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 index acbb9278..47bd06bf 100644 --- 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] @@ -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"); }
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?
2015-11-28T01:15:59Z
0.9