repo
stringclasses 1
value | pull_number
int64 266
411
| instance_id
stringclasses 8
values | issue_numbers
listlengths 1
1
| base_commit
stringclasses 7
values | patch
stringclasses 8
values | test_patch
stringclasses 8
values | problem_statement
stringclasses 8
values | hints_text
stringclasses 6
values | created_at
stringclasses 8
values | version
stringclasses 5
values | FAIL_TO_PASS
listlengths 1
6
| PASS_TO_PASS
listlengths 57
81
| FAIL_TO_FAIL
listlengths 0
0
| PASS_TO_FAIL
listlengths 0
0
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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
|
[
"tests/compile-pass/bitflags_impl_attrs.rs"
] |
[
"tests::complement::cases",
"tests::bits::cases",
"tests::all::cases",
"tests::contains::cases",
"tests::difference::cases",
"tests::empty::cases",
"tests::eq::cases",
"tests::extend::cases",
"tests::extend::external::cases",
"tests::flags::external::cases",
"tests::from_bits::cases",
"tests::flags::cases",
"tests::from_bits_retain::cases",
"tests::from_name::cases",
"tests::intersection::cases",
"tests::insert::cases",
"tests::intersects::cases",
"tests::is_all::cases",
"tests::is_empty::cases",
"tests::iter::collect::cases",
"tests::iter::iter::cases",
"tests::iter::iter_names::cases",
"tests::parser::from_str::invalid",
"tests::from_bits_truncate::cases",
"tests::parser::from_str::valid",
"tests::parser::from_str_strict::invalid",
"tests::parser::from_str_truncate::valid",
"tests::parser::from_str_strict::valid",
"tests::parser::to_writer_truncate::cases",
"tests::remove::cases",
"tests::parser::to_writer_strict::cases",
"tests::union::cases",
"tests::symmetric_difference::cases",
"tests::fmt::cases",
"tests::parser::to_writer::cases",
"tests::iter::roundtrip",
"tests::parser::roundtrip_truncate",
"tests::parser::roundtrip",
"tests::parser::roundtrip_strict",
"tests/compile-pass/bitflags_impl_repr_packed.rs",
"tests/compile-pass/bitflags_nested_value.rs",
"tests/compile-pass/bitflags_redefined_value.rs",
"tests/compile-pass/bitflags_self_in_value.rs",
"tests/compile-pass/bitflags_trait_bound_flags.rs",
"tests/compile-pass/bitflags_trait_generic_iter.rs",
"tests/compile-pass/bitflags_trait_precedence.rs",
"tests/compile-pass/bitflags_trait_supertrait.rs",
"tests/compile-pass/bitflags_trait_to_flags.rs",
"tests/compile-pass/bitflags_visibility.rs",
"tests/compile-pass/deprecated.rs",
"tests/compile-pass/doc_alias.rs",
"tests/compile-pass/flags_trait_bound_bitflags.rs",
"tests/compile-pass/flags_trait_generic_iter.rs",
"tests/compile-pass/flags_trait_precedence.rs",
"tests/compile-pass/flags_trait_supertrait.rs",
"tests/compile-pass/impl_convert_from_bits.rs",
"tests/compile-pass/impl_copy.rs",
"tests/compile-pass/impl_default.rs",
"tests/compile-pass/impl_eq.rs",
"tests/compile-pass/impl_fmt.rs",
"tests/compile-pass/impl_new.rs",
"tests/compile-pass/into_iter_trait_wrapped.rs",
"tests/compile-pass/item_positions.rs",
"tests/compile-pass/large.rs",
"tests/compile-pass/missing_docs.rs",
"tests/compile-pass/no_prelude.rs",
"tests/compile-pass/non_snake_case.rs",
"tests/compile-pass/parser_strict_non_hex_bits.rs",
"tests/compile-pass/path_based_bits.rs",
"tests/compile-pass/repr_c.rs",
"tests/compile-pass/repr_transparent.rs",
"tests/compile-pass/shadow_core.rs",
"tests/compile-pass/shadow_macros.rs",
"tests/compile-pass/shadow_result.rs",
"tests/compile-pass/unnamed.rs"
] |
[] |
[] |
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
|
[
"tests/compile-pass/bitflags_self_in_value.rs"
] |
[
"tests::bits_types",
"tests::into_iter_from_iter_roundtrip",
"tests::submodule::test_private",
"tests::test_assignment_operators",
"tests::test_binary",
"tests::test_bits",
"tests::test_const_fn",
"tests::test_contains",
"tests::test_debug",
"tests::test_deprecated",
"tests::test_display_from_str_roundtrip",
"tests::test_empty_does_not_intersect_with_full",
"tests::test_empty_bitflags",
"tests::test_default",
"tests::test_from_bits_retain",
"tests::test_from_bits_truncate",
"tests::test_from_bits_truncate_edge_cases",
"tests::test_from_iterator",
"tests::test_from_name",
"tests::test_from_str_err",
"tests::test_hash",
"tests::test_in_function",
"tests::test_insert",
"tests::test_is_all",
"tests::test_is_empty",
"tests::test_extend",
"tests::test_from_bits_edge_cases",
"tests::test_iter",
"tests::test_from_bits",
"tests::test_lt",
"tests::test_lowerhex",
"tests::test_octal",
"tests::test_disjoint_intersects",
"tests::test_operators",
"tests::test_ord",
"tests::test_overlapping_intersects",
"tests::test_pub_crate",
"tests::test_pub_in_module",
"tests::test_public",
"tests::test_set",
"tests::test_remove",
"tests::test_set_ops_basic",
"tests::test_operators_unchecked",
"tests::test_set_ops_const",
"tests::test_upperhex",
"tests::test_u128_bitflags",
"tests::test_zero_value_flags",
"tests::test_set_ops_unchecked",
"tests::test_two_empties_do_not_intersect",
"tests::test_set_ops_exhaustive",
"basic",
"tests/compile-pass/bitflags_nested_value.rs",
"tests/compile-pass/bitflags_redefined_value.rs",
"tests/compile-pass/bitflags_trait_bound_flags.rs",
"tests/compile-pass/bitflags_trait_generic_iter.rs",
"tests/compile-pass/bitflags_trait_precedence.rs",
"tests/compile-pass/bitflags_trait_supertrait.rs",
"tests/compile-pass/bitflags_trait_to_flags.rs",
"tests/compile-pass/bitflags_visibility.rs",
"tests/compile-pass/deprecated.rs",
"tests/compile-pass/doc_alias.rs",
"tests/compile-pass/flags_trait_bound_bitflags.rs",
"tests/compile-pass/flags_trait_generic_iter.rs",
"tests/compile-pass/flags_trait_precedence.rs",
"tests/compile-pass/flags_trait_supertrait.rs",
"tests/compile-pass/impl_convert_from_bits.rs",
"tests/compile-pass/impl_copy.rs",
"tests/compile-pass/impl_default.rs",
"tests/compile-pass/impl_eq.rs",
"tests/compile-pass/impl_fmt.rs",
"tests/compile-pass/impl_new.rs",
"tests/compile-pass/into_iter_trait_wrapped.rs",
"tests/compile-pass/item_positions.rs",
"tests/compile-pass/large.rs",
"tests/compile-pass/no_prelude.rs",
"tests/compile-pass/non_snake_case.rs",
"tests/compile-pass/path_based_bits.rs",
"tests/compile-pass/repr_c.rs",
"tests/compile-pass/repr_transparent.rs",
"tests/compile-pass/shadow_core.rs",
"tests/compile-pass/shadow_macros.rs"
] |
[] |
[] |
|
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
|
[
"tests/compile-pass/bitflags_trait_bound_flags.rs",
"tests/compile-pass/bitflags_trait_to_flags.rs",
"tests/compile-pass/flags_trait_bound_bitflags.rs",
"tests/compile-pass/flags_trait_generic_iter.rs",
"tests/compile-pass/flags_trait_precedence.rs",
"tests/compile-pass/flags_trait_supertrait.rs"
] |
[
"tests::bits_types",
"tests::submodule::test_private",
"tests::test_assignment_operators",
"tests::test_binary",
"tests::into_iter_from_iter_roundtrip",
"tests::test_bits",
"tests::test_const_fn",
"tests::test_contains",
"tests::test_debug",
"tests::test_default",
"tests::test_deprecated",
"tests::test_disjoint_intersects",
"tests::test_extend",
"tests::test_from_bits",
"tests::test_from_bits_edge_cases",
"tests::test_from_bits_retain",
"tests::test_from_bits_truncate",
"tests::test_from_bits_truncate_edge_cases",
"tests::test_from_name",
"tests::test_from_iterator",
"tests::test_from_str_err",
"tests::test_hash",
"tests::test_in_function",
"tests::test_insert",
"tests::test_iter",
"tests::test_is_empty",
"tests::test_empty_does_not_intersect_with_full",
"tests::test_empty_bitflags",
"tests::test_display_from_str_roundtrip",
"tests::test_lowerhex",
"tests::test_octal",
"tests::test_lt",
"tests::test_is_all",
"tests::test_operators",
"tests::test_ord",
"tests::test_overlapping_intersects",
"tests::test_pub_crate",
"tests::test_remove",
"tests::test_set_ops_basic",
"tests::test_set_ops_const",
"tests::test_two_empties_do_not_intersect",
"tests::test_operators_unchecked",
"tests::test_set",
"tests::test_public",
"tests::test_pub_in_module",
"tests::test_upperhex",
"tests::test_zero_value_flags",
"tests::test_set_ops_unchecked",
"tests::test_u128_bitflags",
"tests::test_set_ops_exhaustive",
"basic",
"tests/compile-pass/bitflags_nested_value.rs",
"tests/compile-pass/bitflags_redefined_value.rs",
"tests/compile-pass/bitflags_trait_generic_iter.rs",
"tests/compile-pass/bitflags_trait_precedence.rs",
"tests/compile-pass/bitflags_trait_supertrait.rs",
"tests/compile-pass/bitflags_visibility.rs",
"tests/compile-pass/deprecated.rs",
"tests/compile-pass/doc_alias.rs",
"tests/compile-pass/impl_convert_from_bits.rs",
"tests/compile-pass/impl_copy.rs",
"tests/compile-pass/impl_default.rs",
"tests/compile-pass/impl_eq.rs",
"tests/compile-pass/impl_fmt.rs",
"tests/compile-pass/impl_new.rs",
"tests/compile-pass/into_iter_trait_wrapped.rs",
"tests/compile-pass/item_positions.rs",
"tests/compile-pass/large.rs",
"tests/compile-pass/no_prelude.rs",
"tests/compile-pass/non_snake_case.rs",
"tests/compile-pass/path_based_bits.rs",
"tests/compile-pass/repr_c.rs",
"tests/compile-pass/repr_transparent.rs",
"tests/compile-pass/shadow_core.rs",
"tests/compile-pass/shadow_macros.rs",
"tests/compile-pass/shadow_result.rs"
] |
[] |
[] |
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
|
[
"tests/compile-pass/large.rs"
] |
[
"tests::bits_types",
"tests::into_iter_from_iter_roundtrip",
"tests::submodule::test_private",
"tests::test_assignment_operators",
"tests::test_binary",
"tests::test_bits",
"tests::test_const_fn",
"tests::test_contains",
"tests::test_debug",
"tests::test_default",
"tests::test_disjoint_intersects",
"tests::test_empty_bitflags",
"tests::test_empty_does_not_intersect_with_full",
"tests::test_extend",
"tests::test_from_bits",
"tests::test_display_from_str_roundtrip",
"tests::test_deprecated",
"tests::test_from_bits_edge_cases",
"tests::test_from_bits_truncate_edge_cases",
"tests::test_from_bits_truncate",
"tests::test_from_bits_retain",
"tests::test_from_str_err",
"tests::test_in_function",
"tests::test_hash",
"tests::test_insert",
"tests::test_from_name",
"tests::test_is_empty",
"tests::test_iter",
"tests::test_from_iterator",
"tests::test_octal",
"tests::test_is_all",
"tests::test_lt",
"tests::test_operators_unchecked",
"tests::test_overlapping_intersects",
"tests::test_lowerhex",
"tests::test_operators",
"tests::test_pub_crate",
"tests::test_pub_in_module",
"tests::test_ord",
"tests::test_public",
"tests::test_remove",
"tests::test_set_ops_const",
"tests::test_set",
"tests::test_set_ops_basic",
"tests::test_two_empties_do_not_intersect",
"tests::test_u128_bitflags",
"tests::test_upperhex",
"tests::test_set_ops_unchecked",
"tests::test_zero_value_flags",
"tests::test_set_ops_exhaustive",
"basic",
"tests/compile-pass/cfg/nested-value.rs",
"tests/compile-pass/cfg/redefined-value.rs",
"tests/compile-pass/deprecated.rs",
"tests/compile-pass/doc_alias.rs",
"tests/compile-pass/impls/convert.rs",
"tests/compile-pass/impls/copy.rs",
"tests/compile-pass/impls/default.rs",
"tests/compile-pass/impls/eq.rs",
"tests/compile-pass/impls/fmt.rs",
"tests/compile-pass/impls/inherent_methods.rs",
"tests/compile-pass/item_positions.rs",
"tests/compile-pass/no_prelude.rs",
"tests/compile-pass/non_snake_case.rs",
"tests/compile-pass/path_based_bits.rs",
"tests/compile-pass/redefinition/core.rs",
"tests/compile-pass/redefinition/macros.rs",
"tests/compile-pass/redefinition/result.rs",
"tests/compile-pass/repr/c.rs",
"tests/compile-pass/repr/transparent.rs",
"tests/compile-pass/trait/generic_iter.rs",
"tests/compile-pass/trait/precedence.rs",
"tests/compile-pass/trait/wrapped_iter.rs",
"tests/compile-pass/visibility/bits_field.rs",
"tests/compile-pass/visibility/pub_in.rs"
] |
[] |
[] |
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
|
[
"tests/compile-pass/doc_alias.rs"
] |
[
"tests::bits_types",
"tests::into_iter_from_iter_roundtrip",
"tests::submodule::test_private",
"tests::test_assignment_operators",
"tests::test_bits",
"tests::test_binary",
"tests::test_const_fn",
"tests::test_contains",
"tests::test_debug",
"tests::test_default",
"tests::test_deprecated",
"tests::test_disjoint_intersects",
"tests::test_display_from_str_roundtrip",
"tests::test_empty_does_not_intersect_with_full",
"tests::test_from_bits",
"tests::test_extend",
"tests::test_empty_bitflags",
"tests::test_from_bits_edge_cases",
"tests::test_from_bits_truncate_edge_cases",
"tests::test_from_bits_retain",
"tests::test_from_bits_truncate",
"tests::test_from_name",
"tests::test_from_iterator",
"tests::test_from_str_err",
"tests::test_hash",
"tests::test_in_function",
"tests::test_insert",
"tests::test_is_all",
"tests::test_is_empty",
"tests::test_lowerhex",
"tests::test_iter",
"tests::test_lt",
"tests::test_octal",
"tests::test_operators",
"tests::test_operators_unchecked",
"tests::test_ord",
"tests::test_overlapping_intersects",
"tests::test_pub_crate",
"tests::test_pub_in_module",
"tests::test_public",
"tests::test_remove",
"tests::test_set",
"tests::test_set_ops_basic",
"tests::test_set_ops_const",
"tests::test_set_ops_unchecked",
"tests::test_two_empties_do_not_intersect",
"tests::test_u128_bitflags",
"tests::test_upperhex",
"tests::test_zero_value_flags",
"tests::test_set_ops_exhaustive",
"basic",
"tests/compile-pass/cfg/nested-value.rs",
"tests/compile-pass/cfg/redefined-value.rs",
"tests/compile-pass/deprecated.rs",
"tests/compile-pass/impls/convert.rs",
"tests/compile-pass/impls/copy.rs",
"tests/compile-pass/impls/default.rs",
"tests/compile-pass/impls/eq.rs",
"tests/compile-pass/impls/fmt.rs",
"tests/compile-pass/impls/inherent_methods.rs",
"tests/compile-pass/item_positions.rs",
"tests/compile-pass/no_prelude.rs",
"tests/compile-pass/non_snake_case.rs",
"tests/compile-pass/path_based_bits.rs",
"tests/compile-pass/redefinition/core.rs",
"tests/compile-pass/redefinition/macros.rs",
"tests/compile-pass/redefinition/result.rs",
"tests/compile-pass/repr/c.rs",
"tests/compile-pass/repr/transparent.rs",
"tests/compile-pass/trait/generic_iter.rs",
"tests/compile-pass/trait/precedence.rs",
"tests/compile-pass/trait/wrapped_iter.rs",
"tests/compile-pass/visibility/bits_field.rs",
"tests/compile-pass/visibility/pub_in.rs"
] |
[] |
[] |
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
|
[
"tests/compile-pass/cfg/redefined-value.rs",
"tests/compile-pass/deprecated.rs",
"tests/compile-pass/non_snake_case.rs"
] |
[
"tests::test_assignment_operators",
"tests::submodule::test_private",
"tests::test_binary",
"tests::test_bits",
"tests::test_const_fn",
"tests::test_contains",
"tests::test_debug",
"tests::test_default",
"tests::test_deprecated",
"tests::test_disjoint_intersects",
"tests::test_empty_bitflags",
"tests::test_empty_does_not_intersect_with_full",
"tests::test_extend",
"tests::test_from_bits",
"tests::test_from_bits_edge_cases",
"tests::test_from_bits_truncate",
"tests::test_from_bits_truncate_edge_cases",
"tests::test_from_bits_unchecked",
"tests::test_hash",
"tests::test_in_function",
"tests::test_insert",
"tests::test_is_all",
"tests::test_is_empty",
"tests::test_iter",
"tests::test_lowerhex",
"tests::test_octal",
"tests::test_lt",
"tests::test_operators",
"tests::test_operators_unchecked",
"tests::test_ord",
"tests::test_overlapping_intersects",
"tests::test_pub_crate",
"tests::test_pub_in_module",
"tests::test_public",
"tests::test_remove",
"tests::test_serde_bitflags_deserialize",
"tests::test_serde_bitflags_roundtrip",
"tests::test_serde_bitflags_serialize",
"tests::test_set_ops_basic",
"tests::test_set_ops_const",
"tests::test_set_ops_unchecked",
"tests::test_u128_bitflags",
"tests::test_upperhex",
"tests::test_two_empties_do_not_intersect",
"tests::test_zero_value_flags",
"tests::test_set",
"tests::test_from_iterator",
"tests::test_set_ops_exhaustive",
"basic",
"tests/compile-pass/cfg/nested-value.rs",
"tests/compile-pass/impls/convert.rs",
"tests/compile-pass/impls/default.rs",
"tests/compile-pass/impls/fmt.rs",
"tests/compile-pass/impls/inherent_methods.rs",
"tests/compile-pass/no_prelude.rs",
"tests/compile-pass/redefinition/core.rs",
"tests/compile-pass/redefinition/macros.rs",
"tests/compile-pass/redefinition/result.rs",
"tests/compile-pass/repr/c.rs",
"tests/compile-pass/repr/transparent.rs",
"tests/compile-pass/trait/precedence.rs",
"tests/compile-pass/visibility/bits_field.rs",
"tests/compile-pass/visibility/pub_in.rs"
] |
[] |
[] |
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
|
[
"tests/compile-pass/impls/fmt.rs"
] |
[
"tests::submodule::test_private",
"tests::test_assignment_operators",
"tests::test_binary",
"tests::test_bits",
"tests::test_const_fn",
"tests::test_contains",
"tests::test_debug",
"tests::test_default",
"tests::test_deprecated",
"tests::test_disjoint_intersects",
"tests::test_empty_bitflags",
"tests::test_empty_does_not_intersect_with_full",
"tests::test_extend",
"tests::test_from_bits",
"tests::test_from_bits_unchecked",
"tests::test_from_iterator",
"tests::test_hash",
"tests::test_is_all",
"tests::test_lowerhex",
"tests::test_is_empty",
"tests::test_operators",
"tests::test_operators_unchecked",
"tests::test_overlapping_intersects",
"tests::test_insert",
"tests::test_lt",
"tests::test_pub_crate",
"tests::test_pub_in_module",
"tests::test_remove",
"tests::test_serde_bitflags_serialize",
"tests::test_ord",
"tests::test_serde_bitflags_roundtrip",
"tests::test_serde_bitflags_deserialize",
"tests::test_set",
"tests::test_set_ops_basic",
"tests::test_in_function",
"tests::test_set_ops_const",
"tests::test_public",
"tests::test_octal",
"tests::test_set_ops_unchecked",
"tests::test_two_empties_do_not_intersect",
"tests::test_u128_bitflags",
"tests::test_upperhex",
"tests::test_zero_value_flags",
"tests::test_from_bits_truncate",
"tests::test_set_ops_exhaustive",
"basic",
"tests/compile-pass/cfg/nested-value.rs",
"tests/compile-pass/impls/convert.rs",
"tests/compile-pass/impls/default.rs",
"tests/compile-pass/impls/inherent_methods.rs",
"tests/compile-pass/redefinition/core.rs",
"tests/compile-pass/redefinition/macros.rs",
"tests/compile-pass/repr/c.rs",
"tests/compile-pass/repr/transparent.rs",
"tests/compile-pass/trait/precedence.rs",
"tests/compile-pass/visibility/bits_field.rs",
"tests/compile-pass/visibility/pub_in.rs"
] |
[] |
[] |
|
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
|
[
"tests/compile-pass/redefinition/result.rs"
] |
[
"tests::submodule::test_private",
"tests::test_assignment_operators",
"tests::test_binary",
"tests::test_bits",
"tests::test_const_fn",
"tests::test_contains",
"tests::test_debug",
"tests::test_default",
"tests::test_deprecated",
"tests::test_disjoint_intersects",
"tests::test_empty_bitflags",
"tests::test_extend",
"tests::test_empty_does_not_intersect_with_full",
"tests::test_from_bits",
"tests::test_from_bits_truncate",
"tests::test_from_bits_unchecked",
"tests::test_from_iterator",
"tests::test_hash",
"tests::test_in_function",
"tests::test_insert",
"tests::test_is_all",
"tests::test_is_empty",
"tests::test_lowerhex",
"tests::test_lt",
"tests::test_octal",
"tests::test_operators",
"tests::test_operators_unchecked",
"tests::test_ord",
"tests::test_pub_crate",
"tests::test_pub_in_module",
"tests::test_public",
"tests::test_remove",
"tests::test_serde_bitflags_deserialize",
"tests::test_serde_bitflags_roundtrip",
"tests::test_set_ops_basic",
"tests::test_set_ops_const",
"tests::test_two_empties_do_not_intersect",
"tests::test_set_ops_unchecked",
"tests::test_u128_bitflags",
"tests::test_upperhex",
"tests::test_set",
"tests::test_zero_value_flags",
"tests::test_serde_bitflags_serialize",
"tests::test_overlapping_intersects",
"tests::test_set_ops_exhaustive",
"basic",
"tests/compile-pass/cfg/nested-value.rs",
"tests/compile-pass/impls/convert.rs",
"tests/compile-pass/impls/default.rs",
"tests/compile-pass/impls/inherent_methods.rs",
"tests/compile-pass/redefinition/core.rs",
"tests/compile-pass/redefinition/stringify.rs",
"tests/compile-pass/repr/c.rs",
"tests/compile-pass/repr/transparent.rs",
"tests/compile-pass/trait/precedence.rs",
"tests/compile-pass/visibility/bits_field.rs",
"tests/compile-pass/visibility/pub_in.rs"
] |
[] |
[] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.