enumset-1.1.5/.cargo_vcs_info.json0000644000000001450000000000100125200ustar { "git": { "sha1": "6a9a67676e6ce885a3d3c68f5946d8a5b4a9db7f" }, "path_in_vcs": "enumset" }enumset-1.1.5/Cargo.toml0000644000000036520000000000100105240ustar # 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 = "2021" rust-version = "1.61" name = "enumset" version = "1.1.5" authors = ["Alissa Rao "] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "A library for creating compact sets of enums." documentation = "https://docs.rs/enumset/" readme = "README.md" keywords = [ "enum", "bitset", ] categories = ["data-structures"] license = "MIT/Apache-2.0" repository = "https://github.com/Lymia/enumset" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [lib] name = "enumset" path = "src/lib.rs" [[test]] name = "conversions" path = "tests/conversions.rs" [[test]] name = "ops" path = "tests/ops.rs" [[test]] name = "repr" path = "tests/repr.rs" [[test]] name = "serde" path = "tests/serde.rs" [dependencies.enumset_derive] version = "0.10.0" [dependencies.serde2] version = "1" optional = true default-features = false package = "serde" [dev-dependencies.bincode] version = "1" features = ["i128"] [dev-dependencies.serde_derive] version = "1" [dev-dependencies.serde_json] version = "1" [features] alloc = [] proc-macro-crate = ["enumset_derive/proc-macro-crate"] serde = [ "serde2", "enumset_derive/serde", ] std = [ "alloc", "enumset_derive/proc-macro-crate", "enumset_derive/std_deprecation_warning", ] [badges.maintenance] status = "actively-developed" [badges.travis-ci] branch = "master" repository = "Lymia/enumset" enumset-1.1.5/Cargo.toml.orig000064400000000000000000000021361046102023000142010ustar 00000000000000[package] name = "enumset" version = "1.1.5" authors = ["Alissa Rao "] edition = "2021" rust-version = "1.61" description = "A library for creating compact sets of enums." keywords = ["enum", "bitset"] categories = ["data-structures"] documentation = "https://docs.rs/enumset/" repository = "https://github.com/Lymia/enumset" readme = "README.md" license = "MIT/Apache-2.0" [badges] travis-ci = { repository = "Lymia/enumset", branch = "master" } maintenance = { status = "actively-developed" } [features] serde = ["serde2", "enumset_derive/serde"] alloc = [] proc-macro-crate = ["enumset_derive/proc-macro-crate"] # Deprecated features std = ["alloc", "enumset_derive/proc-macro-crate", "enumset_derive/std_deprecation_warning"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] enumset_derive = { version = "0.10.0", path = "../enumset_derive" } serde2 = { package = "serde", version = "1", default-features = false, optional = true } [dev-dependencies] bincode = { version = "1", features = ["i128"] } serde_derive = "1" serde_json = "1" enumset-1.1.5/LICENSE-APACHE000064400000000000000000000251371046102023000132440ustar 00000000000000 Apache 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: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) 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 (d) 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. enumset-1.1.5/LICENSE-MIT000064400000000000000000000020721046102023000127450ustar 00000000000000Copyright (c) 2017-2023 Alissa Rao 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. enumset-1.1.5/README.md000064400000000000000000000022561046102023000125740ustar 00000000000000# enumset [![Build Status](https://github.com/Lymia/enumset/actions/workflows/test.yml/badge.svg)](https://github.com/Lymia/enumset/actions/workflows/test.yml) [![Latest Version](https://img.shields.io/crates/v/enumset.svg)](https://crates.io/crates/enumset) ![Requires rustc 1.61+](https://img.shields.io/badge/rustc-1.61+-red.svg) [![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/enumset) A library for defining enums that can be used in compact bit sets. It supports `serde` and `#[no_std]` environments, and has basic support for using EnumSets in constants. See [the documentation](https://docs.rs/enumset) for more information. # License This project is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in enumset by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. enumset-1.1.5/src/lib.rs000064400000000000000000000177151046102023000132260ustar 00000000000000#![no_std] #![deny(missing_docs)] #![allow(clippy::missing_safety_doc)] // The safety requirement is "use the procedural derive". #![allow(clippy::needless_range_loop)] // range loop style is clearer in most places in enumset #![cfg_attr(docsrs, feature(doc_cfg))] //! A library for defining enums that can be used in compact bit sets. It supports arbitrarily //! large enums, and has very basic support for using them in constants. //! //! # Cargo Features //! //! The following cargo features are available for this crate: //! //! * `serde`: Allows serialization and deserialization of the types in this crate. //! * `alloc`: Enables the use of functions that requires an allocator. //! * `proc-macro-crate`: Enable the use of the `proc-macro-crate` crate to allow the renaming of //! the `enumset` crate in your user crate. This feature increases the MSRV to 1.69.0 //! //! # Defining enums for use with EnumSet //! //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`: //! //! ```rust //! # use enumset::*; //! #[derive(EnumSetType, Debug)] //! pub enum Enum { //! A, B, C, D, E, F, G, //! } //! ``` //! //! For more information on more advanced use cases, see the documentation for //! [`#[derive(EnumSetType)]`](./derive.EnumSetType.html). //! //! # Working with EnumSets //! //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition, //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so: //! //! ```rust //! # use enumset::*; //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G } //! let new_set = Enum::A | Enum::C | Enum::G; //! assert_eq!(new_set.len(), 3); //! ``` //! //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and //! enums with `#[derive(EnumSetType)]`: //! ```rust //! # use enumset::*; //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G } //! // Intersection of sets //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty()); //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A); //! assert_eq!(Enum::A & Enum::B, EnumSet::empty()); //! //! // Symmetric difference of sets //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C); //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C); //! //! // Difference of sets //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C); //! //! // Complement of sets //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F); //! ``` //! //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts: //! //! ```rust //! # use enumset::*; //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G } //! const CONST_SET: EnumSet = enum_set!(Enum::A | Enum::B); //! assert_eq!(CONST_SET, Enum::A | Enum::B); //! ``` //! //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets: //! //! ```rust //! # use enumset::*; //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G } //! let mut set = EnumSet::new(); //! set.insert(Enum::A); //! set.insert_all(Enum::E | Enum::G); //! assert!(set.contains(Enum::A)); //! assert!(!set.contains(Enum::B)); //! assert_eq!(set, Enum::A | Enum::E | Enum::G); //! ``` #[cfg(feature = "alloc")] extern crate alloc; mod macros; mod repr; mod set; mod traits; pub use crate::macros::__internal; pub use crate::set::{EnumSet, EnumSetIter}; pub use crate::traits::{EnumSetType, EnumSetTypeWithRepr}; /// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with /// [`EnumSet`]. /// /// # Limitations /// /// Currently, the following limitations apply to what kinds of enums this macro may be used with: /// /// * The enum must have no data fields in any variant. /// * Variant discriminators must be zero or positive. /// * No variant discriminator may be larger than `0xFFFFFFBF`. This is chosen to limit problems /// involving overflow and similar edge cases. /// * Variant discriminators must be defined with integer literals. Expressions like `V = 1 + 1` /// are not currently supported. /// /// # Additional Impls /// /// In addition to the implementation of `EnumSetType`, this procedural macro creates multiple /// other impls that are either required for the macro to work, or make the procedural macro more /// ergonomic to use. /// /// A full list of traits implemented as is follows: /// /// * [`Copy`], [`Clone`], [`Eq`], [`PartialEq`] implementations are created to allow `EnumSet` /// to function properly. These automatic implementations may be suppressed using /// `#[enumset(no_super_impls)]`, but these traits must still be implemented in another way. /// * [`PartialEq`], [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] implementations are /// created to allow the crate to be used more ergonomically in expressions. These automatic /// implementations may be suppressed using `#[enumset(no_ops)]`. /// /// # Options /// /// Options are given with `#[enumset(foo)]` annotations attached to the same enum as the derive. /// Multiple options may be given in the same annotation using the `#[enumset(foo, bar)]` syntax. /// /// A full list of options is as follows: /// /// * `#[enumset(no_super_impls)]` prevents the derive from creating implementations required for /// [`EnumSet`] to function. When this attribute is specified, implementations of [`Copy`], /// [`Clone`], [`Eq`], and [`PartialEq`]. This can be useful if you are using a code generator /// that already derives these traits. These impls should function identically to the /// automatically derived versions, or unintentional behavior may be a result. /// * `#[enumset(no_ops)` prevents the derive from implementing any operator traits. /// * `#[enumset(crate_name = "enumset2")]` may be used to change the name of the `enumset` crate /// used in the generated code. When the `std` feature is enabled, enumset parses `Cargo.toml` /// to determine the name of the crate, and this flag is unnecessary. /// * `#[enumset(repr = "u8")]` may be used to specify the in-memory representation of `EnumSet`s /// of this enum type. The effects of this are described in [the `EnumSet` documentation under /// “FFI, Safety and `repr`”][EnumSet#ffi-safety-and-repr]. Allowed types are `u8`, `u16`, `u32`, /// `u64` and `u128`. If this is not used, then the derive macro will choose a type to best fit /// the enum, but there are no guarantees about which type will be chosen. /// * `#[enumset(repr = "array")]` forces the `EnumSet` of this type to be backed with an array, /// even if all the variants could fit into a primitive numeric type. /// /// When the `serde` feature is used, the following features may also be specified. These options /// may be used (with no effect) when building without the feature enabled: /// /// * `#[enumset(serialize_repr = "…")]` may be used to override the way the `EnumSet` is /// serialized. Valid options are `u8`, `u16`, `u32`, `u64`, `list`, `map` and `array`. For more /// information, see the /// ["Serialization" section of the `EnumSet` documentation](EnumSet#serialization). /// * `#[enumset(serialize_deny_unknown)]` causes the generated deserializer to return an error /// for unknown bits instead of silently ignoring them. /// /// # Examples /// /// Deriving a plain EnumSetType: /// /// ```rust /// # use enumset::*; /// #[derive(EnumSetType)] /// pub enum Enum { /// A, B, C, D, E, F, G, /// } /// ``` /// /// Deriving a sparse EnumSetType: /// /// ```rust /// # use enumset::*; /// #[derive(EnumSetType)] /// pub enum SparseEnum { /// A = 10, B = 20, C = 30, D = 127, /// } /// ``` /// /// Deriving an EnumSetType without adding ops: /// /// ```rust /// # use enumset::*; /// #[derive(EnumSetType)] /// #[enumset(no_ops)] /// pub enum NoOpsEnum { /// A, B, C, D, E, F, G, /// } /// ``` /// /// [`Sub`]: core::ops::Sub /// [`BitAnd`]: core::ops::BitAnd /// [`BitOr`]: core::ops::BitOr /// [`BitXor`]: core::ops::BitXor /// [`Not`]: core::ops::Not pub use enumset_derive::EnumSetType; enumset-1.1.5/src/macros.rs000064400000000000000000000164451046102023000137430ustar 00000000000000/// Everything in this module is internal API and may change at any time. #[doc(hidden)] pub mod __internal { /// A reexport of core to allow our macros to be generic to std vs core. pub use ::core as core_export; /// A reexport of serde so our users don't have to also have a serde dependency. #[cfg(feature = "serde")] pub use serde2 as serde; /// Reexports of internal types pub use crate::{ repr::{ArrayRepr, EnumSetTypeRepr}, traits::EnumSetTypePrivate, }; } /// Creates a EnumSet literal, which can be used in const contexts. /// /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same /// type, or an error will occur at compile-time. /// /// This macro accepts trailing `|`s to allow easier use in other macros. /// /// # Examples /// /// ```rust /// # use enumset::*; /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C } /// const CONST_SET: EnumSet = enum_set!(Enum::A | Enum::B); /// assert_eq!(CONST_SET, Enum::A | Enum::B); /// ``` /// /// This macro is strongly typed. For example, the following will not compile: /// /// ```compile_fail /// # use enumset::*; /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C } /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C } /// let type_error = enum_set!(Enum::A | Enum2::B); /// ``` #[macro_export] macro_rules! enum_set { ($(|)*) => { EnumSet::empty() }; ($value:path $(|)*) => { { #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); value } }; ($value:path | $($rest:path)|* $(|)*) => { $crate::enum_set_union!($value, $($rest,)*) }; } /// Computes the union of multiple enums or constants enumset at compile time. /// /// The syntax used is `enum_set_union!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent of /// `ENUM_A | ENUM_B | ENUM_C` at compile time. Each variant must be of the same type, or an error /// will occur at compile-time. /// /// # Examples /// /// ```rust /// # use enumset::*; /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C } /// const CONST_SET: EnumSet = enum_set_union!(Enum::A, Enum::B); /// assert_eq!(CONST_SET, Enum::A | Enum::B); /// ``` #[macro_export] macro_rules! enum_set_union { ($value:path $(,)?) => { $crate::enum_set!($value) }; ($value:path, $($rest:path),* $(,)?) => { { #[allow(deprecated)] let helper = $value.__impl_enumset_internal__const_helper(); #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); $(#[allow(deprecated)] let value = { let new = $rest.__impl_enumset_internal__const_only(); helper.const_union(value, new) };)* value } }; } /// Computes the intersection of multiple enums or constants enumset at compile time. /// /// The syntax used is `enum_set_intersection!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent /// of `ENUM_A & ENUM_B & ENUM_C` at compile time. Each variant must be of the same type, or an /// error will occur at compile-time. /// /// # Examples /// /// ```rust /// # use enumset::*; /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D } /// const SET_A: EnumSet = enum_set!(Enum::A | Enum::B); /// const SET_B: EnumSet = enum_set!(Enum::B | Enum::C); /// const CONST_SET: EnumSet = enum_set_intersection!(SET_A, SET_B); /// assert_eq!(CONST_SET, Enum::B); /// ``` #[macro_export] macro_rules! enum_set_intersection { ($value:path $(,)?) => { $crate::enum_set!($value) }; ($value:path, $($rest:path),* $(,)?) => { { #[allow(deprecated)] let helper = $value.__impl_enumset_internal__const_helper(); #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); $(#[allow(deprecated)] let value = { let new = $rest.__impl_enumset_internal__const_only(); helper.const_intersection(value, new) };)* value } }; } /// Computes the complement of an enums or constants enumset at compile time. /// /// # Examples /// /// ```rust /// # use enumset::*; /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D } /// const SET: EnumSet = enum_set!(Enum::B | Enum::C); /// const CONST_SET: EnumSet = enum_set_complement!(SET); /// assert_eq!(CONST_SET, Enum::A | Enum::D); /// ``` #[macro_export] macro_rules! enum_set_complement { ($value:path $(,)?) => {{ #[allow(deprecated)] let helper = $value.__impl_enumset_internal__const_helper(); #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); helper.const_complement(value) }}; } /// Computes the difference of multiple enums or constants enumset at compile time. /// /// The syntax used is `enum_set_difference!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent /// of `ENUM_A - ENUM_B - ENUM_C` at compile time. Each variant must be of the same type, or an /// error will occur at compile-time. /// /// # Examples /// /// ```rust /// # use enumset::*; /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D } /// const SET_A: EnumSet = enum_set!(Enum::A | Enum::B | Enum::D); /// const SET_B: EnumSet = enum_set!(Enum::B | Enum::C); /// const CONST_SET: EnumSet = enum_set_symmetric_difference!(SET_A, SET_B); /// assert_eq!(CONST_SET, Enum::A | Enum::C | Enum::D); /// ``` #[macro_export] macro_rules! enum_set_difference { ($value:path $(,)?) => { $crate::enum_set!($value) }; ($value:path, $($rest:path),* $(,)?) => { { #[allow(deprecated)] let helper = $value.__impl_enumset_internal__const_helper(); #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); $(#[allow(deprecated)] let value = { let new = $rest.__impl_enumset_internal__const_only(); helper.const_intersection(value, helper.const_complement(new)) };)* value } }; } /// Computes the symmetric difference of multiple enums or constants enumset at compile time. /// /// The syntax used is `enum_set_symmetric_difference!(ENUM_A, ENUM_B, ENUM_C)`, computing the /// equivalent of `ENUM_A ^ ENUM_B ^ ENUM_C` at compile time. Each variant must be of the same /// type, or an error will occur at compile-time. /// /// # Examples /// /// ```rust /// # use enumset::*; /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D } /// const SET_A: EnumSet = EnumSet::all(); /// const SET_B: EnumSet = enum_set!(Enum::B | Enum::C); /// const CONST_SET: EnumSet = enum_set_difference!(SET_A, SET_B); /// assert_eq!(CONST_SET, Enum::A | Enum::D); /// ``` #[macro_export] macro_rules! enum_set_symmetric_difference { ($value:path $(,)?) => { $crate::enum_set!($value) }; ($value:path, $($rest:path),* $(,)?) => { { #[allow(deprecated)] let helper = $value.__impl_enumset_internal__const_helper(); #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); $(#[allow(deprecated)] let value = { let new = $rest.__impl_enumset_internal__const_only(); helper.const_symmetric_difference(value, new) };)* value } }; } enumset-1.1.5/src/repr/array.rs000064400000000000000000000211121046102023000145300ustar 00000000000000use crate::repr::primitive::PrimitiveIter; use crate::repr::EnumSetTypeRepr; use core::ops::*; /// An implementation of `EnumSetTypeRepr` based on an arbitrary size array. /// /// `N` **must** not be `0`, or else everything will break. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)] pub struct ArrayRepr(pub [u64; N]); impl ArrayRepr { fn split_bit(bit: u32) -> (usize, u32) { (bit as usize / 64, bit % 64) } } impl BitAnd for ArrayRepr { type Output = Self; fn bitand(mut self, rhs: Self) -> Self::Output { for i in 0..N { self.0[i] &= rhs.0[i]; } self } } impl BitOr for ArrayRepr { type Output = Self; fn bitor(mut self, rhs: Self) -> Self::Output { for i in 0..N { self.0[i] |= rhs.0[i]; } self } } impl BitXor for ArrayRepr { type Output = Self; fn bitxor(mut self, rhs: Self) -> Self::Output { for i in 0..N { self.0[i] ^= rhs.0[i]; } self } } impl Not for ArrayRepr { type Output = Self; fn not(mut self) -> Self::Output { for i in 0..N { self.0[i] = !self.0[i]; } self } } impl EnumSetTypeRepr for ArrayRepr { const PREFERRED_ARRAY_LEN: usize = N; const WIDTH: u32 = N as u32 * 64; const EMPTY: Self = ArrayRepr([0; N]); fn is_empty(&self) -> bool { self.0.iter().all(|x| *x == 0) } fn add_bit(&mut self, bit: u32) { let (idx, bit) = Self::split_bit(bit); self.0[idx].add_bit(bit); } fn remove_bit(&mut self, bit: u32) { let (idx, bit) = Self::split_bit(bit); self.0[idx].remove_bit(bit); } fn has_bit(&self, bit: u32) -> bool { let (idx, bit) = Self::split_bit(bit); self.0[idx].has_bit(bit) } fn count_ones(&self) -> u32 { self.0.iter().map(|x| x.count_ones()).sum() } fn leading_zeros(&self) -> u32 { let mut accum = 0; for i in (0..N).rev() { if self.0[i] != 0 { return accum + self.0[i].leading_zeros(); } accum += 64; } Self::WIDTH } fn trailing_zeros(&self) -> u32 { let mut accum = 0; for i in 0..N { if self.0[i] != 0 { return accum + self.0[i].trailing_zeros(); } accum += 64; } Self::WIDTH } fn and_not(&self, other: Self) -> Self { let mut new = Self([0; N]); for i in 0..N { new.0[i] = self.0[i] & !other.0[i]; } new } type Iter = ArrayIter; fn iter(self) -> Self::Iter { ArrayIter::new(self) } fn from_u8(v: u8) -> Self { Self::from_u64(v as u64) } fn from_u16(v: u16) -> Self { Self::from_u64(v as u64) } fn from_u32(v: u32) -> Self { Self::from_u64(v as u64) } fn from_u64(v: u64) -> Self { let mut new = Self([0; N]); new.0[0] = v; new } fn from_u128(v: u128) -> Self { let mut new = Self([0; N]); new.0[0] = v as u64; if N != 1 { new.0[1] = (v >> 64) as u64; } new } fn from_usize(v: usize) -> Self { Self::from_u64(v as u64) } fn from_u8_opt(v: u8) -> Option { Some(Self::from_u8(v)) } fn from_u16_opt(v: u16) -> Option { Some(Self::from_u16(v)) } fn from_u32_opt(v: u32) -> Option { Some(Self::from_u32(v)) } fn from_u64_opt(v: u64) -> Option { Some(Self::from_u64(v)) } fn from_u128_opt(v: u128) -> Option { if N == 1 && (v >> 64) != 0 { None } else { Some(Self::from_u128(v)) } } fn from_usize_opt(v: usize) -> Option { Some(Self::from_usize(v)) } fn to_u8(&self) -> u8 { self.to_u64().to_u8() } fn to_u16(&self) -> u16 { self.to_u64().to_u16() } fn to_u32(&self) -> u32 { self.to_u64().to_u32() } fn to_u64(&self) -> u64 { self.0[0] } fn to_u128(&self) -> u128 { let hi = if N == 1 { 0 } else { (self.0[1] as u128) << 64 }; self.0[0] as u128 | hi } fn to_usize(&self) -> usize { self.to_u64().to_usize() } fn to_u8_opt(&self) -> Option { self.to_u64_opt().and_then(|x| x.to_u8_opt()) } fn to_u16_opt(&self) -> Option { self.to_u64_opt().and_then(|x| x.to_u16_opt()) } fn to_u32_opt(&self) -> Option { self.to_u64_opt().and_then(|x| x.to_u32_opt()) } fn to_u64_opt(&self) -> Option { for i in 1..N { if self.0[i] != 0 { return None; } } Some(self.to_u64()) } fn to_u128_opt(&self) -> Option { for i in 2..N { if self.0[i] != 0 { return None; } } Some(self.to_u128()) } fn to_usize_opt(&self) -> Option { self.to_u64_opt().and_then(|x| x.to_usize_opt()) } fn to_u64_array(&self) -> [u64; O] { let mut array = [0; O]; let copy_len = if N < O { N } else { O }; array[..copy_len].copy_from_slice(&self.0[..copy_len]); array } fn to_u64_array_opt(&self) -> Option<[u64; O]> { if N > O { for i in O..N { if self.0[i] != 0 { return None; } } } Some(self.to_u64_array()) } fn from_u64_array(v: [u64; O]) -> Self { ArrayRepr(ArrayRepr::(v).to_u64_array::()) } fn from_u64_array_opt(v: [u64; O]) -> Option { ArrayRepr::(v).to_u64_array_opt::().map(ArrayRepr) } fn to_u64_slice(&self, out: &mut [u64]) { let copy_len = if N < out.len() { N } else { out.len() }; out[..copy_len].copy_from_slice(&self.0[..copy_len]); for i in copy_len..out.len() { out[i] = 0; } } #[must_use] fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()> { if N > out.len() { for i in out.len()..N { if self.0[i] != 0 { return None; } } } self.to_u64_slice(out); Some(()) } fn from_u64_slice(v: &[u64]) -> Self { let mut new = ArrayRepr([0; N]); let copy_len = if N < v.len() { N } else { v.len() }; new.0[..copy_len].copy_from_slice(&v[..copy_len]); new } fn from_u64_slice_opt(v: &[u64]) -> Option { if v.len() > N { for i in N..v.len() { if v[i] != 0 { return None; } } } Some(Self::from_u64_slice(v)) } } #[derive(Clone, Debug)] pub struct ArrayIter { data: [PrimitiveIter; N], done: bool, idx_f: usize, idx_r: usize, } impl ArrayIter { pub fn new(array: ArrayRepr) -> Self { let mut new = [PrimitiveIter(0); N]; for i in 0..N { new[i] = PrimitiveIter(array.0[i]) } ArrayIter { data: new, done: false, idx_f: 0, idx_r: N - 1 } } } impl Iterator for ArrayIter { type Item = u32; fn next(&mut self) -> Option { if self.done { return None; } while self.idx_f <= self.idx_r { if let Some(x) = self.data[self.idx_f].next() { return Some(self.idx_f as u32 * 64 + x); } else { self.idx_f += 1; } } self.done = true; None } fn size_hint(&self) -> (usize, Option) { let mut sum = 0; for i in self.idx_f..self.idx_r + 1 { sum += self.data[i].0.count_ones() as usize; } (sum, Some(sum)) } } impl DoubleEndedIterator for ArrayIter { fn next_back(&mut self) -> Option { if self.done { return None; } while self.idx_f <= self.idx_r { if let Some(x) = self.data[self.idx_r].next_back() { return Some(self.idx_r as u32 * 64 + x); } else { if self.idx_r == 0 { break; } self.idx_r -= 1; } } self.done = true; None } } enumset-1.1.5/src/repr/mod.rs000064400000000000000000000051071046102023000141770ustar 00000000000000#![allow(missing_docs)] mod array; mod primitive; use core::fmt::Debug; use core::hash::Hash; use core::ops::*; /// A trait marking valid underlying bitset storage types and providing the /// operations `EnumSet` and related types use. /// /// # Safety /// /// Note that `iter` *MUST* be implemented correctly and only return bits that /// are actually set in the representation, or else it will cause undefined /// behavior upstream in `EnumSet`. pub trait EnumSetTypeRepr : // Basic traits used to derive traits Copy + Ord + Eq + Debug + Hash + // Operations used by enumset BitAnd + BitOr + BitXor + Not + { const PREFERRED_ARRAY_LEN: usize; const WIDTH: u32; const EMPTY: Self; fn is_empty(&self) -> bool; fn add_bit(&mut self, bit: u32); fn remove_bit(&mut self, bit: u32); fn has_bit(&self, bit: u32) -> bool; fn count_ones(&self) -> u32; fn leading_zeros(&self) -> u32; fn trailing_zeros(&self) -> u32; fn and_not(&self, other: Self) -> Self; type Iter: Iterator + DoubleEndedIterator + Clone + Debug; fn iter(self) -> Self::Iter; fn from_u8(v: u8) -> Self; fn from_u16(v: u16) -> Self; fn from_u32(v: u32) -> Self; fn from_u64(v: u64) -> Self; fn from_u128(v: u128) -> Self; fn from_usize(v: usize) -> Self; fn to_u8(&self) -> u8; fn to_u16(&self) -> u16; fn to_u32(&self) -> u32; fn to_u64(&self) -> u64; fn to_u128(&self) -> u128; fn to_usize(&self) -> usize; fn from_u8_opt(v: u8) -> Option; fn from_u16_opt(v: u16) -> Option; fn from_u32_opt(v: u32) -> Option; fn from_u64_opt(v: u64) -> Option; fn from_u128_opt(v: u128) -> Option; fn from_usize_opt(v: usize) -> Option; fn to_u8_opt(&self) -> Option; fn to_u16_opt(&self) -> Option; fn to_u32_opt(&self) -> Option; fn to_u64_opt(&self) -> Option; fn to_u128_opt(&self) -> Option; fn to_usize_opt(&self) -> Option; fn to_u64_array(&self) -> [u64; O]; fn to_u64_array_opt(&self) -> Option<[u64; O]>; fn from_u64_array(v: [u64; O]) -> Self; fn from_u64_array_opt(v: [u64; O]) -> Option; fn to_u64_slice(&self, out: &mut [u64]); #[must_use] fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()>; fn from_u64_slice(v: &[u64]) -> Self; fn from_u64_slice_opt(v: &[u64]) -> Option; } pub use array::ArrayRepr; enumset-1.1.5/src/repr/primitive.rs000064400000000000000000000234701046102023000154330ustar 00000000000000use crate::repr::EnumSetTypeRepr; macro_rules! prim { ($name:ty, $width:expr, $preferred_array_len:expr) => { const _: () = { fn lo(v: $name) -> u64 { v as u64 } fn hi(v: $name) -> u64 { ((v as u128) >> 64) as u64 } impl EnumSetTypeRepr for $name { const PREFERRED_ARRAY_LEN: usize = $preferred_array_len; const WIDTH: u32 = $width; const EMPTY: Self = 0; #[inline(always)] fn is_empty(&self) -> bool { *self == 0 } #[inline(always)] fn add_bit(&mut self, bit: u32) { *self |= 1 << bit as $name; } #[inline(always)] fn remove_bit(&mut self, bit: u32) { *self &= !(1 << bit as $name); } #[inline(always)] fn has_bit(&self, bit: u32) -> bool { (self & (1 << bit as $name)) != 0 } #[inline(always)] fn count_ones(&self) -> u32 { (*self).count_ones() } #[inline(always)] fn leading_zeros(&self) -> u32 { (*self).leading_zeros() } #[inline(always)] fn trailing_zeros(&self) -> u32 { (*self).trailing_zeros() } #[inline(always)] fn and_not(&self, other: Self) -> Self { (*self) & !other } type Iter = PrimitiveIter; #[inline] fn iter(self) -> Self::Iter { PrimitiveIter(self) } #[inline(always)] fn from_u8(v: u8) -> Self { v as $name } #[inline(always)] fn from_u16(v: u16) -> Self { v as $name } #[inline(always)] fn from_u32(v: u32) -> Self { v as $name } #[inline(always)] fn from_u64(v: u64) -> Self { v as $name } #[inline(always)] fn from_u128(v: u128) -> Self { v as $name } #[inline(always)] fn from_usize(v: usize) -> Self { v as $name } #[inline(always)] fn to_u8(&self) -> u8 { (*self) as u8 } #[inline(always)] fn to_u16(&self) -> u16 { (*self) as u16 } #[inline(always)] fn to_u32(&self) -> u32 { (*self) as u32 } #[inline(always)] fn to_u64(&self) -> u64 { (*self) as u64 } #[inline(always)] fn to_u128(&self) -> u128 { (*self) as u128 } #[inline(always)] fn to_usize(&self) -> usize { (*self) as usize } #[inline(always)] fn from_u8_opt(v: u8) -> Option { v.try_into().ok() } #[inline(always)] fn from_u16_opt(v: u16) -> Option { v.try_into().ok() } #[inline(always)] fn from_u32_opt(v: u32) -> Option { v.try_into().ok() } #[inline(always)] fn from_u64_opt(v: u64) -> Option { v.try_into().ok() } #[inline(always)] fn from_u128_opt(v: u128) -> Option { v.try_into().ok() } #[inline(always)] fn from_usize_opt(v: usize) -> Option { v.try_into().ok() } #[inline(always)] fn to_u8_opt(&self) -> Option { (*self).try_into().ok() } #[inline(always)] fn to_u16_opt(&self) -> Option { (*self).try_into().ok() } #[inline(always)] fn to_u32_opt(&self) -> Option { (*self).try_into().ok() } #[inline(always)] fn to_u64_opt(&self) -> Option { (*self).try_into().ok() } #[inline(always)] fn to_u128_opt(&self) -> Option { (*self).try_into().ok() } #[inline(always)] fn to_usize_opt(&self) -> Option { (*self).try_into().ok() } #[inline(always)] fn to_u64_array(&self) -> [u64; O] { let mut array = [0; O]; if O > 0 { array[0] = lo(*self); } if O > 1 && $preferred_array_len == 2 { array[1] = hi(*self); } array } #[inline(always)] fn to_u64_array_opt(&self) -> Option<[u64; O]> { if O == 0 && *self != 0 { None } else if O == 1 && hi(*self) != 0 { None } else { Some(self.to_u64_array()) } } #[inline(always)] fn from_u64_array(v: [u64; O]) -> Self { if O == 0 { 0 } else if O > 1 && $preferred_array_len == 2 { Self::from_u128(v[0] as u128 | ((v[1] as u128) << 64)) } else { Self::from_u64(v[0]) } } #[inline(always)] fn from_u64_array_opt(v: [u64; O]) -> Option { if O == 0 { Some(0) } else if O == 1 { Self::from_u64_opt(v[0]) } else { for i in 2..O { if v[i] != 0 { return None; } } Self::from_u128_opt(v[0] as u128 | ((v[1] as u128) << 64)) } } #[inline(always)] fn to_u64_slice(&self, out: &mut [u64]) { if out.len() > 0 { out[0] = lo(*self); } if out.len() > 1 && $preferred_array_len == 2 { out[1] = hi(*self); } for i in $preferred_array_len..out.len() { out[i] = 0; } } #[inline(always)] #[must_use] fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()> { if out.len() == 0 && *self != 0 { None } else if out.len() == 1 && hi(*self) != 0 { None } else { self.to_u64_slice(out); Some(()) } } #[inline(always)] fn from_u64_slice(v: &[u64]) -> Self { if v.len() == 0 { 0 } else if v.len() > 1 && $preferred_array_len == 2 { Self::from_u128(v[0] as u128 | ((v[1] as u128) << 64)) } else { Self::from_u64(v[0]) } } #[inline(always)] fn from_u64_slice_opt(v: &[u64]) -> Option { if v.len() == 0 { Some(0) } else if v.len() == 1 { Self::from_u64_opt(v[0]) } else { for i in 2..v.len() { if v[i] != 0 { return None; } } Self::from_u128_opt(v[0] as u128 | ((v[1] as u128) << 64)) } } } }; }; } prim!(u8, 8, 1); prim!(u16, 16, 1); prim!(u32, 32, 1); prim!(u64, 64, 1); prim!(u128, 128, 2); #[derive(Copy, Clone, Debug)] #[repr(transparent)] pub struct PrimitiveIter(pub T); impl Iterator for PrimitiveIter { type Item = u32; fn next(&mut self) -> Option { if self.0.is_empty() { None } else { let bit = self.0.trailing_zeros(); self.0.remove_bit(bit); Some(bit) } } fn size_hint(&self) -> (usize, Option) { let left = self.0.count_ones() as usize; (left, Some(left)) } } impl DoubleEndedIterator for PrimitiveIter { fn next_back(&mut self) -> Option { if self.0.is_empty() { None } else { let bit = T::WIDTH - 1 - self.0.leading_zeros(); self.0.remove_bit(bit); Some(bit) } } } enumset-1.1.5/src/set.rs000064400000000000000000000777671046102023000132700ustar 00000000000000use crate::repr::EnumSetTypeRepr; use crate::traits::EnumSetType; use crate::EnumSetTypeWithRepr; use core::cmp::Ordering; use core::fmt::{Debug, Display, Formatter}; use core::hash::{Hash, Hasher}; use core::iter::Sum; use core::ops::{ BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Sub, SubAssign, }; #[cfg(feature = "serde")] use { serde2 as serde, serde2::{Deserialize, Serialize}, }; /// An efficient set type for enums. /// /// It is implemented using a bitset stored using the smallest integer that can fit all bits /// in the underlying enum. In general, an enum variant with a discriminator of `n` is stored in /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`). /// /// # Numeric representation /// /// `EnumSet` is internally implemented using integer types, and as such can be easily converted /// from and to numbers. /// /// Each bit of the underlying integer corresponds to at most one particular enum variant. If the /// corresponding bit for a variant is set, it present in the set. Bits that do not correspond to /// any variant are always unset. /// /// By default, each enum variant is stored in a bit corresponding to its discriminator. An enum /// variant with a discriminator of `n` is stored in the `n + 1`th least significant bit /// (corresponding to a mask of e.g. `1 << enum as u32`). /// /// # Array representation /// /// Sets with more than 128 variants are instead stored with an underlying array of `u64`s. This /// is treated as if it was a single large integer. The `n`th least significant bit of this integer /// is stored in the `n % 64`th least significant bit of the `n / 64`th element in the array. /// /// # Serialization /// /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using /// the `serde` crate. The exact serialization format can be controlled with additional attributes /// on the enum type. These attributes are valid regardless of whether the `serde` feature /// is enabled. /// /// By default, `EnumSet` is serialized by directly writing out a single integer containing the /// numeric representation of the bitset. The integer type used is the smallest one that can fit /// the largest variant in the enum. If no integer type is large enough, instead the `EnumSet` is /// serialized as an array of `u64`s containing the array representation. /// /// The `#[enumset(serialize_repr = "…")]` attribute can be used to override the representation /// used. Valid values are as follows: /// /// * `u8`, `u16`, `u32`, `u64`, and `u128` serialize the type as the corresponding integer type. /// * `array` serializes the set as an list of `u64`s corresponding to the array representation. /// * `list` serializes the set as a list of enum variants. This requires your enum type implement /// [`Serialize`] and [`Deserialize`]. /// * `map` serializes the set as a map of enum variants to booleans. The set contains a value if /// the boolean is `true`. This requires your enum type implement `Serialize` and `Deserialize`. /// /// The representation used is determined statically at compile time, and there is currently no /// support for reading different formats with the same deserializer. /// /// By default, unknown bits are ignored and silently removed from the bitset. To override this /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause /// deserialization to fail if an invalid bit is set. /// /// # FFI, Safety and `repr` /// /// If an enum type `T` is annotated with /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#options) where `…` is a primitive integer /// type, then several things happen: /// /// * `T` will implement /// [EnumSetTypeWithRepr](crate::traits::EnumSetTypeWithRepr)<Repr = R> in /// addition to [`EnumSetType`]. /// * The `EnumSet` methods with `repr` in their name, such as [`as_repr`][EnumSet::as_repr] and /// [`from_repr`][EnumSet::from_repr], will be available for `EnumSet`. /// * The in-memory representation of `EnumSet` is guaranteed to be `R`. /// /// That last guarantee makes it sound to send `EnumSet` across an FFI boundary. For example: /// /// ``` /// # use enumset::*; /// # /// # mod ffi_impl { /// # // This example “foreign” function is actually written in Rust, but for the sake /// # // of example, we'll pretend it's written in C. /// # #[no_mangle] /// # extern "C" fn some_foreign_function(set: u32) -> u32 { /// # set & 0b100 /// # } /// # } /// # /// extern "C" { /// // This function is written in C like: /// // uint32_t some_foreign_function(uint32_t set) { … } /// fn some_foreign_function(set: EnumSet) -> EnumSet; /// } /// /// #[derive(Debug, EnumSetType)] /// #[enumset(repr = "u32")] /// enum MyEnum { A, B, C } /// /// let set: EnumSet = enum_set!(MyEnum::A | MyEnum::C); /// /// let new_set: EnumSet = unsafe { some_foreign_function(set) }; /// assert_eq!(new_set, enum_set!(MyEnum::C)); /// ``` /// /// When an `EnumSet` is received via FFI, all bits that don't correspond to an enum variant /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`. #[cfg_attr( not(feature = "serde"), doc = "\n\n", doc = "[`Serialize`]: https://docs.rs/serde/latest/serde/trait.Serialize.html\n", doc = "[`Deserialize`]: https://docs.rs/serde/latest/serde/trait.Deserialize.html\n" )] #[derive(Copy, Clone, PartialEq, Eq)] #[repr(transparent)] pub struct EnumSet { #[doc(hidden)] /// This is public due to the `enum_set!` macro. /// This is **NOT** public API and may change at any time. pub __priv_repr: T::Repr, } //region EnumSet operations impl EnumSet { const EMPTY_REPR: Self = EnumSet { __priv_repr: T::Repr::EMPTY }; const ALL_REPR: Self = EnumSet { __priv_repr: T::ALL_BITS }; /// An empty `EnumSet`. /// /// This is deprecated because [`EnumSet::empty`] is now `const`. #[deprecated = "Use `EnumSet::empty()` instead."] pub const EMPTY: Self = Self::EMPTY_REPR; /// An `EnumSet` containing all valid variants of the enum. /// /// This is deprecated because [`EnumSet::all`] is now `const`. #[deprecated = "Use `EnumSet::all()` instead."] pub const ALL: Self = Self::ALL_REPR; /// Creates an empty `EnumSet`. #[inline(always)] pub const fn new() -> Self { Self::EMPTY_REPR } /// Returns an `EnumSet` containing a single element. #[inline(always)] pub fn only(t: T) -> Self { let mut set = Self::new(); set.insert(t); set } /// Creates an empty `EnumSet`. /// /// This is an alias for [`EnumSet::new`]. #[inline(always)] pub const fn empty() -> Self { Self::EMPTY_REPR } /// Returns an `EnumSet` containing all valid variants of the enum. #[inline(always)] pub const fn all() -> Self { Self::ALL_REPR } /// Total number of bits used by this type. Note that the actual amount of space used is /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`). /// /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants. /// (e.g. `enum Foo { A = 10, B = 20 }`) #[inline(always)] pub const fn bit_width() -> u32 { T::BIT_WIDTH } /// The number of valid variants that this type can contain. /// /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants. /// (e.g. `enum Foo { A = 10, B = 20 }`) #[inline(always)] pub const fn variant_count() -> u32 { T::VARIANT_COUNT } /// Returns the number of elements in this set. #[inline(always)] pub fn len(&self) -> usize { self.__priv_repr.count_ones() as usize } /// Returns `true` if the set contains no elements. #[inline(always)] pub fn is_empty(&self) -> bool { self.__priv_repr.is_empty() } /// Removes all elements from the set. #[inline(always)] pub fn clear(&mut self) { self.__priv_repr = T::Repr::EMPTY; } /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to /// checking for an empty intersection. #[inline(always)] pub fn is_disjoint(&self, other: Self) -> bool { (*self & other).is_empty() } /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the /// values in `other`. #[inline(always)] pub fn is_superset(&self, other: Self) -> bool { (*self & other).__priv_repr == other.__priv_repr } /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all /// the values in `self`. #[inline(always)] pub fn is_subset(&self, other: Self) -> bool { other.is_superset(*self) } /// Returns a set containing any elements present in either set. #[inline(always)] pub fn union(&self, other: Self) -> Self { EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr } } /// Returns a set containing every element present in both sets. #[inline(always)] pub fn intersection(&self, other: Self) -> Self { EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr } } /// Returns a set containing element present in `self` but not in `other`. #[inline(always)] pub fn difference(&self, other: Self) -> Self { EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) } } /// Returns a set containing every element present in either `self` or `other`, but is not /// present in both. #[inline(always)] pub fn symmetrical_difference(&self, other: Self) -> Self { EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr } } /// Returns a set containing all enum variants not in this set. #[inline(always)] pub fn complement(&self) -> Self { EnumSet { __priv_repr: !self.__priv_repr & T::ALL_BITS } } /// Checks whether this set contains a value. #[inline(always)] pub fn contains(&self, value: T) -> bool { self.__priv_repr.has_bit(value.enum_into_u32()) } /// Adds a value to this set. /// /// If the set did not have this value present, `true` is returned. /// /// If the set did have this value present, `false` is returned. #[inline(always)] pub fn insert(&mut self, value: T) -> bool { let contains = !self.contains(value); self.__priv_repr.add_bit(value.enum_into_u32()); contains } /// Removes a value from this set. Returns whether the value was present in the set. #[inline(always)] pub fn remove(&mut self, value: T) -> bool { let contains = self.contains(value); self.__priv_repr.remove_bit(value.enum_into_u32()); contains } /// Adds all elements in another set to this one. #[inline(always)] pub fn insert_all(&mut self, other: Self) { self.__priv_repr = self.__priv_repr | other.__priv_repr } /// Removes all values in another set from this one. #[inline(always)] pub fn remove_all(&mut self, other: Self) { self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr); } } #[doc(hidden)] impl EnumSet { /// Creates a new enumset helper. #[deprecated(note = "This method is an internal implementation detail generated by the \ `enumset` crate's procedural macro. It should not be used directly.")] #[doc(hidden)] #[allow(non_snake_case)] pub const fn __impl_enumset_internal__const_helper(&self) -> T::ConstHelper { T::CONST_HELPER_INSTANCE } /// Creates a new enumset with only this variant. #[deprecated(note = "This method is an internal implementation detail generated by the \ `enumset` crate's procedural macro. It should not be used directly.")] #[doc(hidden)] #[allow(non_snake_case)] pub const fn __impl_enumset_internal__const_only(self) -> Self { self } } impl Default for EnumSet { /// Returns an empty set. fn default() -> Self { Self::new() } } impl>> Sub for EnumSet { type Output = Self; #[inline(always)] fn sub(self, other: O) -> Self::Output { self.difference(other.into()) } } impl>> BitAnd for EnumSet { type Output = Self; #[inline(always)] fn bitand(self, other: O) -> Self::Output { self.intersection(other.into()) } } impl>> BitOr for EnumSet { type Output = Self; #[inline(always)] fn bitor(self, other: O) -> Self::Output { self.union(other.into()) } } impl>> BitXor for EnumSet { type Output = Self; #[inline(always)] fn bitxor(self, other: O) -> Self::Output { self.symmetrical_difference(other.into()) } } impl>> SubAssign for EnumSet { #[inline(always)] fn sub_assign(&mut self, rhs: O) { *self = *self - rhs; } } impl>> BitAndAssign for EnumSet { #[inline(always)] fn bitand_assign(&mut self, rhs: O) { *self = *self & rhs; } } impl>> BitOrAssign for EnumSet { #[inline(always)] fn bitor_assign(&mut self, rhs: O) { *self = *self | rhs; } } impl>> BitXorAssign for EnumSet { #[inline(always)] fn bitxor_assign(&mut self, rhs: O) { *self = *self ^ rhs; } } impl Not for EnumSet { type Output = Self; #[inline(always)] fn not(self) -> Self::Output { self.complement() } } impl From for EnumSet { fn from(t: T) -> Self { EnumSet::only(t) } } impl PartialEq for EnumSet { fn eq(&self, other: &T) -> bool { self.__priv_repr == EnumSet::only(*other).__priv_repr } } impl Debug for EnumSet { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let mut is_first = true; // Note: We don't use `.debug_struct` to avoid splitting lines when using `{:x}` f.write_str("EnumSet(")?; for v in self.iter() { if !is_first { f.write_str(" | ")?; } is_first = false; v.fmt(f)?; } f.write_str(")")?; Ok(()) } } impl Display for EnumSet { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let mut is_first = true; for v in self.iter() { if !is_first { f.write_str(" | ")?; } is_first = false; v.fmt(f)?; } Ok(()) } } #[allow(clippy::derived_hash_with_manual_eq)] // This impl exists to change trait bounds only. impl Hash for EnumSet { fn hash(&self, state: &mut H) { self.__priv_repr.hash(state) } } #[allow(clippy::non_canonical_partial_ord_impl)] impl PartialOrd for EnumSet { fn partial_cmp(&self, other: &Self) -> Option { self.__priv_repr.partial_cmp(&other.__priv_repr) } } impl Ord for EnumSet { fn cmp(&self, other: &Self) -> Ordering { self.__priv_repr.cmp(&other.__priv_repr) } } #[cfg(feature = "serde")] impl Serialize for EnumSet { fn serialize(&self, serializer: S) -> Result { T::serialize(*self, serializer) } } #[cfg(feature = "serde")] impl<'de, T: EnumSetType> Deserialize<'de> for EnumSet { fn deserialize>(deserializer: D) -> Result { T::deserialize(deserializer) } } //endregion //region EnumSet conversions impl EnumSet { /// Returns a `T::Repr` representing the elements of this set. /// /// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail, /// panic or truncate any bits. /// /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]` /// annotation. #[inline(always)] pub fn as_repr(&self) -> ::Repr { self.__priv_repr } /// Constructs a bitset from a `T::Repr` without checking for invalid bits. /// /// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail, /// panic or truncate any bits, provided the conditions under “Safety” are upheld. /// /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]` /// annotation. /// /// # Safety /// /// All bits in the provided parameter `bits` that don't correspond to an enum variant of /// `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`. #[inline(always)] pub unsafe fn from_repr_unchecked(bits: ::Repr) -> Self { Self { __priv_repr: bits } } /// Constructs a bitset from a `T::Repr`. /// /// If a bit that doesn't correspond to an enum variant is set, this /// method will panic. /// /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]` /// annotation. #[inline(always)] pub fn from_repr(bits: ::Repr) -> Self { Self::try_from_repr(bits).expect("Bitset contains invalid variants.") } /// Attempts to constructs a bitset from a `T::Repr`. /// /// If a bit that doesn't correspond to an enum variant is set, this /// method will return `None`. /// /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]` /// annotation. #[inline(always)] pub fn try_from_repr(bits: ::Repr) -> Option { let mask = Self::all().__priv_repr; if bits.and_not(mask).is_empty() { Some(EnumSet { __priv_repr: bits }) } else { None } } /// Constructs a bitset from a `T::Repr`, ignoring invalid variants. /// /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]` /// annotation. #[inline(always)] pub fn from_repr_truncated(bits: ::Repr) -> Self { let mask = Self::all().as_repr(); let bits = bits & mask; EnumSet { __priv_repr: bits } } } /// Helper macro for generating conversion functions. macro_rules! conversion_impls { ( $(for_num!( $underlying:ty, $underlying_str:expr, $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident, $from:ident $try_from:ident $from_truncated:ident $from_unchecked:ident, $to:ident $try_to:ident $to_truncated:ident );)* ) => { impl EnumSet {$( #[doc = "Returns a `"] #[doc = $underlying_str] #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \ not fit in a `"] #[doc = $underlying_str] #[doc = "`, this method will panic."] #[inline(always)] pub fn $to(&self) -> $underlying { self.$try_to().expect("Bitset will not fit into this type.") } #[doc = "Tries to return a `"] #[doc = $underlying_str] #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \ not fit in a `"] #[doc = $underlying_str] #[doc = "`, this method will panic."] #[inline(always)] pub fn $try_to(&self) -> Option<$underlying> { EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr) } #[doc = "Returns a truncated `"] #[doc = $underlying_str] #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \ not fit in a `"] #[doc = $underlying_str] #[doc = "`, this method will truncate any bits that don't fit."] #[inline(always)] pub fn $to_truncated(&self) -> $underlying { EnumSetTypeRepr::$to_fn(&self.__priv_repr) } #[doc = "Constructs a bitset from a `"] #[doc = $underlying_str] #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \ method will panic."] #[inline(always)] pub fn $from(bits: $underlying) -> Self { Self::$try_from(bits).expect("Bitset contains invalid variants.") } #[doc = "Attempts to constructs a bitset from a `"] #[doc = $underlying_str] #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \ method will return `None`."] #[inline(always)] pub fn $try_from(bits: $underlying) -> Option { let bits = T::Repr::$from_fn_opt(bits); let mask = T::ALL_BITS; bits.and_then(|bits| if bits.and_not(mask).is_empty() { Some(EnumSet { __priv_repr: bits }) } else { None }) } #[doc = "Constructs a bitset from a `"] #[doc = $underlying_str] #[doc = "`, ignoring bits that do not correspond to a variant."] #[inline(always)] pub fn $from_truncated(bits: $underlying) -> Self { let mask = Self::all().$to_truncated(); let bits = ::$from_fn(bits & mask); EnumSet { __priv_repr: bits } } #[doc = "Constructs a bitset from a `"] #[doc = $underlying_str] #[doc = "`, without checking for invalid bits."] /// /// # Safety /// /// All bits in the provided parameter `bits` that don't correspond to an enum variant /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set /// to `1`. #[inline(always)] pub unsafe fn $from_unchecked(bits: $underlying) -> Self { EnumSet { __priv_repr: ::$from_fn(bits) } } )*} } } conversion_impls! { for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt, from_u8 try_from_u8 from_u8_truncated from_u8_unchecked, as_u8 try_as_u8 as_u8_truncated); for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt, from_u16 try_from_u16 from_u16_truncated from_u16_unchecked, as_u16 try_as_u16 as_u16_truncated); for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt, from_u32 try_from_u32 from_u32_truncated from_u32_unchecked, as_u32 try_as_u32 as_u32_truncated); for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt, from_u64 try_from_u64 from_u64_truncated from_u64_unchecked, as_u64 try_as_u64 as_u64_truncated); for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt, from_u128 try_from_u128 from_u128_truncated from_u128_unchecked, as_u128 try_as_u128 as_u128_truncated); for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt, from_usize try_from_usize from_usize_truncated from_usize_unchecked, as_usize try_as_usize as_usize_truncated); } impl EnumSet { /// Returns an `[u64; O]` representing the elements of this set. /// /// If the underlying bitset will not fit in a `[u64; O]`, this method will panic. pub fn as_array(&self) -> [u64; O] { self.try_as_array() .expect("Bitset will not fit into this type.") } /// Returns an `[u64; O]` representing the elements of this set. /// /// If the underlying bitset will not fit in a `[u64; O]`, this method will instead return /// `None`. pub fn try_as_array(&self) -> Option<[u64; O]> { self.__priv_repr.to_u64_array_opt() } /// Returns an `[u64; O]` representing the elements of this set. /// /// If the underlying bitset will not fit in a `[u64; O]`, this method will truncate any bits /// that don't fit. pub fn as_array_truncated(&self) -> [u64; O] { self.__priv_repr.to_u64_array() } /// Attempts to constructs a bitset from a `[u64; O]`. /// /// If a bit that doesn't correspond to an enum variant is set, this method will panic. pub fn from_array(v: [u64; O]) -> Self { Self::try_from_array(v).expect("Bitset contains invalid variants.") } /// Attempts to constructs a bitset from a `[u64; O]`. /// /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`. pub fn try_from_array(bits: [u64; O]) -> Option { let bits = T::Repr::from_u64_array_opt::(bits); let mask = T::ALL_BITS; bits.and_then(|bits| { if bits.and_not(mask).is_empty() { Some(EnumSet { __priv_repr: bits }) } else { None } }) } /// Constructs a bitset from a `[u64; O]`, ignoring bits that do not correspond to a variant. pub fn from_array_truncated(bits: [u64; O]) -> Self { let bits = T::Repr::from_u64_array(bits) & T::ALL_BITS; EnumSet { __priv_repr: bits } } /// Constructs a bitset from a `[u64; O]`, without checking for invalid bits. /// /// # Safety /// /// All bits in the provided parameter `bits` that don't correspond to an enum variant /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set /// to `1`. #[inline(always)] pub unsafe fn from_array_unchecked(bits: [u64; O]) -> Self { EnumSet { __priv_repr: T::Repr::from_u64_array(bits) } } /// Returns a `Vec` representing the elements of this set. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub fn to_vec(&self) -> alloc::vec::Vec { let mut vec = alloc::vec![0; T::Repr::PREFERRED_ARRAY_LEN]; self.__priv_repr.to_u64_slice(&mut vec); vec } /// Copies the elements of this set into a `&mut [u64]`. /// /// If the underlying bitset will not fit in the provided slice, this method will panic. pub fn copy_into_slice(&self, data: &mut [u64]) { self.try_copy_into_slice(data) .expect("Bitset will not fit into slice.") } /// Copies the elements of this set into a `&mut [u64]`. /// /// If the underlying bitset will not fit in the provided slice, this method will return /// `None`. Otherwise, it will return `Some(())`. #[must_use] pub fn try_copy_into_slice(&self, data: &mut [u64]) -> Option<()> { self.__priv_repr.to_u64_slice_opt(data) } /// Copies the elements of this set into a `&mut [u64]`. /// /// If the underlying bitset will not fit in the provided slice, this method will truncate any /// bits that don't fit. pub fn copy_into_slice_truncated(&self, data: &mut [u64]) { self.__priv_repr.to_u64_slice(data) } /// Attempts to constructs a bitset from a `&[u64]`. /// /// If a bit that doesn't correspond to an enum variant is set, this method will panic. pub fn from_slice(v: &[u64]) -> Self { Self::try_from_slice(v).expect("Bitset contains invalid variants.") } /// Attempts to constructs a bitset from a `&[u64]`. /// /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`. pub fn try_from_slice(bits: &[u64]) -> Option { let bits = T::Repr::from_u64_slice_opt(bits); let mask = T::ALL_BITS; bits.and_then(|bits| { if bits.and_not(mask).is_empty() { Some(EnumSet { __priv_repr: bits }) } else { None } }) } /// Constructs a bitset from a `&[u64]`, ignoring bits that do not correspond to a variant. pub fn from_slice_truncated(bits: &[u64]) -> Self { let bits = T::Repr::from_u64_slice(bits) & T::ALL_BITS; EnumSet { __priv_repr: bits } } /// Constructs a bitset from a `&[u64]`, without checking for invalid bits. /// /// # Safety /// /// All bits in the provided parameter `bits` that don't correspond to an enum variant /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set /// to `1`. #[inline(always)] pub unsafe fn from_slice_unchecked(bits: &[u64]) -> Self { EnumSet { __priv_repr: T::Repr::from_u64_slice(bits) } } } //endregion //region EnumSet iter /// The iterator used by [`EnumSet`]s. #[derive(Clone, Debug)] pub struct EnumSetIter { iter: ::Iter, } impl EnumSetIter { fn new(set: EnumSet) -> EnumSetIter { EnumSetIter { iter: set.__priv_repr.iter() } } } impl EnumSet { /// Iterates the contents of the set in order from the least significant bit to the most /// significant bit. /// /// Note that iterator invalidation is impossible as the iterator contains a copy of this type, /// rather than holding a reference to it. pub fn iter(&self) -> EnumSetIter { EnumSetIter::new(*self) } } impl Iterator for EnumSetIter { type Item = T; fn next(&mut self) -> Option { self.iter.next().map(|x| unsafe { T::enum_from_u32(x) }) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl DoubleEndedIterator for EnumSetIter { fn next_back(&mut self) -> Option { self.iter .next_back() .map(|x| unsafe { T::enum_from_u32(x) }) } } impl ExactSizeIterator for EnumSetIter {} impl Extend for EnumSet { fn extend>(&mut self, iter: I) { iter.into_iter().for_each(|v| { self.insert(v); }); } } impl FromIterator for EnumSet { fn from_iter>(iter: I) -> Self { let mut set = EnumSet::default(); set.extend(iter); set } } impl Extend> for EnumSet { fn extend>>(&mut self, iter: I) { iter.into_iter().for_each(|v| { self.insert_all(v); }); } } impl FromIterator> for EnumSet { fn from_iter>>(iter: I) -> Self { let mut set = EnumSet::default(); set.extend(iter); set } } impl IntoIterator for EnumSet { type Item = T; type IntoIter = EnumSetIter; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl Sum for EnumSet { fn sum>(iter: I) -> Self { iter.fold(EnumSet::empty(), |a, v| a | v) } } impl<'a, T: EnumSetType> Sum<&'a EnumSet> for EnumSet { fn sum>(iter: I) -> Self { iter.fold(EnumSet::empty(), |a, v| a | *v) } } impl Sum for EnumSet { fn sum>(iter: I) -> Self { iter.fold(EnumSet::empty(), |a, v| a | v) } } impl<'a, T: EnumSetType> Sum<&'a T> for EnumSet { fn sum>(iter: I) -> Self { iter.fold(EnumSet::empty(), |a, v| a | *v) } } //endregion enumset-1.1.5/src/traits.rs000064400000000000000000000053451046102023000137620ustar 00000000000000use crate::repr::EnumSetTypeRepr; #[cfg(feature = "serde")] use {crate::EnumSet, serde2 as serde}; /// The trait used to define enum types that may be used with [`EnumSet`]. /// /// This trait must be impelmented using `#[derive(EnumSetType)]`, is not public API, and its /// internal structure may change at any time with no warning. /// /// For full documentation on the procedural derive and its options, see /// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType). /// /// [`EnumSet`]: crate::set::EnumSet pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate {} /// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation. /// /// An implementation of this trait is generated by using /// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType) with the annotation /// `#[enumset(repr = "…")]`, where `…` is `u8`, `u16`, `u32`, `u64` or `u128`. /// /// For any type `T` that implements this trait, the in-memory representation of `EnumSet` /// is guaranteed to be `Repr`. This guarantee is useful for FFI. See [the `EnumSet` documentation /// under “FFI, Safety and `repr`”][crate::set::EnumSet#ffi-safety-and-repr] for an example. /// /// [`EnumSet`]: crate::set::EnumSet pub unsafe trait EnumSetTypeWithRepr: EnumSetType + EnumSetTypePrivate::Repr> { /// The guaranteed representation. type Repr: EnumSetTypeRepr; } /// The actual members of EnumSetType. Put here to avoid polluting global namespaces. pub unsafe trait EnumSetTypePrivate { /// A helper type used to implement the `enum_set!` macro among other things. type ConstHelper; /// The instance of the `ConstHelper`. const CONST_HELPER_INSTANCE: Self::ConstHelper; /// The underlying type used to store the bitset. type Repr: EnumSetTypeRepr; /// A mask of bits that are valid in the bitset. const ALL_BITS: Self::Repr; /// The largest bit used in the bitset. const BIT_WIDTH: u32; /// The number of variants in the bitset. const VARIANT_COUNT: u32; /// Converts an enum of this type into its bit position. fn enum_into_u32(self) -> u32; /// Converts a bit position into an enum value. unsafe fn enum_from_u32(val: u32) -> Self; /// Serializes the `EnumSet`. /// /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive /// can control how `EnumSet` is serialized. #[cfg(feature = "serde")] fn serialize(set: EnumSet, ser: S) -> Result where Self: EnumSetType; /// Deserializes the `EnumSet`. #[cfg(feature = "serde")] fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result, D::Error> where Self: EnumSetType; } enumset-1.1.5/tests/conversions.rs000064400000000000000000000305541046102023000153770ustar 00000000000000#![deny(warnings)] use enumset::*; macro_rules! read_slice { ($set:expr, $size:expr) => {{ let mut arr = [0; $size]; $set.copy_into_slice(&mut arr); arr }}; } macro_rules! try_read_slice { ($set:expr, $size:expr) => {{ let mut arr = [0; $size]; match $set.try_copy_into_slice(&mut arr) { Some(()) => Some(arr), None => None, } }}; } macro_rules! read_slice_truncated { ($set:expr, $size:expr) => {{ let mut arr = [0; $size]; $set.copy_into_slice_truncated(&mut arr); arr }}; } #[derive(EnumSetType, Debug)] pub enum Enum8 { A, B, C, D, E, F, G, // H omitted for non-existent bit test } #[derive(EnumSetType, Debug)] pub enum Enum16 { A, B, C, D, E=8, F, G, H, } #[derive(EnumSetType, Debug)] pub enum Enum32 { A, B, C, D, E=16, F, G, H, } #[derive(EnumSetType, Debug)] pub enum Enum64 { A, B, C, D, E=32, F, G, H, } #[derive(EnumSetType, Debug)] pub enum Enum128 { A, B, C, D, E=64, F, G, H, } #[derive(EnumSetType, Debug)] pub enum Enum192 { A, B, C, D, E=128, F, G, H, } #[derive(EnumSetType, Debug)] pub enum Enum256 { A, B, C, D, E=192, F, G, H, } macro_rules! check_simple_conversion { ($mod:ident, $e:ident) => { mod $mod { use super::*; #[test] fn to_integer() { assert_eq!(7, ($e::A | $e::B | $e::C).as_u8()); assert_eq!(7, ($e::A | $e::B | $e::C).as_u16()); assert_eq!(7, ($e::A | $e::B | $e::C).as_u32()); assert_eq!(7, ($e::A | $e::B | $e::C).as_u64()); assert_eq!(7, ($e::A | $e::B | $e::C).as_u128()); assert_eq!(7, ($e::A | $e::B | $e::C).as_usize()); } #[test] fn try_from_integer() { assert_eq!(Some($e::A | $e::B | $e::C), EnumSet::try_from_u8(7)); assert_eq!(None, EnumSet::<$e>::try_from_u8(7 | (1 << 7))); assert_eq!(None, EnumSet::<$e>::try_from_u16(7 | (1 << 15))); assert_eq!(None, EnumSet::<$e>::try_from_u32(7 | (1 << 31))); assert_eq!(None, EnumSet::<$e>::try_from_usize(7 | (1 << 31))); assert_eq!(None, EnumSet::<$e>::try_from_u64(7 | (1 << 63))); assert_eq!(None, EnumSet::<$e>::try_from_u128(7 | (1 << 127))); } #[test] fn from_integer_truncated() { assert_eq!($e::A | $e::B | $e::C, EnumSet::from_u8_truncated(7)); assert_eq!($e::A | $e::B | $e::C, EnumSet::from_u8_truncated(7 | (1 << 7))); assert_eq!($e::A | $e::B | $e::C, EnumSet::from_u16_truncated(7 | (1 << 15))); assert_eq!($e::A | $e::B | $e::C, EnumSet::from_u32_truncated(7 | (1 << 31))); assert_eq!($e::A | $e::B | $e::C, EnumSet::from_usize_truncated(7 | (1 << 31))); assert_eq!($e::A | $e::B | $e::C, EnumSet::from_u64_truncated(7 | (1 << 63))); assert_eq!($e::A | $e::B | $e::C, EnumSet::from_u128_truncated(7 | (1 << 127))); } #[test] fn basic_to_array() { // array tests assert_eq!(($e::A | $e::B | $e::C).as_array_truncated(), []); assert_eq!(EnumSet::<$e>::empty().as_array_truncated(), []); assert_eq!(($e::A | $e::B | $e::C).as_array(), [7]); assert_eq!(($e::A | $e::B | $e::C).as_array(), [7, 0]); assert_eq!(($e::A | $e::B | $e::C).as_array(), [7, 0, 0]); assert_eq!(($e::A | $e::B | $e::C).as_array(), [7, 0, 0, 0]); assert_eq!(($e::A | $e::B | $e::C).as_array(), [7, 0, 0, 0, 0]); // slice tests assert_eq!(read_slice!($e::A | $e::B | $e::C, 1), [7]); assert_eq!(read_slice!($e::A | $e::B | $e::C, 2), [7, 0]); assert_eq!(read_slice!($e::A | $e::B | $e::C, 3), [7, 0, 0]); assert_eq!(read_slice!($e::A | $e::B | $e::C, 4), [7, 0, 0, 0]); assert_eq!(read_slice!($e::A | $e::B | $e::C, 5), [7, 0, 0, 0, 0]); // slice tests truncated assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 1), [7]); assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 2), [7, 0]); assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 3), [7, 0, 0]); assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 4), [7, 0, 0, 0]); assert_eq!(read_slice_truncated!($e::A | $e::B | $e::C, 5), [7, 0, 0, 0, 0]); } #[test] fn basic_from_array() { // array tests assert_eq!(EnumSet::<$e>::empty(), EnumSet::<$e>::from_array([])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array([7])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array([7, 0, 0])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array([7, 0, 0, 0])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array([7, 0, 0, 0, 0])); // array tests assert_eq!(EnumSet::<$e>::empty(), EnumSet::<$e>::from_slice(&[])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice(&[7])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice(&[7, 0, 0])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice(&[7, 0, 0, 0])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice(&[7, 0, 0, 0, 0])); } #[test] fn basic_from_array_truncated() { // array tests assert_eq!(EnumSet::<$e>::empty(), EnumSet::<$e>::from_array_truncated([])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array_truncated([7 | (1 << 31)])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array_truncated([7, 0, 16])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array_truncated([7, 0, 0, 16])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_array_truncated([7, 0, 0, 0, 16])); // array tests assert_eq!(EnumSet::<$e>::empty(), EnumSet::<$e>::from_slice_truncated(&[])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice_truncated(&[7 | (1 << 31)])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice_truncated(&[7, 0, 16])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice_truncated(&[7, 0, 0, 16])); assert_eq!($e::A | $e::B | $e::C, EnumSet::<$e>::from_slice_truncated(&[7, 0, 0, 0, 16])); } #[test] #[should_panic] fn fail_from_u8() { EnumSet::<$e>::from_u8(7 | (1 << 7)); } #[test] #[should_panic] fn fail_from_u16() { EnumSet::<$e>::from_u16(7 | (1 << 15)); } #[test] #[should_panic] fn fail_from_u32() { EnumSet::<$e>::from_u32(7 | (1 << 31)); } #[test] #[should_panic] fn fail_from_usize() { EnumSet::<$e>::from_usize(7 | (1 << 31)); } #[test] #[should_panic] fn fail_from_u64() { EnumSet::<$e>::from_u64(7 | (1 << 63)); } #[test] #[should_panic] fn fail_from_u128() { EnumSet::<$e>::from_u128(7 | (1 << 127)); } #[test] #[should_panic] fn fail_to_array() { ($e::A | $e::B | $e::C).as_array::<0>(); } #[test] #[should_panic] fn fail_to_slice() { read_slice!($e::A | $e::B | $e::C, 0); } #[test] #[should_panic] fn fail_from_array_1() { EnumSet::<$e>::from_array([7 | (1 << 63), 0, 0, 0]); } #[test] #[should_panic] fn fail_from_slice_1() { EnumSet::<$e>::from_slice(&[7 | (1 << 63), 0, 0, 0]); } #[test] #[should_panic] fn fail_from_array_2() { EnumSet::<$e>::from_array([7, 0, 0, 0, 1]); } #[test] #[should_panic] fn fail_from_slice_2() { EnumSet::<$e>::from_slice(&[7, 0, 0, 0, 1]); } } }; } check_simple_conversion!(enum_8_simple, Enum8); check_simple_conversion!(enum_16_simple, Enum16); check_simple_conversion!(enum_32_simple, Enum32); check_simple_conversion!(enum_64_simple, Enum64); check_simple_conversion!(enum_128_simple, Enum128); check_simple_conversion!(enum_192_simple, Enum192); check_simple_conversion!(enum_256_simple, Enum256); macro_rules! check_oversized_64 { ($mod:ident, $e:ident) => { mod $mod { use super::*; #[test] fn downcast_to_u64() { assert_eq!(Some(7), ($e::A | $e::B | $e::C).try_as_u64()); assert_eq!(Some([7]), ($e::A | $e::B | $e::C).try_as_array()); assert_eq!(Some([7]), try_read_slice!($e::A | $e::B | $e::C, 1)); assert_eq!(None, ($e::E | $e::F | $e::G).try_as_u64()); assert_eq!(None, ($e::E | $e::F | $e::G).try_as_array::<1>()); assert_eq!(None, try_read_slice!($e::E | $e::F | $e::G, 1)); } #[test] fn downcast_to_u64_truncated() { assert_eq!(0, ($e::E | $e::F | $e::G).as_u64_truncated()); assert_eq!([0], ($e::E | $e::F | $e::G).as_array_truncated()); assert_eq!([0], read_slice_truncated!($e::E | $e::F | $e::G, 1)); } #[test] #[should_panic] fn fail_to_u64() { ($e::E | $e::F | $e::G).as_u64(); } } }; } check_oversized_64!(enum_128_oversized_64, Enum128); check_oversized_64!(enum_192_oversized_64, Enum192); check_oversized_64!(enum_256_oversized_64, Enum256); macro_rules! check_oversized_128 { ($mod:ident, $e:ident) => { mod $mod { use super::*; #[test] fn downcast_to_u128() { assert_eq!(Some(7), ($e::A | $e::B | $e::C).try_as_u128()); assert_eq!(None, ($e::E | $e::F | $e::G).try_as_u128()); assert_eq!(0, ($e::E | $e::F | $e::G).as_u128_truncated()); } #[test] #[should_panic] fn fail_to_u128() { ($e::E | $e::F | $e::G).as_u128(); } } }; } check_oversized_128!(enum_192_oversized_128, Enum192); check_oversized_128!(enum_256_oversized_128, Enum256); enumset-1.1.5/tests/ops.rs000064400000000000000000000506571046102023000136360ustar 00000000000000#![allow(dead_code)] #![deny(warnings)] use enumset::*; use std::collections::{HashSet, BTreeSet}; use std::fmt::{Debug, Display, Formatter}; #[derive(EnumSetType, Debug)] pub enum EmptyEnum { } #[derive(EnumSetType, Debug)] pub enum Enum1 { A, } #[derive(EnumSetType, Debug)] enum SmallEnum { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } #[derive(Clone, Copy, Debug, EnumSetType, Eq, PartialEq)] #[enumset(no_super_impls)] enum SmallEnumExplicitDerive { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } #[derive(EnumSetType, Debug)] #[enumset(repr = "u128")] pub enum LargeEnum { _00, _01, _02, _03, _04, _05, _06, _07, _10, _11, _12, _13, _14, _15, _16, _17, _20, _21, _22, _23, _24, _25, _26, _27, _30, _31, _32, _33, _34, _35, _36, _37, _40, _41, _42, _43, _44, _45, _46, _47, _50, _51, _52, _53, _54, _55, _56, _57, _60, _61, _62, _63, _64, _65, _66, _67, _70, _71, _72, _73, _74, _75, _76, _77, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } #[derive(EnumSetType, Debug)] pub enum Enum8 { A, B, C, D, E, F, G, H, } #[derive(EnumSetType, Debug)] pub enum Enum128 { A, B, C, D, E, F, G, H, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78, _79, _80, _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, _91, _92, _93, _94, _95, _96, _97, _98, _99, _100, _101, _102, _103, _104, _105, _106, _107, _108, _109, _110, _111, _112, _113, _114, _115, _116, _117, _118, _119, _120, _121, _122, _123, _124, _125, _126, _127, } #[derive(EnumSetType, Debug)] pub enum SparseEnum { A = 0xA, B = 20, C = 30, D = 40, E = 50, F = 60, G = 70, H = 80, } #[repr(u32)] #[derive(EnumSetType, Debug)] pub enum ReprEnum { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } #[repr(u64)] #[derive(EnumSetType, Debug)] pub enum ReprEnum2 { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } #[repr(isize)] #[derive(EnumSetType, Debug)] pub enum ReprEnum3 { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } #[repr(C)] #[derive(EnumSetType, Debug)] pub enum ReprEnum4 { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } #[derive(EnumSetType, Debug)] pub enum GiantEnum { A = 100, B = 200, C = 300, D = 400, E = 500, F = 600, G = 700, H = 800, } #[derive(EnumSetType, Debug)] #[enumset(repr = "array")] pub enum SmallArrayEnum { A, B, C, D, E, F, G, H } #[derive(EnumSetType, Debug)] #[enumset(repr = "array")] pub enum MarginalArrayEnumS2 { A, B, C, D, E, F, G, H, Marginal = 64, } #[derive(EnumSetType, Debug)] #[enumset(repr = "array")] pub enum MarginalArrayEnumS2H { A = 64, B, C, D, E, F, G, H, Marginal = 127, } #[derive(EnumSetType, Debug)] #[enumset(repr = "array")] pub enum MarginalArrayEnumS3 { A, B, C, D, E, F, G, H, Marginal = 128, } macro_rules! test_variants { ($enum_name:ident $all_empty_test:ident $($variant:ident,)*) => { #[test] fn $all_empty_test() { let all = EnumSet::<$enum_name>::all(); let empty = EnumSet::<$enum_name>::empty(); $( assert!(!empty.contains($enum_name::$variant)); assert!(all.contains($enum_name::$variant)); )* } } } test_variants! { SmallEnum small_enum_all_empty A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } test_variants! { SmallEnumExplicitDerive small_enum_explicit_derive_all_empty A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } test_variants! { LargeEnum large_enum_all_empty _00, _01, _02, _03, _04, _05, _06, _07, _10, _11, _12, _13, _14, _15, _16, _17, _20, _21, _22, _23, _24, _25, _26, _27, _30, _31, _32, _33, _34, _35, _36, _37, _40, _41, _42, _43, _44, _45, _46, _47, _50, _51, _52, _53, _54, _55, _56, _57, _60, _61, _62, _63, _64, _65, _66, _67, _70, _71, _72, _73, _74, _75, _76, _77, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } test_variants! { SparseEnum sparse_enum_all_empty A, B, C, D, E, F, G, } macro_rules! test_enum { ($e:ident, $mem_size:expr) => { const CONST_SET: EnumSet<$e> = enum_set!($e::A | $e::C); const CONST_1_SET: EnumSet<$e> = enum_set!($e::A); const CONST_SET_CHAIN: EnumSet<$e> = enum_set!(CONST_SET | $e::D); const CONST_SET_CHAIN_2: EnumSet<$e> = enum_set!($e::E | CONST_SET); const CONST_SET_CHAIN_3: EnumSet<$e> = enum_set!(CONST_SET_CHAIN | CONST_SET_CHAIN_2); const CONST_UNION: EnumSet<$e> = enum_set_union!(CONST_SET_CHAIN, CONST_SET_CHAIN_2); const CONST_INTERSECTION: EnumSet<$e> = enum_set_intersection!(CONST_SET_CHAIN, CONST_SET_CHAIN_2); const CONST_DIFFERENCE: EnumSet<$e> = enum_set_difference!(CONST_UNION, CONST_SET); const CONST_COMPLEMENT: EnumSet<$e> = enum_set_complement!(CONST_SET); const CONST_SYMMETRIC_DIFFERENCE: EnumSet<$e> = enum_set_symmetric_difference!(CONST_SET_CHAIN, CONST_SET_CHAIN_2); const EMPTY_SET: EnumSet<$e> = EnumSet::empty(); const ALL_SET: EnumSet<$e> = EnumSet::all(); const VARIANT_COUNT: usize = EnumSet::<$e>::variant_count() as usize; #[test] fn const_set() { assert_eq!(CONST_SET, $e::A | $e::C); assert_eq!(CONST_1_SET, $e::A); assert_eq!(CONST_SET_CHAIN, $e::A | $e::C | $e::D); assert_eq!(CONST_SET_CHAIN_2, $e::A | $e::C | $e::E); assert_eq!(CONST_SET_CHAIN_3, $e::A | $e::C | $e::D | $e::E); assert_eq!(CONST_UNION, $e::A | $e::C | $e::D | $e::E); assert_eq!(CONST_INTERSECTION, $e::A | $e::C); assert_eq!(CONST_COMPLEMENT, !($e::A | $e::C)); assert_eq!(CONST_SYMMETRIC_DIFFERENCE, $e::D | $e::E); assert!(EMPTY_SET.is_empty()); assert_eq!(ALL_SET.len(), VARIANT_COUNT); assert_eq!(ALL_SET, EnumSet::all()); } #[test] fn basic_add_remove() { let mut set = EnumSet::new(); set.insert($e::A); set.insert($e::B); set.insert($e::C); assert_eq!(set, $e::A | $e::B | $e::C); set.remove($e::B); assert_eq!(set, $e::A | $e::C); set.insert($e::D); assert_eq!(set, $e::A | $e::C | $e::D); set.insert_all($e::F | $e::E | $e::G); assert_eq!(set, $e::A | $e::C | $e::D | $e::F | $e::E | $e::G); set.remove_all($e::A | $e::D | $e::G); assert_eq!(set, $e::C | $e::F | $e::E); assert!(!set.is_empty()); set.clear(); assert!(set.is_empty()); } #[test] fn already_present_element() { let mut set = EnumSet::new(); assert!(set.insert($e::A)); assert!(!set.insert($e::A)); set.remove($e::A); assert!(set.insert($e::A)); } #[test] fn empty_is_empty() { assert_eq!(EnumSet::<$e>::empty().len(), 0) } #[test] fn all_len() { assert_eq!(EnumSet::<$e>::all().len(), EnumSet::<$e>::variant_count() as usize) } #[test] fn iter_test() { let mut set = EnumSet::new(); set.insert($e::A); set.insert($e::B); set.extend($e::C | $e::E); let mut set_2 = EnumSet::new(); let vec: Vec<_> = set.iter().collect(); for val in vec { assert!(!set_2.contains(val)); set_2.insert(val); } assert_eq!(set, set_2); let mut set_3 = EnumSet::new(); for val in set { assert!(!set_3.contains(val)); set_3.insert(val); } assert_eq!(set, set_3); let mut set_4 = EnumSet::new(); let vec: EnumSet<_> = set.into_iter().map(EnumSet::only).collect(); for val in vec { assert!(!set_4.contains(val)); set_4.insert(val); } assert_eq!(set, set_4); let mut set_5 = EnumSet::new(); let vec: EnumSet<_> = set.iter().collect(); for val in vec { assert!(!set_5.contains(val)); set_5.insert(val); } assert_eq!(set, set_5); } #[test] fn empty_iter_test() { for _ in EnumSet::<$e>::new() { panic!("should not happen"); } } #[test] fn iter_ordering_test() { let set_a = $e::A | $e::B | $e::E; let vec_a: Vec<_> = set_a.iter().collect(); assert_eq!(vec_a, &[$e::A, $e::B, $e::E]); let vec_a_rev: Vec<_> = set_a.iter().rev().collect(); assert_eq!(vec_a_rev, &[$e::E, $e::B, $e::A]); let set_b = $e::B | $e::C | $e::D | $e::G; let vec_b: Vec<_> = set_b.iter().collect(); assert_eq!(vec_b, &[$e::B, $e::C, $e::D, $e::G]); let vec_b_rev: Vec<_> = set_b.iter().rev().collect(); assert_eq!(vec_b_rev, &[$e::G, $e::D, $e::C, $e::B]); } fn check_iter_size_hint(set: EnumSet<$e>) { let count = set.len(); // check for forward iteration { let mut itr = set.iter(); for idx in 0 .. count { assert_eq!(itr.size_hint(), (count-idx, Some(count-idx))); assert_eq!(itr.len(), count-idx); assert!(itr.next().is_some()); } assert_eq!(itr.size_hint(), (0, Some(0))); assert_eq!(itr.len(), 0); } // check for backwards iteration { let mut itr = set.iter().rev(); for idx in 0 .. count { assert_eq!(itr.size_hint(), (count-idx, Some(count-idx))); assert_eq!(itr.len(), count-idx); assert!(itr.next().is_some()); } assert_eq!(itr.size_hint(), (0, Some(0))); assert_eq!(itr.len(), 0); } } #[test] fn test_iter_size_hint() { check_iter_size_hint(EnumSet::<$e>::new()); check_iter_size_hint(EnumSet::<$e>::all()); let mut set = EnumSet::new(); set.insert($e::A); set.insert($e::C); set.insert($e::E); check_iter_size_hint(set); } #[test] fn iter_ops_test() { let set = $e::A | $e::B | $e::C | $e::E; let set2 = set.iter().filter(|&v| v != $e::B).collect::>(); assert_eq!(set2, $e::A | $e::C | $e::E); } #[test] fn basic_ops_test() { assert_eq!(($e::A | $e::B) | ($e::B | $e::C), $e::A | $e::B | $e::C); assert_eq!(($e::A | $e::B) & ($e::B | $e::C), $e::B); assert_eq!(($e::A | $e::B) ^ ($e::B | $e::C), $e::A | $e::C); assert_eq!(($e::A | $e::B) - ($e::B | $e::C), $e::A); assert_eq!($e::A | !$e::A, EnumSet::<$e>::all()); } #[test] fn mutable_ops_test() { let mut set = $e::A | $e::B; assert_eq!(set, $e::A | $e::B); set |= $e::C | $e::D; assert_eq!(set, $e::A | $e::B | $e::C | $e::D); set -= $e::C; assert_eq!(set, $e::A | $e::B | $e::D); set ^= $e::B | $e::E; assert_eq!(set, $e::A | $e::D | $e::E); set &= $e::A | $e::E | $e::F; assert_eq!(set, $e::A | $e::E); } #[test] fn basic_set_status() { assert!(($e::A | $e::B | $e::C).is_disjoint($e::D | $e::E | $e::F)); assert!(!($e::A | $e::B | $e::C | $e::D).is_disjoint($e::D | $e::E | $e::F)); assert!(($e::A | $e::B).is_subset($e::A | $e::B | $e::C)); assert!(!($e::A | $e::D).is_subset($e::A | $e::B | $e::C)); } #[test] fn debug_impl() { assert_eq!(format!("{:?}", $e::A | $e::B | $e::D), "EnumSet(A | B | D)"); } #[test] fn to_from_bits() { let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G; if EnumSet::<$e>::bit_width() < 128 { assert_eq!(EnumSet::from_u128(value.as_u128()), value); } if EnumSet::<$e>::bit_width() < 64 { assert_eq!(EnumSet::from_u64(value.as_u64()), value); } if EnumSet::<$e>::bit_width() < 32 { assert_eq!(EnumSet::from_u32(value.as_u32()), value); } if EnumSet::<$e>::bit_width() < 16 { assert_eq!(EnumSet::from_u16(value.as_u16()), value); } if EnumSet::<$e>::bit_width() < 8 { assert_eq!(EnumSet::from_u8(value.as_u8()), value); } } #[test] #[should_panic] fn too_many_bits() { if EnumSet::<$e>::variant_count() == 128 { panic!("(test skipped)") } EnumSet::<$e>::from_u128(!0); } #[test] fn match_const_test() { match CONST_SET { CONST_SET => { /* ok */ } _ => panic!("match fell through?"), } } #[test] fn set_test() { const SET_TEST_A: EnumSet<$e> = enum_set!($e::A | $e::B | $e::C); const SET_TEST_B: EnumSet<$e> = enum_set!($e::A | $e::B | $e::D); const SET_TEST_C: EnumSet<$e> = enum_set!($e::A | $e::B | $e::E); const SET_TEST_D: EnumSet<$e> = enum_set!($e::A | $e::B | $e::F); const SET_TEST_E: EnumSet<$e> = enum_set!($e::A | $e::B | $e::G); macro_rules! test_set { ($set:ident) => {{ assert!(!$set.contains(&SET_TEST_A)); assert!(!$set.contains(&SET_TEST_B)); assert!(!$set.contains(&SET_TEST_C)); assert!(!$set.contains(&SET_TEST_D)); assert!(!$set.contains(&SET_TEST_E)); $set.insert(SET_TEST_A); $set.insert(SET_TEST_C); assert!($set.contains(&SET_TEST_A)); assert!(!$set.contains(&SET_TEST_B)); assert!($set.contains(&SET_TEST_C)); assert!(!$set.contains(&SET_TEST_D)); assert!(!$set.contains(&SET_TEST_E)); $set.remove(&SET_TEST_C); $set.remove(&SET_TEST_D); assert!($set.contains(&SET_TEST_A)); assert!(!$set.contains(&SET_TEST_B)); assert!(!$set.contains(&SET_TEST_C)); assert!(!$set.contains(&SET_TEST_D)); assert!(!$set.contains(&SET_TEST_E)); $set.insert(SET_TEST_A); $set.insert(SET_TEST_D); assert!($set.contains(&SET_TEST_A)); assert!(!$set.contains(&SET_TEST_B)); assert!(!$set.contains(&SET_TEST_C)); assert!($set.contains(&SET_TEST_D)); assert!(!$set.contains(&SET_TEST_E)); }} } let mut hash_set = HashSet::new(); test_set!(hash_set); let mut tree_set = BTreeSet::new(); test_set!(tree_set); } #[test] fn sum_test() { let target = $e::A | $e::B | $e::D | $e::E | $e::G | $e::H; let list_a = [$e::A | $e::B, $e::D | $e::E, $e::G | $e::H]; let sum_a: EnumSet<$e> = list_a.iter().map(|x| *x).sum(); assert_eq!(target, sum_a); let sum_b: EnumSet<$e> = list_a.iter().sum(); assert_eq!(target, sum_b); let list_b = [$e::A, $e::B, $e::D, $e::E, $e::G, $e::H]; let sum_c: EnumSet<$e> = list_b.iter().map(|x| *x).sum(); assert_eq!(target, sum_c); let sum_d: EnumSet<$e> = list_b.iter().sum(); assert_eq!(target, sum_d); } #[test] fn check_size() { assert_eq!(::std::mem::size_of::>(), $mem_size); } } } macro_rules! tests { ($m:ident, $($tt:tt)*) => { mod $m { use super::*; $($tt)*; } } } tests!(small_enum, test_enum!(SmallEnum, 4)); tests!(small_enum_explicit_derive, test_enum!(SmallEnumExplicitDerive, 4)); tests!(large_enum, test_enum!(LargeEnum, 16)); tests!(enum8, test_enum!(Enum8, 1)); tests!(enum128, test_enum!(Enum128, 16)); tests!(sparse_enum, test_enum!(SparseEnum, 16)); tests!(repr_enum_u32, test_enum!(ReprEnum, 4)); tests!(repr_enum_u64, test_enum!(ReprEnum2, 4)); tests!(repr_enum_isize, test_enum!(ReprEnum3, 4)); tests!(repr_enum_c, test_enum!(ReprEnum4, 4)); tests!(giant_enum, test_enum!(GiantEnum, 104)); tests!(small_array_enum, test_enum!(SmallArrayEnum, 8)); tests!(marginal_array_enum_s2, test_enum!(MarginalArrayEnumS2, 16)); tests!(marginal_array_enum_s2h, test_enum!(MarginalArrayEnumS2H, 16)); tests!(marginal_array_enum_s3, test_enum!(MarginalArrayEnumS3, 24)); #[derive(EnumSetType, Debug)] pub enum ThresholdEnum { A = 1, B, C, D, U8 = 0, U16 = 8, U32 = 16, U64 = 32, U128 = 64, } macro_rules! bits_tests { ( $mod_name:ident, $threshold_expr:expr, ($($too_big_expr:expr),*), $ty:ty, $to:ident $try_to:ident $to_truncated:ident $from:ident $try_from:ident $from_truncated:ident ) => { mod $mod_name { use super::*; use crate::ThresholdEnum::*; #[test] fn to_from_basic() { for &mask in &[ $threshold_expr | B | C | D, $threshold_expr | A | D, $threshold_expr | B | C, ] { assert_eq!(mask, EnumSet::::$from(mask.$to())); assert_eq!(mask.$to_truncated(), mask.$to()); assert_eq!(Some(mask.$to()), mask.$try_to()) } } #[test] #[should_panic] fn from_invalid() { let invalid_mask: $ty = 0x80; EnumSet::::$from(invalid_mask); } #[test] fn try_from_invalid() { assert!(EnumSet::::$try_from(0xFF).is_none()); } $( #[test] fn try_to_overflow() { let set: EnumSet = $too_big_expr.into(); assert!(set.$try_to().is_none()); } )* #[test] fn truncated_overflow() { let trunc_invalid = EnumSet::::$from_truncated(0xFE); assert_eq!(A | B | C | D, trunc_invalid); $( let set: EnumSet = $too_big_expr | A; assert_eq!(2, set.$to_truncated()); )* } } } } bits_tests!(test_u8_bits, U8, (U16), u8, as_u8 try_as_u8 as_u8_truncated from_u8 try_from_u8 from_u8_truncated); bits_tests!(test_u16_bits, U16, (U32), u16, as_u16 try_as_u16 as_u16_truncated from_u16 try_from_u16 from_u16_truncated); bits_tests!(test_u32_bits, U32, (U64), u32, as_u32 try_as_u32 as_u32_truncated from_u32 try_from_u32 from_u32_truncated); bits_tests!(test_u64_bits, U64, (U128), u64, as_u64 try_as_u64 as_u64_truncated from_u64 try_from_u64 from_u64_truncated); bits_tests!(test_u128_bits, U128, (), u128, as_u128 try_as_u128 as_u128_truncated from_u128 try_from_u128 from_u128_truncated); bits_tests!(test_usize_bits, U32, (U128), usize, as_usize try_as_usize as_usize_truncated from_usize try_from_usize from_usize_truncated); impl Display for Enum8 { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Debug::fmt(self, f) } } #[test] fn test_display_impl() { assert_eq!((Enum8::A | Enum8::D | Enum8::H).to_string(), "A | D | H"); } enumset-1.1.5/tests/repr.rs000064400000000000000000000007251046102023000137740ustar 00000000000000#![deny(warnings)] use enumset::*; #[derive(EnumSetType, Debug)] #[enumset(repr = "u16")] enum ReprEnum { A, B, C, D, E, F, G, H, } #[test] fn test() { let mut set = EnumSet::::new(); set.insert(ReprEnum::B); set.insert(ReprEnum::F); let repr: u16 = set.as_repr(); assert_eq!( (1 << 1) | (1 << 5), repr, ); let set2 = unsafe { EnumSet::::from_repr_unchecked(repr) }; assert_eq!(set, set2); } enumset-1.1.5/tests/serde.rs000064400000000000000000000107611046102023000141270ustar 00000000000000#![cfg(feature = "serde")] #![deny(warnings)] #![allow(dead_code)] use enumset::*; use serde_derive::*; // Test resistance against shadowed types. type Some = (); type None = (); type Result = (); #[derive(Serialize, Deserialize, EnumSetType, Debug)] #[enumset(serialize_repr = "list")] #[serde(crate="serde2")] pub enum ListEnum { A, B, C, D, E, F, G, H, } #[derive(Serialize, Deserialize, EnumSetType, Debug)] #[enumset(serialize_repr = "map")] #[serde(crate="serde2")] pub enum MapEnum { A, B, C, D, E, F, G, H, } #[derive(EnumSetType, Debug)] #[enumset(serialize_repr = "array")] pub enum ArrayEnum { A, B, C, D, E, F, G, H, } #[derive(EnumSetType, Debug)] pub enum LargeEnum { A, B, C, D, E=200, F, G, H, } #[derive(EnumSetType, Debug)] #[enumset(serialize_repr = "u128")] pub enum ReprEnum { A, B, C, D, E, F, G, H, } #[derive(EnumSetType, Debug)] #[enumset(serialize_repr = "u128", serialize_deny_unknown)] pub enum DenyUnknownEnum { A, B, C, D, E, F, G, H, } macro_rules! serde_test_simple { ($e:ident, $ser_size:expr) => { const VALUES: &[EnumSet<$e>] = &[ enum_set!(), enum_set!($e::A | $e::C | $e::D | $e::F | $e::E | $e::G), enum_set!($e::A), enum_set!($e::H), enum_set!($e::A | $e::B), enum_set!($e::A | $e::B | $e::C | $e::D), enum_set!($e::A | $e::B | $e::C | $e::D | $e::F | $e::G | $e::H), enum_set!($e::G | $e::H), enum_set!($e::E | $e::F | $e::G | $e::H), ]; #[test] fn serialize_deserialize_test_bincode() { for &value in VALUES { let serialized = bincode::serialize(&value).unwrap(); let deserialized = bincode::deserialize::>(&serialized).unwrap(); assert_eq!(value, deserialized); if $ser_size != !0 { assert_eq!(serialized.len(), $ser_size); } } } #[test] fn serialize_deserialize_test_json() { for &value in VALUES { let serialized = serde_json::to_string(&value).unwrap(); let deserialized = serde_json::from_str::>(&serialized).unwrap(); assert_eq!(value, deserialized); } } } } macro_rules! serde_test { ($e:ident, $ser_size:expr) => { serde_test_simple!($e, $ser_size); #[test] fn deserialize_all_test() { let serialized = bincode::serialize(&!0u128).unwrap(); let deserialized = bincode::deserialize::>(&serialized).unwrap(); assert_eq!(EnumSet::<$e>::all(), deserialized); } } } macro_rules! tests { ($m:ident, $($tt:tt)*) => { mod $m { use super::*; $($tt)*; } } } #[test] fn test_deny_unknown() { let serialized = bincode::serialize(&!0u128).unwrap(); let deserialized = bincode::deserialize::>(&serialized); assert!(deserialized.is_err()); } #[test] fn test_json_reprs_basic() { assert_eq!(ListEnum::A | ListEnum::C | ListEnum::F, serde_json::from_str::>(r#"["A","C","F"]"#).unwrap()); assert_eq!(MapEnum::A | MapEnum::C | MapEnum::F, serde_json::from_str::>(r#"{"A":true,"C":true,"F":true}"#).unwrap()); assert_eq!(ReprEnum::A | ReprEnum::C | ReprEnum::D, serde_json::from_str::>("13").unwrap()); assert_eq!(r#"["A","C","F"]"#, serde_json::to_string(&(ListEnum::A | ListEnum::C | ListEnum::F)).unwrap()); assert_eq!(r#"{"A":true,"C":true,"F":true}"#, serde_json::to_string(&(MapEnum::A | MapEnum::C | MapEnum::F)).unwrap()); assert_eq!("13", serde_json::to_string(&(ReprEnum::A | ReprEnum::C | ReprEnum::D)).unwrap()); } #[test] fn test_json_reprs_edge_cases() { assert_eq!(MapEnum::A | MapEnum::C | MapEnum::F, serde_json::from_str::>(r#"{"D":false,"A":true,"E":false,"C":true,"F":true}"#).unwrap()); assert_eq!(LargeEnum::A | LargeEnum::B | LargeEnum::C | LargeEnum::D, serde_json::from_str::>(r#"[15]"#).unwrap()); } tests!(list_enum, serde_test_simple!(ListEnum, !0)); tests!(map_enum, serde_test_simple!(MapEnum, !0)); tests!(array_enum, serde_test_simple!(ArrayEnum, !0)); tests!(large_enum, serde_test_simple!(LargeEnum, !0)); tests!(repr_enum, serde_test!(ReprEnum, 16)); tests!(deny_unknown_enum, serde_test_simple!(DenyUnknownEnum, 16));