enumflags2-0.7.10/.cargo_vcs_info.json0000644000000001360000000000100131640ustar { "git": { "sha1": "8205d5ba03ccc9ccb7407693440f8e47f8ceeeb4" }, "path_in_vcs": "" }enumflags2-0.7.10/.github/workflows/rust.yml000064400000000000000000000016571046102023000171020ustar 00000000000000name: Rust on: [push, pull_request] jobs: build: strategy: matrix: include: - rust: nightly - rust: stable extra-test-opts: -- --skip ui - rust: 1.56 extra-test-opts: -- --skip ui runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} profile: minimal default: true - uses: taiki-e/install-action@cargo-hack - run: cargo hack build --feature-powerset - run: cargo test --all ${{ matrix.extra-test-opts }} clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true components: clippy - uses: taiki-e/install-action@cargo-hack - run: cargo hack clippy --workspace -- -D warnings enumflags2-0.7.10/.gitignore000064400000000000000000000000251046102023000137410ustar 00000000000000target Cargo.lock *~ enumflags2-0.7.10/Cargo.toml0000644000000022770000000000100111720ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.56" name = "enumflags2" version = "0.7.10" authors = [ "maik klein ", "Maja Kądziołka ", ] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Enum-based bit flags" documentation = "https://docs.rs/enumflags2" readme = "README.md" keywords = [ "enum", "bitflag", "flag", "bitflags", ] license = "MIT OR Apache-2.0" repository = "https://github.com/meithecatte/enumflags2" [lib] name = "enumflags2" path = "src/lib.rs" [dependencies.enumflags2_derive] version = "=0.7.10" [dependencies.serde] version = "^1.0.0" optional = true default-features = false [features] std = [] enumflags2-0.7.10/Cargo.toml.orig000064400000000000000000000012661046102023000146500ustar 00000000000000[package] name = "enumflags2" version = "0.7.10" authors = ["maik klein ", "Maja Kądziołka "] description = "Enum-based bit flags" license = "MIT OR Apache-2.0" repository = "https://github.com/meithecatte/enumflags2" readme = "README.md" keywords = ["enum", "bitflag", "flag", "bitflags"] documentation = "https://docs.rs/enumflags2" edition = "2018" rust-version = "1.56" [dependencies.enumflags2_derive] version = "=0.7.10" path = "enumflags_derive" [dependencies.serde] version = "^1.0.0" default-features = false optional = true [features] std = [] [workspace] members = [ "enumflags_derive", "test_suite", "benchmarks", ] enumflags2-0.7.10/LICENSE-APACHE000064400000000000000000000227631046102023000137120ustar 00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2017-2023 Maik Klein, Maja Kądziołka Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. enumflags2-0.7.10/LICENSE-MIT000064400000000000000000000020651046102023000134130ustar 00000000000000Copyright (c) 2017-2023 Maik Klein, Maja Kądziołka 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. enumflags2-0.7.10/README.md000064400000000000000000000074451046102023000132450ustar 00000000000000[![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE-MIT) [![LICENSE](https://img.shields.io/badge/license-apache-blue.svg)](LICENSE-APACHE) [![Documentation](https://docs.rs/enumflags2/badge.svg)](https://docs.rs/enumflags2) [![Crates.io Version](https://img.shields.io/crates/v/enumflags2.svg)](https://crates.io/crates/enumflags2) # Enumflags `enumflags2` implements the classic bitflags datastructure. Annotate an enum with `#[bitflags]`, and `BitFlags` will be able to hold arbitrary combinations of your enum within the space of a single integer. ## Features - [x] Uses enums to represent individual flags—a set of flags is a separate type from a single flag. - [x] Automatically chooses a free bit when you don't specify. - [x] Detects incorrect BitFlags at compile time. - [x] Has a similar API compared to the popular [bitflags](https://crates.io/crates/bitflags) crate. - [x] Does not expose the generated types explicity. The user interacts exclusively with `struct BitFlags;`. - [x] The debug formatter prints the binary flag value as well as the flag enums: `BitFlags(0b1111, [A, B, C, D])`. - [x] Optional support for serialization with the [`serde`](https://serde.rs/) feature flag. ## Example ```rust use enumflags2::{bitflags, make_bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Test { A = 0b0001, B = 0b0010, C, // unspecified variants pick unused bits automatically D = 0b1000, } // Flags can be combined with |, this creates a BitFlags of your type: let a_b: BitFlags = Test::A | Test::B; let a_c = Test::A | Test::C; let b_c_d = make_bitflags!(Test::{B | C | D}); // The debug output lets you inspect both the numeric value and // the actual flags: assert_eq!(format!("{:?}", a_b), "BitFlags(0b11, A | B)"); // But if you'd rather see only one of those, that's available too: assert_eq!(format!("{}", a_b), "A | B"); assert_eq!(format!("{:04b}", a_b), "0011"); // Iterate over the flags like a normal set assert_eq!(a_b.iter().collect::>(), &[Test::A, Test::B]); // Query the contents with contains and intersects assert!(a_b.contains(Test::A)); assert!(b_c_d.contains(Test::B | Test::C)); assert!(!(b_c_d.contains(a_b))); assert!(a_b.intersects(a_c)); assert!(!(a_b.intersects(Test::C | Test::D))); ``` ## Optional Feature Flags - [`serde`](https://serde.rs/) implements `Serialize` and `Deserialize` for `BitFlags`. - `std` implements `std::error::Error` for `FromBitsError`. ## `const fn`-compatible APIs **Background:** The subset of `const fn` features currently stabilized is pretty limited. Most notably, [const traits are still at the RFC stage][const-trait-rfc], which makes it impossible to use any overloaded operators in a const context. **Naming convention:** If a separate, more limited function is provided for usage in a `const fn`, the name is suffixed with `_c`. **Blanket implementations:** If you attempt to write a `const fn` ranging over `T: BitFlag`, you will be met with an error explaining that currently, the only allowed trait bound for a `const fn` is `?Sized`. You will probably want to write a separate implementation for `BitFlags`, `BitFlags`, etc — probably generated by a macro. This strategy is often used by `enumflags2` itself; to avoid clutter, only one of the copies is shown in the documentation. ## Customizing `Default` By default, creating an instance of `BitFlags` with `Default` will result in an empty set. If that's undesirable, you may customize this: ```rust #[bitflags(default = B | C)] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Test { A = 0b0001, B = 0b0010, C = 0b0100, D = 0b1000, } assert_eq!(BitFlags::default(), Test::B | Test::C); ``` [const-trait-rfc]: https://github.com/rust-lang/rfcs/pull/2632 enumflags2-0.7.10/src/const_api.rs000064400000000000000000000122721046102023000150740ustar 00000000000000use crate::{BitFlags, BitFlag}; use core::marker::PhantomData; /// Workaround for `const fn` limitations. /// /// Some `const fn`s in this crate will need an instance of this type /// for some type-level information usually provided by traits. /// /// A token can be obtained from [`BitFlags::CONST_TOKEN`]. The relevant types /// should be readily inferred from context. /// /// For an example of usage, see [`not_c`][BitFlags::not_c]. pub struct ConstToken(BitFlags); impl BitFlags where T: BitFlag, { /// An empty `BitFlags`. Equivalent to [`empty()`][BitFlags::empty], /// but works in a const context. pub const EMPTY: Self = BitFlags { val: T::EMPTY, marker: PhantomData, }; /// A `BitFlags` with all flags set. Equivalent to [`all()`][BitFlags::all], /// but works in a const context. pub const ALL: Self = BitFlags { val: T::ALL_BITS, marker: PhantomData, }; /// A [`ConstToken`] for this type of flag. pub const CONST_TOKEN: ConstToken = ConstToken(Self::ALL); } for_each_uint! { $ty $hide_docs => impl BitFlags { /// Create a new BitFlags unsafely, without checking if the bits form /// a valid bit pattern for the type. /// /// Const variant of /// [`from_bits_unchecked`][BitFlags::from_bits_unchecked]. /// /// Consider using /// [`from_bits_truncate_c`][BitFlags::from_bits_truncate_c] instead. /// /// # Safety /// /// All bits set in `val` must correspond to a value of the enum. #[must_use] #[inline(always)] $(#[$hide_docs])? pub const unsafe fn from_bits_unchecked_c( val: $ty, const_token: ConstToken ) -> Self { let _ = const_token; BitFlags { val, marker: PhantomData, } } /// Create a `BitFlags` from an underlying bitwise value. If any /// invalid bits are set, ignore them. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, Debug, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// const FLAGS: BitFlags = /// BitFlags::::from_bits_truncate_c(0b10101010, BitFlags::CONST_TOKEN); /// assert_eq!(FLAGS, MyFlag::Two); /// ``` #[must_use] #[inline(always)] $(#[$hide_docs])? pub const fn from_bits_truncate_c( bits: $ty, const_token: ConstToken ) -> Self { BitFlags { val: bits & const_token.0.val, marker: PhantomData, } } /// Bitwise OR — return value contains flag if either argument does. /// /// Also available as `a | b`, but operator overloads are not usable /// in `const fn`s at the moment. #[must_use] #[inline(always)] $(#[$hide_docs])? pub const fn union_c(self, other: Self) -> Self { BitFlags { val: self.val | other.val, marker: PhantomData, } } /// Bitwise AND — return value contains flag if both arguments do. /// /// Also available as `a & b`, but operator overloads are not usable /// in `const fn`s at the moment. #[must_use] #[inline(always)] $(#[$hide_docs])? pub const fn intersection_c(self, other: Self) -> Self { BitFlags { val: self.val & other.val, marker: PhantomData, } } /// Bitwise NOT — return value contains flag if argument doesn't. /// /// Also available as `!a`, but operator overloads are not usable /// in `const fn`s at the moment. /// /// Moreover, due to `const fn` limitations, `not_c` needs a /// [`ConstToken`] as an argument. /// /// ``` /// # use enumflags2::{bitflags, BitFlags, make_bitflags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, Debug, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// const FLAGS: BitFlags = make_bitflags!(MyFlag::{One | Two}); /// const NEGATED: BitFlags = FLAGS.not_c(BitFlags::CONST_TOKEN); /// assert_eq!(NEGATED, MyFlag::Three); /// ``` #[must_use] #[inline(always)] $(#[$hide_docs])? pub const fn not_c(self, const_token: ConstToken) -> Self { BitFlags { val: !self.val & const_token.0.val, marker: PhantomData, } } /// Returns the underlying bitwise value. /// /// `const` variant of [`bits`][BitFlags::bits]. #[inline(always)] $(#[$hide_docs])? pub const fn bits_c(self) -> $ty { self.val } } } enumflags2-0.7.10/src/fallible.rs000064400000000000000000000041031046102023000146610ustar 00000000000000use super::BitFlag; use super::BitFlags; use core::convert::TryFrom; use core::fmt; // Coherence doesn't let us use a generic type here. Work around by implementing // for each integer type manually. for_each_uint! { $ty $hide_docs => impl TryFrom<$ty> for BitFlags where T: BitFlag, { type Error = FromBitsError; fn try_from(bits: T::Numeric) -> Result { Self::from_bits(bits) } } } /// The error struct used by [`BitFlags::from_bits`] /// and the [`TryFrom`] implementation for invalid values. /// /// Note that the implementation of [`std::error::Error`] /// for this type is gated on the `std` feature flag. /// /// ``` /// # use std::convert::TryInto; /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[derive(Clone, Copy, Debug)] /// #[repr(u8)] /// enum MyFlags { /// A = 0b0001, /// B = 0b0010, /// C = 0b0100, /// D = 0b1000, /// } /// /// let result: Result, _> = 0b10101u8.try_into(); /// assert!(result.is_err()); /// let error = result.unwrap_err(); /// assert_eq!(error.truncate(), MyFlags::C | MyFlags::A); /// assert_eq!(error.invalid_bits(), 0b10000); /// ``` #[derive(Debug, Copy, Clone)] pub struct FromBitsError { pub(crate) flags: BitFlags, pub(crate) invalid: T::Numeric, } impl FromBitsError { /// Return the truncated result of the conversion. pub fn truncate(self) -> BitFlags { self.flags } /// Return the bits that didn't correspond to any flags. pub fn invalid_bits(self) -> T::Numeric { self.invalid } } impl fmt::Display for FromBitsError { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( fmt, "Invalid bits for {:?}: {:#b}", self.flags, self.invalid ) } } #[cfg(feature = "std")] impl std::error::Error for FromBitsError { fn description(&self) -> &str { "invalid bitflags representation" } } enumflags2-0.7.10/src/formatting.rs000064400000000000000000000114351046102023000152670ustar 00000000000000use crate::{BitFlag, BitFlags}; use core::fmt::{self, Binary, Debug}; impl fmt::Debug for BitFlags where T: BitFlag + fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let name = T::BITFLAGS_TYPE_NAME; let bits = DebugBinaryFormatter(&self.val); let iter = if !self.is_empty() { Some(FlagFormatter(self.iter())) } else { None }; if !fmt.alternate() { // Concise tuple formatting is a better default let mut debug = fmt.debug_tuple(name); debug.field(&bits); if let Some(iter) = iter { debug.field(&iter); } debug.finish() } else { // Pretty-printed tuples are ugly and hard to read, so use struct format let mut debug = fmt.debug_struct(name); debug.field("bits", &bits); if let Some(iter) = iter { debug.field("flags", &iter); } debug.finish() } } } impl fmt::Display for BitFlags where T: BitFlag + fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&FlagFormatter(self.iter()), fmt) } } impl fmt::Binary for BitFlags where T: BitFlag, T::Numeric: fmt::Binary, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Binary::fmt(&self.bits(), fmt) } } impl fmt::Octal for BitFlags where T: BitFlag, T::Numeric: fmt::Octal, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Octal::fmt(&self.bits(), fmt) } } impl fmt::LowerHex for BitFlags where T: BitFlag, T::Numeric: fmt::LowerHex, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::LowerHex::fmt(&self.bits(), fmt) } } impl fmt::UpperHex for BitFlags where T: BitFlag, T::Numeric: fmt::UpperHex, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::UpperHex::fmt(&self.bits(), fmt) } } // Format an iterator of flags into "A | B | etc" struct FlagFormatter(I); impl> Debug for FlagFormatter { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut iter = self.0.clone(); if let Some(val) = iter.next() { Debug::fmt(&val, fmt)?; for val in iter { fmt.write_str(" | ")?; Debug::fmt(&val, fmt)?; } Ok(()) } else { fmt.write_str("") } } } // A formatter that obeys format arguments but falls back to binary when // no explicit format is requested. Supports {:08?}, {:08x?}, etc. struct DebugBinaryFormatter<'a, F>(&'a F); impl<'a, F: Debug + Binary + 'a> Debug for DebugBinaryFormatter<'a, F> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { // Check if {:x?} or {:X?} was used; this is determined via the // discriminator of core::fmt::FlagV1::{DebugLowerHex, DebugUpperHex}, // which is not an accessible type: https://github.com/rust-lang/rust/blob/d65e272a9fe3e61aa5f229c5358e35a909435575/src/libcore/fmt/mod.rs#L306 // See also: https://github.com/rust-lang/rfcs/pull/2226 #[allow(deprecated)] let format_hex = fmt.flags() >> 4; let width = fmt.width().unwrap_or(0); if format_hex & 1 != 0 { // FlagV1::DebugLowerHex write!(fmt, "{:#0width$x?}", &self.0, width = width) } else if format_hex & 2 != 0 { // FlagV1::DebugUpperHex write!(fmt, "{:#0width$X?}", &self.0, width = width) } else { // Fall back to binary otheriwse write!(fmt, "{:#0width$b}", &self.0, width = width) } } } #[test] fn flag_formatter() { use core::iter; macro_rules! assert_fmt { ($fmt:expr, $expr:expr, $expected:expr) => { assert_eq!(format!($fmt, FlagFormatter($expr)), $expected) }; } assert_fmt!("{:?}", iter::empty::(), ""); assert_fmt!("{:?}", iter::once(1), "1"); assert_fmt!("{:?}", [1, 2].iter(), "1 | 2"); assert_fmt!("{:?}", [1, 2, 10].iter(), "1 | 2 | 10"); assert_fmt!("{:02x?}", [1, 2, 10].iter(), "01 | 02 | 0a"); assert_fmt!("{:#04X?}", [1, 2, 10].iter(), "0x01 | 0x02 | 0x0A"); } #[test] fn debug_binary_formatter() { macro_rules! assert_fmt { ($fmt:expr, $expr:expr, $expected:expr) => { assert_eq!(format!($fmt, DebugBinaryFormatter(&$expr)), $expected) }; } assert_fmt!("{:?}", 10, "0b1010"); assert_fmt!("{:#?}", 10, "0b1010"); assert_fmt!("{:010?}", 10, "0b00001010"); assert_fmt!("{:010x?}", 10, "0x0000000a"); assert_fmt!("{:#010X?}", 10, "0x0000000A"); } enumflags2-0.7.10/src/iter.rs000064400000000000000000000051641046102023000140620ustar 00000000000000use crate::{BitFlag, BitFlags, BitFlagNum}; use core::iter::{FromIterator, FusedIterator}; impl BitFlags where T: BitFlag, { /// Iterate over the `BitFlags`. /// /// ``` /// # use enumflags2::{bitflags, make_bitflags}; /// # #[bitflags] /// # #[derive(Clone, Copy, PartialEq, Debug)] /// # #[repr(u8)] /// # enum MyFlag { /// # A = 1 << 0, /// # B = 1 << 1, /// # C = 1 << 2, /// # } /// let flags = make_bitflags!(MyFlag::{A | C}); /// /// flags.iter() /// .for_each(|flag| println!("{:?}", flag)); /// ``` #[inline] pub fn iter(self) -> Iter { Iter { rest: self } } } impl IntoIterator for BitFlags { type IntoIter = Iter; type Item = T; fn into_iter(self) -> Self::IntoIter { self.iter() } } /// Iterator that yields each flag set in a `BitFlags`. #[derive(Clone, Debug)] pub struct Iter { rest: BitFlags, } impl Iterator for Iter where T: BitFlag, { type Item = T; fn next(&mut self) -> Option { if self.rest.is_empty() { None } else { // SAFETY: `flag` will be a single bit, because // x & -x = x & (~x + 1), and the increment causes only one 0 -> 1 transition. // The invariant of `from_bits_unchecked` is satisfied, because bits & x // is a subset of bits, which we know are the valid bits. unsafe { let bits = self.rest.bits(); let flag: T::Numeric = bits & bits.wrapping_neg(); let flag: T = core::mem::transmute_copy(&flag); self.rest = BitFlags::from_bits_unchecked(bits & (bits - BitFlagNum::ONE)); Some(flag) } } } fn size_hint(&self) -> (usize, Option) { let l = self.rest.len(); (l, Some(l)) } } impl ExactSizeIterator for Iter where T: BitFlag, { fn len(&self) -> usize { self.rest.len() } } impl FusedIterator for Iter {} impl FromIterator for BitFlags where T: BitFlag, B: Into>, { #[inline] fn from_iter(it: I) -> BitFlags where I: IntoIterator, { it.into_iter() .fold(BitFlags::empty(), |acc, flag| acc | flag) } } impl Extend for BitFlags where T: BitFlag, B: Into>, { #[inline] fn extend(&mut self, it: I) where I: IntoIterator, { *self = it.into_iter().fold(*self, |acc, flag| acc | flag) } } enumflags2-0.7.10/src/lib.rs000064400000000000000000000742031046102023000136650ustar 00000000000000//! # Enum Flags //! `enumflags2` implements the classic bitflags datastructure. Annotate an enum //! with `#[bitflags]`, and `BitFlags` will be able to hold arbitrary combinations //! of your enum within the space of a single integer. //! //! ## Example //! ``` //! use enumflags2::{bitflags, make_bitflags, BitFlags}; //! //! #[bitflags] //! #[repr(u8)] //! #[derive(Copy, Clone, Debug, PartialEq)] //! enum Test { //! A = 0b0001, //! B = 0b0010, //! C, // unspecified variants pick unused bits automatically //! D = 0b1000, //! } //! //! // Flags can be combined with |, this creates a BitFlags of your type: //! let a_b: BitFlags = Test::A | Test::B; //! let a_c = Test::A | Test::C; //! let b_c_d = make_bitflags!(Test::{B | C | D}); //! //! // The debug output lets you inspect both the numeric value and //! // the actual flags: //! assert_eq!(format!("{:?}", a_b), "BitFlags(0b11, A | B)"); //! //! // But if you'd rather see only one of those, that's available too: //! assert_eq!(format!("{}", a_b), "A | B"); //! assert_eq!(format!("{:04b}", a_b), "0011"); //! //! // Iterate over the flags like a normal set //! assert_eq!(a_b.iter().collect::>(), &[Test::A, Test::B]); //! //! // Query the contents with contains and intersects //! assert!(a_b.contains(Test::A)); //! assert!(b_c_d.contains(Test::B | Test::C)); //! assert!(!(b_c_d.contains(a_b))); //! //! assert!(a_b.intersects(a_c)); //! assert!(!(a_b.intersects(Test::C | Test::D))); //! ``` //! //! ## Optional Feature Flags //! //! - [`serde`](https://serde.rs/) implements `Serialize` and `Deserialize` //! for `BitFlags`. //! - `std` implements `std::error::Error` for `FromBitsError`. //! //! ## `const fn`-compatible APIs //! //! **Background:** The subset of `const fn` features currently stabilized is pretty limited. //! Most notably, [const traits are still at the RFC stage][const-trait-rfc], //! which makes it impossible to use any overloaded operators in a const //! context. //! //! **Naming convention:** If a separate, more limited function is provided //! for usage in a `const fn`, the name is suffixed with `_c`. //! //! **Blanket implementations:** If you attempt to write a `const fn` ranging //! over `T: BitFlag`, you will be met with an error explaining that currently, //! the only allowed trait bound for a `const fn` is `?Sized`. You will probably //! want to write a separate implementation for `BitFlags`, //! `BitFlags`, etc — best accomplished by a simple macro. //! //! **Documentation considerations:** The strategy described above is often used //! by `enumflags2` itself. To avoid clutter in the auto-generated documentation, //! the implementations for widths other than `u8` are marked with `#[doc(hidden)]`. //! //! ## Customizing `Default` //! //! By default, creating an instance of `BitFlags` with `Default` will result in an empty //! set. If that's undesirable, you may customize this: //! //! ``` //! # use enumflags2::{BitFlags, bitflags}; //! #[bitflags(default = B | C)] //! #[repr(u8)] //! #[derive(Copy, Clone, Debug, PartialEq)] //! enum Test { //! A = 0b0001, //! B = 0b0010, //! C = 0b0100, //! D = 0b1000, //! } //! //! assert_eq!(BitFlags::default(), Test::B | Test::C); //! ``` //! //! [const-trait-rfc]: https://github.com/rust-lang/rfcs/pull/2632 #![warn(missing_docs)] #![cfg_attr(all(not(test), not(feature = "std")), no_std)] use core::hash::{Hash, Hasher}; use core::marker::PhantomData; use core::{cmp, ops}; #[allow(unused_imports)] #[macro_use] extern crate enumflags2_derive; #[doc(hidden)] pub use enumflags2_derive::bitflags_internal as bitflags; // Internal macro: expand into a separate copy for each supported numeric type. macro_rules! for_each_uint { ( $d:tt $tyvar:ident $dd:tt $docattr:ident => $($input:tt)* ) => { macro_rules! implement { ( $d $tyvar:ty => $d($d $docattr:meta)? ) => { $($input)* } } implement! { u8 => } implement! { u16 => doc(hidden) } implement! { u32 => doc(hidden) } implement! { u64 => doc(hidden) } implement! { u128 => doc(hidden) } } } /// A trait automatically implemented by `#[bitflags]` to make the enum /// a valid type parameter for `BitFlags`. pub trait BitFlag: Copy + Clone + 'static + _internal::RawBitFlags { /// Create a `BitFlags` with no flags set (in other words, with a value of 0). /// /// This is a convenience reexport of [`BitFlags::empty`]. It can be called with /// `MyFlag::empty()`, thus bypassing the need for type hints in some situations. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// use enumflags2::BitFlag; /// /// let empty = MyFlag::empty(); /// assert!(empty.is_empty()); /// assert_eq!(empty.contains(MyFlag::One), false); /// assert_eq!(empty.contains(MyFlag::Two), false); /// assert_eq!(empty.contains(MyFlag::Three), false); /// ``` #[inline] fn empty() -> BitFlags { BitFlags::empty() } /// Create a `BitFlags` with all flags set. /// /// This is a convenience reexport of [`BitFlags::all`]. It can be called with /// `MyFlag::all()`, thus bypassing the need for type hints in some situations. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// use enumflags2::BitFlag; /// /// let all = MyFlag::all(); /// assert!(all.is_all()); /// assert_eq!(all.contains(MyFlag::One), true); /// assert_eq!(all.contains(MyFlag::Two), true); /// assert_eq!(all.contains(MyFlag::Three), true); /// ``` #[inline] fn all() -> BitFlags { BitFlags::all() } /// Create a `BitFlags` if the raw value provided does not contain /// any illegal flags. /// /// This is a convenience reexport of [`BitFlags::from_bits`]. It can be called /// with `MyFlag::from_bits(bits)`, thus bypassing the need for type hints in /// some situations. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq, Debug)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// use enumflags2::BitFlag; /// /// let flags = MyFlag::from_bits(0b11).unwrap(); /// assert_eq!(flags.contains(MyFlag::One), true); /// assert_eq!(flags.contains(MyFlag::Two), true); /// assert_eq!(flags.contains(MyFlag::Three), false); /// let invalid = MyFlag::from_bits(1 << 3); /// assert!(invalid.is_err()); /// ``` #[inline] fn from_bits(bits: Self::Numeric) -> Result, FromBitsError> { BitFlags::from_bits(bits) } /// Create a `BitFlags` from an underlying bitwise value. If any /// invalid bits are set, ignore them. /// /// This is a convenience reexport of [`BitFlags::from_bits_truncate`]. It can be /// called with `MyFlag::from_bits_truncate(bits)`, thus bypassing the need for /// type hints in some situations. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// use enumflags2::BitFlag; /// /// let flags = MyFlag::from_bits_truncate(0b1_1011); /// assert_eq!(flags.contains(MyFlag::One), true); /// assert_eq!(flags.contains(MyFlag::Two), true); /// assert_eq!(flags.contains(MyFlag::Three), false); /// ``` #[inline] fn from_bits_truncate(bits: Self::Numeric) -> BitFlags { BitFlags::from_bits_truncate(bits) } /// Create a `BitFlags` unsafely, without checking if the bits form /// a valid bit pattern for the type. /// /// Consider using [`from_bits`][BitFlag::from_bits] /// or [`from_bits_truncate`][BitFlag::from_bits_truncate] instead. /// /// # Safety /// /// All bits set in `val` must correspond to a value of the enum. /// /// # Example /// /// This is a convenience reexport of [`BitFlags::from_bits_unchecked`]. It can be /// called with `MyFlag::from_bits_unchecked(bits)`, thus bypassing the need for /// type hints in some situations. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// use enumflags2::BitFlag; /// /// let flags = unsafe { /// MyFlag::from_bits_unchecked(0b011) /// }; /// /// assert_eq!(flags.contains(MyFlag::One), true); /// assert_eq!(flags.contains(MyFlag::Two), true); /// assert_eq!(flags.contains(MyFlag::Three), false); /// ``` #[inline] unsafe fn from_bits_unchecked(bits: Self::Numeric) -> BitFlags { BitFlags::from_bits_unchecked(bits) } } /// While the module is public, this is only the case because it needs to be /// accessed by the macro. Do not use this directly. Stability guarantees /// don't apply. #[doc(hidden)] pub mod _internal { /// A trait automatically implemented by `#[bitflags]` to make the enum /// a valid type parameter for `BitFlags`. /// /// # Safety /// /// The values should reflect reality, like they do if the implementation /// is generated by the procmacro. pub unsafe trait RawBitFlags: Copy + Clone + 'static { /// The underlying integer type. type Numeric: BitFlagNum; /// A value with no bits set. const EMPTY: Self::Numeric; /// The value used by the Default implementation. Equivalent to EMPTY, unless /// customized. const DEFAULT: Self::Numeric; /// A value with all flag bits set. const ALL_BITS: Self::Numeric; /// The name of the type for debug formatting purposes. /// /// This is typically `BitFlags` const BITFLAGS_TYPE_NAME: &'static str; /// Return the bits as a number type. fn bits(self) -> Self::Numeric; } use ::core::fmt; use ::core::ops::{BitAnd, BitOr, BitXor, Not, Sub}; use ::core::hash::Hash; pub trait BitFlagNum: Default + BitOr + BitAnd + BitXor + Sub + Not + PartialOrd + Ord + Hash + fmt::Debug + fmt::Binary + Copy + Clone { const ONE: Self; fn is_power_of_two(self) -> bool; fn count_ones(self) -> u32; fn wrapping_neg(self) -> Self; } for_each_uint! { $ty $hide_docs => impl BitFlagNum for $ty { const ONE: Self = 1; fn is_power_of_two(self) -> bool { <$ty>::is_power_of_two(self) } fn count_ones(self) -> u32 { <$ty>::count_ones(self) } fn wrapping_neg(self) -> Self { <$ty>::wrapping_neg(self) } } } // Re-export libcore so the macro doesn't inject "extern crate" downstream. pub mod core { pub use core::{convert, ops, option}; } pub struct AssertionSucceeded; pub struct AssertionFailed; pub trait ExactlyOneBitSet { type X; } impl ExactlyOneBitSet for AssertionSucceeded { type X = (); } pub trait AssertionHelper { type Status; } impl AssertionHelper for [(); 1] { type Status = AssertionSucceeded; } impl AssertionHelper for [(); 0] { type Status = AssertionFailed; } pub const fn next_bit(x: u128) -> u128 { 1 << x.trailing_ones() } } use _internal::BitFlagNum; // Internal debug formatting implementations mod formatting; // impl TryFrom for BitFlags mod fallible; pub use crate::fallible::FromBitsError; mod iter; pub use crate::iter::Iter; mod const_api; pub use crate::const_api::ConstToken; /// Represents a set of flags of some type `T`. /// `T` must have the `#[bitflags]` attribute applied. /// /// A `BitFlags` is as large as the `T` itself, /// and stores one flag per bit. /// /// ## Comparison operators, [`PartialOrd`] and [`Ord`] /// /// To make it possible to use `BitFlags` as the key of a /// [`BTreeMap`][std::collections::BTreeMap], `BitFlags` implements /// [`Ord`]. There is no meaningful total order for bitflags, /// so the implementation simply compares the integer values of the bits. /// /// Unfortunately, this means that comparing `BitFlags` with an operator /// like `<=` will compile, and return values that are probably useless /// and not what you expect. In particular, `<=` does *not* check whether /// one value is a subset of the other. Use [`BitFlags::contains`] for that. /// /// ## Customizing `Default` /// /// By default, creating an instance of `BitFlags` with `Default` will result /// in an empty set. If that's undesirable, you may customize this: /// /// ``` /// # use enumflags2::{BitFlags, bitflags}; /// #[bitflags(default = B | C)] /// #[repr(u8)] /// #[derive(Copy, Clone, Debug, PartialEq)] /// enum MyFlag { /// A = 0b0001, /// B = 0b0010, /// C = 0b0100, /// D = 0b1000, /// } /// /// assert_eq!(BitFlags::default(), MyFlag::B | MyFlag::C); /// ``` /// /// ## Memory layout /// /// `BitFlags` is marked with the `#[repr(transparent)]` trait, meaning /// it can be safely transmuted into the corresponding numeric type. /// /// Usually, the same can be achieved by using [`BitFlags::bits`] in one /// direction, and [`BitFlags::from_bits`], [`BitFlags::from_bits_truncate`], /// or [`BitFlags::from_bits_unchecked`] in the other direction. However, /// transmuting might still be useful if, for example, you're dealing with /// an entire array of `BitFlags`. /// /// When transmuting *into* a `BitFlags`, make sure that each set bit /// corresponds to an existing flag /// (cf. [`from_bits_unchecked`][BitFlags::from_bits_unchecked]). /// /// For example: /// /// ``` /// # use enumflags2::{BitFlags, bitflags}; /// #[bitflags] /// #[repr(u8)] // <-- the repr determines the numeric type /// #[derive(Copy, Clone)] /// enum TransmuteMe { /// One = 1 << 0, /// Two = 1 << 1, /// } /// /// # use std::slice; /// // NOTE: we use a small, self-contained function to handle the slice /// // conversion to make sure the lifetimes are right. /// fn transmute_slice<'a>(input: &'a [BitFlags]) -> &'a [u8] { /// unsafe { /// slice::from_raw_parts(input.as_ptr() as *const u8, input.len()) /// } /// } /// /// let many_flags = &[ /// TransmuteMe::One.into(), /// TransmuteMe::One | TransmuteMe::Two, /// ]; /// /// let as_nums = transmute_slice(many_flags); /// assert_eq!(as_nums, &[0b01, 0b11]); /// ``` /// /// ## Implementation notes /// /// You might expect this struct to be defined as /// /// ```ignore /// struct BitFlags { /// value: T::Numeric /// } /// ``` /// /// Ideally, that would be the case. However, because `const fn`s cannot /// have trait bounds in current Rust, this would prevent us from providing /// most `const fn` APIs. As a workaround, we define `BitFlags` with two /// type parameters, with a default for the second one: /// /// ```ignore /// struct BitFlags::Numeric> { /// value: N, /// marker: PhantomData, /// } /// ``` /// /// Manually providing a type for the `N` type parameter shouldn't ever /// be necessary. /// /// The types substituted for `T` and `N` must always match, creating a /// `BitFlags` value where that isn't the case is only possible with /// incorrect unsafe code. #[derive(Copy, Clone)] #[repr(transparent)] pub struct BitFlags::Numeric> { val: N, marker: PhantomData, } /// `make_bitflags!` provides a succint syntax for creating instances of /// `BitFlags`. Instead of repeating the name of your type for each flag /// you want to add, try `make_bitflags!(Flags::{Foo | Bar})`. /// ``` /// use enumflags2::{bitflags, make_bitflags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, Debug)] /// enum Test { /// A = 1 << 0, /// B = 1 << 1, /// C = 1 << 2, /// } /// let x = make_bitflags!(Test::{A | C}); /// assert_eq!(x, Test::A | Test::C); /// ``` #[macro_export] macro_rules! make_bitflags { ( $enum:ident ::{ $($variant:ident)|* } ) => { { let mut n = 0; $( { let flag: $enum = $enum::$variant; n |= flag as <$enum as $crate::_internal::RawBitFlags>::Numeric; } )* // SAFETY: The value has been created from numeric values of the underlying // enum, so only valid bits are set. unsafe { $crate::BitFlags::<$enum>::from_bits_unchecked_c( n, $crate::BitFlags::CONST_TOKEN) } } } } /// The default value returned is one with all flags unset, i. e. [`empty`][Self::empty], /// unless [customized](index.html#customizing-default). impl Default for BitFlags where T: BitFlag, { #[inline(always)] fn default() -> Self { BitFlags { val: T::DEFAULT, marker: PhantomData, } } } impl From for BitFlags { #[inline(always)] fn from(t: T) -> BitFlags { Self::from_flag(t) } } impl BitFlags where T: BitFlag, { /// Create a `BitFlags` if the raw value provided does not contain /// any illegal flags. /// /// See also: [a convenience re-export in the `BitFlag` trait][BitFlag::from_bits], /// which can help avoid the need for type hints. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq, Debug)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// let flags: BitFlags = BitFlags::from_bits(0b11).unwrap(); /// assert_eq!(flags.contains(MyFlag::One), true); /// assert_eq!(flags.contains(MyFlag::Two), true); /// assert_eq!(flags.contains(MyFlag::Three), false); /// let invalid = BitFlags::::from_bits(1 << 3); /// assert!(invalid.is_err()); /// ``` #[inline] pub fn from_bits(bits: T::Numeric) -> Result> { let flags = Self::from_bits_truncate(bits); if flags.bits() == bits { Ok(flags) } else { Err(FromBitsError { flags, invalid: bits & !flags.bits(), }) } } /// Create a `BitFlags` from an underlying bitwise value. If any /// invalid bits are set, ignore them. /// /// See also: [a convenience re-export in the `BitFlag` trait][BitFlag::from_bits_truncate], /// which can help avoid the need for type hints. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// let flags: BitFlags = BitFlags::from_bits_truncate(0b1_1011); /// assert_eq!(flags.contains(MyFlag::One), true); /// assert_eq!(flags.contains(MyFlag::Two), true); /// assert_eq!(flags.contains(MyFlag::Three), false); /// ``` #[must_use] #[inline(always)] pub fn from_bits_truncate(bits: T::Numeric) -> Self { // SAFETY: We're truncating out all the invalid bits, so the remaining // ones must be valid. unsafe { BitFlags::from_bits_unchecked(bits & T::ALL_BITS) } } /// Create a new BitFlags unsafely, without checking if the bits form /// a valid bit pattern for the type. /// /// Consider using [`from_bits`][BitFlags::from_bits] /// or [`from_bits_truncate`][BitFlags::from_bits_truncate] instead. /// /// # Safety /// /// All bits set in `val` must correspond to a value of the enum. /// /// # Example /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// let flags: BitFlags = unsafe { /// BitFlags::from_bits_unchecked(0b011) /// }; /// /// assert_eq!(flags.contains(MyFlag::One), true); /// assert_eq!(flags.contains(MyFlag::Two), true); /// assert_eq!(flags.contains(MyFlag::Three), false); /// ``` #[must_use] #[inline(always)] pub unsafe fn from_bits_unchecked(val: T::Numeric) -> Self { BitFlags { val, marker: PhantomData, } } /// Turn a `T` into a `BitFlags`. Also available as `flag.into()`. #[must_use] #[inline(always)] pub fn from_flag(flag: T) -> Self { // SAFETY: A value of the underlying enum is valid by definition. unsafe { Self::from_bits_unchecked(flag.bits()) } } /// Create a `BitFlags` with no flags set (in other words, with a value of `0`). /// /// See also: [`BitFlag::empty`], a convenience reexport; /// [`BitFlags::EMPTY`], the same functionality available /// as a constant for `const fn` code. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// let empty: BitFlags = BitFlags::empty(); /// assert!(empty.is_empty()); /// assert_eq!(empty.contains(MyFlag::One), false); /// assert_eq!(empty.contains(MyFlag::Two), false); /// assert_eq!(empty.contains(MyFlag::Three), false); /// ``` #[inline(always)] pub fn empty() -> Self { Self::EMPTY } /// Create a `BitFlags` with all flags set. /// /// See also: [`BitFlag::all`], a convenience reexport; /// [`BitFlags::ALL`], the same functionality available /// as a constant for `const fn` code. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy, PartialEq, Eq)] /// enum MyFlag { /// One = 1 << 0, /// Two = 1 << 1, /// Three = 1 << 2, /// } /// /// let empty: BitFlags = BitFlags::all(); /// assert!(empty.is_all()); /// assert_eq!(empty.contains(MyFlag::One), true); /// assert_eq!(empty.contains(MyFlag::Two), true); /// assert_eq!(empty.contains(MyFlag::Three), true); /// ``` #[inline(always)] pub fn all() -> Self { Self::ALL } /// Returns true if all flags are set #[inline(always)] pub fn is_all(self) -> bool { self.val == T::ALL_BITS } /// Returns true if no flag is set #[inline(always)] pub fn is_empty(self) -> bool { self.val == T::EMPTY } /// Returns the number of flags set. #[inline(always)] pub fn len(self) -> usize { self.val.count_ones() as usize } /// If exactly one flag is set, the flag is returned. Otherwise, returns `None`. /// /// See also [`Itertools::exactly_one`](https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.exactly_one). #[inline(always)] pub fn exactly_one(self) -> Option { if self.val.is_power_of_two() { // SAFETY: By the invariant of the BitFlags type, all bits are valid // in isolation for the underlying enum. Some(unsafe { core::mem::transmute_copy(&self.val) }) } else { None } } /// Returns the underlying bitwise value. /// /// ``` /// # use enumflags2::{bitflags, BitFlags}; /// #[bitflags] /// #[repr(u8)] /// #[derive(Clone, Copy)] /// enum Flags { /// Foo = 1 << 0, /// Bar = 1 << 1, /// } /// /// let both_flags = Flags::Foo | Flags::Bar; /// assert_eq!(both_flags.bits(), 0b11); /// ``` #[inline(always)] pub fn bits(self) -> T::Numeric { self.val } /// Returns true if at least one flag is shared. #[inline(always)] pub fn intersects>>(self, other: B) -> bool { (self.bits() & other.into().bits()) != Self::EMPTY.val } /// Returns true if all flags are contained. #[inline(always)] pub fn contains>>(self, other: B) -> bool { let other = other.into(); (self.bits() & other.bits()) == other.bits() } /// Toggles the matching bits #[inline(always)] pub fn toggle>>(&mut self, other: B) { *self ^= other.into(); } /// Inserts the flags into the BitFlag #[inline(always)] pub fn insert>>(&mut self, other: B) { *self |= other.into(); } /// Removes the matching flags #[inline(always)] pub fn remove>>(&mut self, other: B) { *self &= !other.into(); } /// Inserts if `cond` holds, else removes /// /// ``` /// # use enumflags2::bitflags; /// #[bitflags] /// #[derive(Clone, Copy, PartialEq, Debug)] /// #[repr(u8)] /// enum MyFlag { /// A = 1 << 0, /// B = 1 << 1, /// C = 1 << 2, /// } /// /// let mut state = MyFlag::A | MyFlag::C; /// state.set(MyFlag::A | MyFlag::B, false); /// /// // Because the condition was false, both /// // `A` and `B` are removed from the set /// assert_eq!(state, MyFlag::C); /// ``` #[inline(always)] pub fn set>>(&mut self, other: B, cond: bool) { if cond { self.insert(other); } else { self.remove(other); } } } impl PartialEq for BitFlags { #[inline(always)] fn eq(&self, other: &Self) -> bool { self.val == other.val } } impl Eq for BitFlags {} impl PartialOrd for BitFlags { #[inline(always)] fn partial_cmp(&self, other: &Self) -> Option { self.val.partial_cmp(&other.val) } } impl Ord for BitFlags { #[inline(always)] fn cmp(&self, other: &Self) -> cmp::Ordering { self.val.cmp(&other.val) } } // Clippy complains when Hash is derived while PartialEq is implemented manually impl Hash for BitFlags { #[inline(always)] fn hash(&self, state: &mut H) { self.val.hash(state) } } impl cmp::PartialEq for BitFlags where T: BitFlag, { #[inline(always)] fn eq(&self, other: &T) -> bool { self.bits() == Into::::into(*other).bits() } } impl ops::BitOr for BitFlags where T: BitFlag, B: Into>, { type Output = BitFlags; #[inline(always)] fn bitor(self, other: B) -> BitFlags { // SAFETY: The two operands are known to be composed of valid bits, // and 0 | 0 = 0 in the columns of the invalid bits. unsafe { BitFlags::from_bits_unchecked(self.bits() | other.into().bits()) } } } impl ops::BitAnd for BitFlags where T: BitFlag, B: Into>, { type Output = BitFlags; #[inline(always)] fn bitand(self, other: B) -> BitFlags { // SAFETY: The two operands are known to be composed of valid bits, // and 0 & 0 = 0 in the columns of the invalid bits. unsafe { BitFlags::from_bits_unchecked(self.bits() & other.into().bits()) } } } impl ops::BitXor for BitFlags where T: BitFlag, B: Into>, { type Output = BitFlags; #[inline(always)] fn bitxor(self, other: B) -> BitFlags { // SAFETY: The two operands are known to be composed of valid bits, // and 0 ^ 0 = 0 in the columns of the invalid bits. unsafe { BitFlags::from_bits_unchecked(self.bits() ^ other.into().bits()) } } } impl ops::BitOrAssign for BitFlags where T: BitFlag, B: Into>, { #[inline(always)] fn bitor_assign(&mut self, other: B) { *self = *self | other; } } impl ops::BitAndAssign for BitFlags where T: BitFlag, B: Into>, { #[inline(always)] fn bitand_assign(&mut self, other: B) { *self = *self & other; } } impl ops::BitXorAssign for BitFlags where T: BitFlag, B: Into>, { #[inline(always)] fn bitxor_assign(&mut self, other: B) { *self = *self ^ other; } } impl ops::Not for BitFlags where T: BitFlag, { type Output = BitFlags; #[inline(always)] fn not(self) -> BitFlags { BitFlags::from_bits_truncate(!self.bits()) } } #[cfg(feature = "serde")] mod impl_serde { use super::{BitFlag, BitFlags}; use serde::de::{Error, Unexpected}; use serde::{Deserialize, Serialize}; impl<'a, T> Deserialize<'a> for BitFlags where T: BitFlag, T::Numeric: Deserialize<'a> + Into, { fn deserialize>(d: D) -> Result { let val = T::Numeric::deserialize(d)?; Self::from_bits(val).map_err(|_| { D::Error::invalid_value( Unexpected::Unsigned(val.into()), &"valid bit representation", ) }) } } impl Serialize for BitFlags where T: BitFlag, T::Numeric: Serialize, { fn serialize(&self, s: S) -> Result { T::Numeric::serialize(&self.val, s) } } }