enumflags2-0.6.4/Cargo.toml.orig010064400017500001746000000014101364767176400147220ustar0000000000000000[package] name = "enumflags2" version = "0.6.4" authors = ["maik klein ", "Jakub \"NieDżejkob\" Kądziołka "] description = "Enum-based bit flags" license = "MIT OR Apache-2.0" repository = "https://github.com/NieDzejkob/enumflags2" readme = "../README.md" keywords = ["enum", "bitflag", "flag", "bitflags"] documentation = "https://docs.rs/enumflags2" edition = "2018" [dependencies.enumflags2_derive] version = "=0.6.4" path = "../enumflags_derive" [dependencies.serde] version = "^1.0.0" default-features = false optional = true [features] std = [] not_literal = ["enumflags2_derive/not_literal"] [dev-dependencies] criterion = "0.3" [[bench]] name = "from_iterator" harness = false path = "../benches/from_iterator.rs" enumflags2-0.6.4/Cargo.toml0000644000000023760000000000000111530ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "enumflags2" version = "0.6.4" authors = ["maik klein ", "Jakub \"NieDżejkob\" Kądziołka "] 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/NieDzejkob/enumflags2" [[bench]] name = "from_iterator" path = "../benches/from_iterator.rs" harness = false [dependencies.enumflags2_derive] version = "=0.6.4" [dependencies.serde] version = "^1.0.0" optional = true default-features = false [dev-dependencies.criterion] version = "0.3" [features] not_literal = ["enumflags2_derive/not_literal"] std = [] enumflags2-0.6.4/LICENSE-APACHE010064400017500001746000000227401364432444100137500ustar0000000000000000Apache 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] [Maik Klein] 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.6.4/LICENSE-MIT010064400017500001746000000020361364432444100134540ustar0000000000000000Copyright (c) 2017 Maik Klein 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.6.4/src/fallible.rs010064400017500001746000000041071364761427000147350ustar0000000000000000use core::convert::TryFrom; use core::fmt; use super::BitFlags; use super::RawBitFlags; // Coherence doesn't let us use a generic type here. Work around by implementing // for each integer type manually. macro_rules! impl_try_from { ($($ty:ty),*) => { $( impl TryFrom<$ty> for BitFlags where T: RawBitFlags, { type Error = FromBitsError; fn try_from(bits: T::Type) -> Result { Self::from_bits(bits) } } )* }; } impl_try_from! { u8, u16, u32, u64, usize } /// The error struct used by [`BitFlags::from_bits`] /// and the [`TryFrom`] implementation` /// for invalid values. /// /// ``` /// # use std::convert::TryInto; /// # use enumflags2::BitFlags; /// #[derive(Clone, Copy, Debug, BitFlags)] /// #[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::Type, } 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::Type { 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.6.4/src/formatting.rs010064400017500001746000000114251364761427000153360ustar0000000000000000use core::fmt::{self, Debug, Binary}; use crate::{BitFlags, RawBitFlags}; impl fmt::Debug for BitFlags where T: RawBitFlags + 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() { let iter = T::flag_list().iter().filter(|&&flag| self.contains(flag)); Some(FlagFormatter(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::Binary for BitFlags where T: RawBitFlags, T::Type: fmt::Binary, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Binary::fmt(&self.bits(), fmt) } } impl fmt::Octal for BitFlags where T: RawBitFlags, T::Type: fmt::Octal, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Octal::fmt(&self.bits(), fmt) } } impl fmt::LowerHex for BitFlags where T: RawBitFlags, T::Type: fmt::LowerHex, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::LowerHex::fmt(&self.bits(), fmt) } } impl fmt::UpperHex for BitFlags where T: RawBitFlags, T::Type: 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 { // convention would print "" or similar here, but this is an // internal API that is never called that way, so just do nothing. Ok(()) } } } // 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.6.4/src/lib.rs010064400017500001746000000274431364767137100137460ustar0000000000000000//! # Enum Flags //! `enumflags2` defines a `BitFlags` type, which is a `Set` //! for enums without associated data. //! //! ## Example //! ``` //! use enumflags2::BitFlags; //! //! #[derive(BitFlags, Copy, Clone, Debug, PartialEq)] //! #[repr(u8)] //! enum Test { //! A = 0b0001, //! B = 0b0010, //! C = 0b0100, //! D = 0b1000, //! } //! //! let a_b = Test::A | Test::B; // BitFlags //! let a_c = Test::A | Test::C; //! let b_c_d = Test::C | Test::B | Test::D; //! //! // BitFlags(0b11, [A, B]) //! println!("{:?}", a_b); //! //! // BitFlags(0b1, [A]) //! println!("{:?}", a_b & a_c); //! //! // Iterate over the flags like a normal set! //! assert_eq!(a_b.iter().collect::>(), &[Test::A, Test::B]); //! //! 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))); //! ``` //! //! ## Note //! //! By default, the `BitFlags` are `usize`-sized. If you want them to be smaller, //! specify a `repr` on your enum as in the example above. //! //! ## Optional Feature Flags //! //! - [`serde`](https://serde.rs/) implements `Serialize` and `Deserialize` //! for `BitFlags`. //! - `std` implements `std::error::Error` for `FromBitsError`. //! - `not_literal` enables a workaround that allows using discriminant //! expressions that can't be evaluated at macro expansion time. Notably, //! this includes using pre-existing constants. //! //! This is disabled by default because of the high potential for confusing //! error messages - if a flag doesn't have exactly one bit set, the error //! message will be "attempt to subtract with overflow", pointing at the //! relevant flag. //! //! ### Migrating from 0.5 //! //! The minimum rustc version has been bumped to 1.34.0, because of `syn 1.0`. The //! version policy from now on will be "what's available on Debian stable", [because //! Debian is famously slow with new software versions][debian-snailpace]. //! //! You should no longer depend on `enumflags2_derive` directly. //! Use the reexport from the `enumflags2` crate. //! semver guarantees will be violated if you depend on the derive crate directly. //! //! The derive macro has been renamed to `BitFlags`, to make it clearer what the //! derive does. //! //! The `nostd` feature flag has been removed. The crate now only depends on `libcore` //! by default. Enable the `std` flag to get an implementation of `std::error::Error` //! on error types. //! //! Flags more than one bit set have been found to have inconsistent semantics. //! They are now rejected at compile-time. The same applies to flags without any //! bit set. If you were relying on this in your code, please [open an issue][issue] //! and explain your usecase. //! //! `BitFlags::from_bits` returns a `Result` instead of an `Option`. This might //! necessitate some minor changes in your code. //! //! `BitFlags::not` has been removed. Use the `!` operator instead. //! //! [debian-snailpace]: https://www.jwz.org/blog/2016/04/i-would-like-debian-to-stop-shipping-xscreensaver/ //! [issue]: https://github.com/NieDzejkob/enumflags2/issues/new #![warn(missing_docs)] #![cfg_attr(all(not(test), not(feature = "std")), no_std)] use core::{cmp, ops}; use core::iter::FromIterator; #[allow(unused_imports)] #[macro_use] extern crate enumflags2_derive; #[doc(hidden)] pub use enumflags2_derive::BitFlags_internal as BitFlags; /// A trait automatically implemented by `derive(BitFlags)` to make the enum /// a valid type parameter for `BitFlags`. pub trait RawBitFlags: Copy + Clone + 'static + _internal::RawBitFlags {} /// While the module is public, this is only the case because it needs to be /// accessed by the derive macro. Do not use this directly. Stability guarantees /// don't apply. #[doc(hidden)] pub mod _internal { /// A trait automatically implemented by `derive(BitFlags)` to make the enum /// a valid type parameter for `BitFlags`. pub trait RawBitFlags: Copy + Clone + 'static { /// The underlying integer type. type Type: BitFlagNum; /// Return a value with all flag bits set. fn all() -> Self::Type; /// Return the bits as a number type. fn bits(self) -> Self::Type; /// Return a slice that contains each variant exactly one. fn flag_list() -> &'static [Self]; /// Return the name of the type for debug formatting purposes. /// /// This is typically `BitFlags` fn bitflags_type_name() -> &'static str { "BitFlags" } } use ::core::ops::{BitAnd, BitOr, BitXor, Not}; use ::core::cmp::PartialOrd; use ::core::fmt; pub trait BitFlagNum : Default + BitOr + BitAnd + BitXor + Not + PartialOrd + fmt::Debug + fmt::Binary + Copy + Clone { } impl BitFlagNum for u8 {} impl BitFlagNum for u16 {} impl BitFlagNum for u32 {} impl BitFlagNum for u64 {} impl BitFlagNum for usize {} // Re-export libcore so the macro doesn't inject "extern crate" downstream. pub mod core { pub use core::{convert, option, ops}; } } // Internal debug formatting implementations mod formatting; // impl TryFrom for BitFlags mod fallible; pub use crate::fallible::FromBitsError; /// Represents a set of flags of some type `T`. /// The type must have the `#[derive(BitFlags)]` attribute applied. #[derive(Copy, Clone, Eq, Hash)] #[repr(transparent)] pub struct BitFlags { val: T::Type, } /// The default value returned is one with all flags unset, i. e. [`empty`][Self::empty]. impl Default for BitFlags where T: RawBitFlags, { fn default() -> Self { Self::empty() } } impl From for BitFlags { fn from(t: T) -> BitFlags { Self::from_flag(t) } } impl BitFlags where T: RawBitFlags, { /// Create a new BitFlags unsafely, without checking if the bits form /// a valid bit pattern for the type. /// /// Consider using `from_bits` or `from_bits_truncate` instead. /// /// # Safety /// /// The argument must not have set bits at positions not corresponding to /// any flag. pub unsafe fn new(val: T::Type) -> Self { BitFlags { val } } /// Create an empty BitFlags. Empty means `0`. pub fn empty() -> Self { unsafe { BitFlags::new(T::Type::default()) } } /// Create a BitFlags with all flags set. pub fn all() -> Self { unsafe { BitFlags::new(T::all()) } } /// Returns true if all flags are set pub fn is_all(self) -> bool { self.val == T::all() } /// Returns true if no flag is set pub fn is_empty(self) -> bool { self.val == Self::empty().bits() } /// Returns the underlying type value pub fn bits(self) -> T::Type { self.val } /// Returns true if at least one flag is shared. pub fn intersects>>(self, other: B) -> bool { (self.bits() & other.into().bits()) > Self::empty().bits() } /// Returns true if all flags are contained. pub fn contains>>(self, other: B) -> bool { let other = other.into(); (self.bits() & other.bits()) == other.bits() } /// Returns a `BitFlags` if the raw value provided does not contain /// any illegal flags. pub fn from_bits(bits: T::Type) -> Result> { let flags = Self::from_bits_truncate(bits); if flags.bits() == bits { Ok(flags) } else { Err(FromBitsError { flags, invalid: bits & !flags.bits(), }) } } /// Turn a `T` into a `BitFlags`. Also available as `flag.into()`. pub fn from_flag(flag: T) -> Self { BitFlags { val: flag.bits() } } /// Truncates flags that are illegal pub fn from_bits_truncate(bits: T::Type) -> Self { unsafe { BitFlags::new(bits & T::all()) } } /// Toggles the matching bits pub fn toggle>>(&mut self, other: B) { *self ^= other.into(); } /// Inserts the flags into the BitFlag pub fn insert>>(&mut self, other: B) { *self |= other.into(); } /// Removes the matching flags pub fn remove>>(&mut self, other: B) { *self &= !other.into(); } /// Returns an iterator that yields each set flag pub fn iter(self) -> impl Iterator { T::flag_list().iter().cloned().filter(move |&flag| self.contains(flag)) } } impl cmp::PartialEq for BitFlags where T: RawBitFlags, B: Into> + Copy, { fn eq(&self, other: &B) -> bool { self.bits() == Into::::into(*other).bits() } } impl ops::BitOr for BitFlags where T: RawBitFlags, B: Into>, { type Output = BitFlags; fn bitor(self, other: B) -> BitFlags { unsafe { BitFlags::new(self.bits() | other.into().bits()) } } } impl ops::BitAnd for BitFlags where T: RawBitFlags, B: Into>, { type Output = BitFlags; fn bitand(self, other: B) -> BitFlags { unsafe { BitFlags::new(self.bits() & other.into().bits()) } } } impl ops::BitXor for BitFlags where T: RawBitFlags, B: Into>, { type Output = BitFlags; fn bitxor(self, other: B) -> BitFlags { unsafe { BitFlags::new((self.bits() ^ other.into().bits()) & T::all()) } } } impl ops::BitOrAssign for BitFlags where T: RawBitFlags, B: Into>, { fn bitor_assign(&mut self, other: B) { *self = *self | other; } } impl ops::BitAndAssign for BitFlags where T: RawBitFlags, B: Into>, { fn bitand_assign(&mut self, other: B) { *self = *self & other; } } impl ops::BitXorAssign for BitFlags where T: RawBitFlags, B: Into>, { fn bitxor_assign(&mut self, other: B) { *self = *self ^ other; } } impl ops::Not for BitFlags where T: RawBitFlags, { type Output = BitFlags; fn not(self) -> BitFlags { unsafe { BitFlags::new(!self.bits() & T::all()) } } } impl FromIterator for BitFlags where T: RawBitFlags, B: Into> { 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: RawBitFlags, B: Into> { fn extend(&mut self, it: I) where I: IntoIterator { *self = it.into_iter().fold(*self, |acc, flag| acc | flag) } } #[cfg(feature = "serde")] mod impl_serde { use serde::{Serialize, Deserialize}; use serde::de::{Error, Unexpected}; use super::{BitFlags, RawBitFlags}; impl<'a, T> Deserialize<'a> for BitFlags where T: RawBitFlags, T::Type: Deserialize<'a> + Into, { fn deserialize>(d: D) -> Result { let val = T::Type::deserialize(d)?; Self::from_bits(val) .or_else(|_| Err(D::Error::invalid_value( Unexpected::Unsigned(val.into()), &"valid bit representation" ))) } } impl Serialize for BitFlags where T: RawBitFlags, T::Type: Serialize, { fn serialize(&self, s: S) -> Result { T::Type::serialize(&self.val, s) } } } enumflags2-0.6.4/tests/bitflag_test.rs010064400017500001746000000000011364432444100161650ustar0000000000000000 enumflags2-0.6.4/.cargo_vcs_info.json0000644000000001120000000000000131370ustar00{ "git": { "sha1": "ad69bd391a75468334ed841dd4ed773467275cc9" } }