diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:22:09 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:22:09 +0000 |
commit | 43a97878ce14b72f0981164f87f2e35e14151312 (patch) | |
tree | 620249daf56c0258faa40cbdcf9cfba06de2a846 /third_party/rust/enumset | |
parent | Initial commit. (diff) | |
download | firefox-upstream.tar.xz firefox-upstream.zip |
Adding upstream version 110.0.1.upstream/110.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/enumset')
-rw-r--r-- | third_party/rust/enumset/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/enumset/Cargo.toml | 69 | ||||
-rw-r--r-- | third_party/rust/enumset/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | third_party/rust/enumset/LICENSE-MIT | 26 | ||||
-rw-r--r-- | third_party/rust/enumset/README.md | 28 | ||||
-rw-r--r-- | third_party/rust/enumset/src/lib.rs | 971 | ||||
-rw-r--r-- | third_party/rust/enumset/src/repr.rs | 225 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/compile-fail/variants.rs | 65 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/compile-fail/variants.stderr | 77 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/compile-pass/no_imports.rs | 50 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/compile-pass/no_std.rs | 50 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/ops.rs | 462 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/repr.rs | 23 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/serde.rs | 90 | ||||
-rw-r--r-- | third_party/rust/enumset/tests/trybuild.rs | 7 |
15 files changed, 2345 insertions, 0 deletions
diff --git a/third_party/rust/enumset/.cargo-checksum.json b/third_party/rust/enumset/.cargo-checksum.json new file mode 100644 index 0000000000..4c9d7a0dc2 --- /dev/null +++ b/third_party/rust/enumset/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"d0d1787c790db1c5196cb6cc3ce3ed9b670f24d8e10532df4ce1af08b4f446f5","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"79b4502d93c23afe2765054a80d03716d4934eb260cdfbe8c401898df3aa5a8f","README.md":"b4272f04bf647cd6c5d395772a63fa44230df914347ce71f0d2ad7371c7a0bdd","src/lib.rs":"5f0d4ca19512bd146c4d1c1e287385860c7fa4c8906b7eb92843a442c3efea0a","src/repr.rs":"3ec64837ced263c1e2ae3a548b4bed553c85286f6d2b89b4b7dd2358c21d6fcb","tests/compile-fail/variants.rs":"b4b4d8d2a1ea37afb1c478c81a3157d9ea7ab4a2cbf00b7b71386c37f99f2b0b","tests/compile-fail/variants.stderr":"f0d4d9ebcf9cccea04a0796ca2f4a2a81ebaa235f78edf30aeb30a3f232ec1f0","tests/compile-pass/no_imports.rs":"6fa96d43c3970e25dd1e216820dd79f22f5bfe416ce7d6a6df86781797279297","tests/compile-pass/no_std.rs":"e8a402ae12562e6eab4ac531c084278a9dda4ac9b4e64b7a37bb87ce890738e7","tests/ops.rs":"7a00df1ca4a502292f926529d8979e6e3476f48931487088ca50fc869d00e8ff","tests/repr.rs":"a1b792a3b6f71db62b7b26b9b880783b4fd6c905c170c35a0e4b90ccc2a701c9","tests/serde.rs":"8dd9717ee36b26c4b762a258693030ae27e3990625e513694ff3d68af0a131fd","tests/trybuild.rs":"22e03e02452e47976668c3d4ed54322e4d19a95bd1f72647f5d5792b80e8d0f1"},"package":"19be8061a06ab6f3a6cf21106c873578bf01bd42ad15e0311a9c76161cb1c753"}
\ No newline at end of file diff --git a/third_party/rust/enumset/Cargo.toml b/third_party/rust/enumset/Cargo.toml new file mode 100644 index 0000000000..fea0f27b11 --- /dev/null +++ b/third_party/rust/enumset/Cargo.toml @@ -0,0 +1,69 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "enumset" +version = "1.0.12" +authors = ["Alissa Rao <lymia@lymiahugs.com>"] +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" + +[dependencies.enumset_derive] +version = "0.6.1" + +[dependencies.serde2] +version = "1" +optional = true +default-features = false +package = "serde" + +[dev-dependencies.bincode] +version = "1" +features = ["i128"] + +[dev-dependencies.rustversion] +version = "1" + +[dev-dependencies.serde_derive] +version = "1" + +[dev-dependencies.serde_json] +version = "1" + +[dev-dependencies.trybuild] +version = "1" + +[features] +alloc = [] +serde = [ + "serde2", + "enumset_derive/serde", +] +std = [ + "alloc", + "enumset_derive/proc-macro-crate", +] + +[badges.maintenance] +status = "actively-developed" + +[badges.travis-ci] +branch = "master" +repository = "Lymia/enumset" diff --git a/third_party/rust/enumset/LICENSE-APACHE b/third_party/rust/enumset/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/third_party/rust/enumset/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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. diff --git a/third_party/rust/enumset/LICENSE-MIT b/third_party/rust/enumset/LICENSE-MIT new file mode 100644 index 0000000000..58450b341a --- /dev/null +++ b/third_party/rust/enumset/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) 2017-2020 Alissa Rao <lymiahugs@gmail.com> + +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. + diff --git a/third_party/rust/enumset/README.md b/third_party/rust/enumset/README.md new file mode 100644 index 0000000000..ffc7db2268 --- /dev/null +++ b/third_party/rust/enumset/README.md @@ -0,0 +1,28 @@ +# 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.36+](https://img.shields.io/badge/rustc-1.36+-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 enums up to 128 variants, and has a macro to use these sets 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. diff --git a/third_party/rust/enumset/src/lib.rs b/third_party/rust/enumset/src/lib.rs new file mode 100644 index 0000000000..5f098f8f5c --- /dev/null +++ b/third_party/rust/enumset/src/lib.rs @@ -0,0 +1,971 @@ +#![no_std] +#![forbid(missing_docs)] +// The safety requirement is "use the procedural derive". +#![allow(clippy::missing_safety_doc)] + +//! A library for defining enums that can be used in compact bit sets. It supports enums up to 128 +//! variants, and has a macro to use these sets in constants. +//! +//! For serde support, enable the `serde` feature. +//! +//! # 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> = 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); +//! ``` + +use core::cmp::Ordering; +use core::fmt; +use core::fmt::{Debug, Formatter}; +use core::hash::{Hash, Hasher}; +use core::iter::{FromIterator, Sum}; +use core::ops::*; + +#[doc(hidden)] +/// Everything in this module is internal API and may change at any time. +pub mod __internal { + use super::*; + + /// 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 there is no requirement to depend on serde. + #[cfg(feature = "serde")] + pub use serde2 as serde; + + /// The actual members of EnumSetType. Put here to avoid polluting global namespaces. + pub unsafe trait EnumSetTypePrivate { + /// 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; + + /// 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<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error> + where Self: EnumSetType; + /// Deserializes the `EnumSet`. + #[cfg(feature = "serde")] + fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error> + where Self: EnumSetType; + } +} +#[cfg(feature = "serde")] +use crate::__internal::serde; +use crate::__internal::EnumSetTypePrivate; +#[cfg(feature = "serde")] +use crate::serde::{Deserialize, Serialize}; + +mod repr; +use crate::repr::EnumSetTypeRepr; + +/// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with +/// [`EnumSet`]. +/// +/// It may be used with any enum with no data fields, at most 127 variants, and no variant +/// discriminators larger than 127. +/// +/// # 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. +/// +/// 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 = "u8")]` may be used to specify the integer type used to serialize +/// the underlying bitset. Any type allowed in the `repr` option may be used in this option. +/// * `#[enumset(serialize_as_list)]` may be used to serialize the bitset as a list of enum +/// variants instead of an integer. This requires [`Deserialize`] and [`Serialize`] be +/// implemented on the enum. +/// * `#[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, +/// } +/// ``` +pub use enumset_derive::EnumSetType; + +/// 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.EnumSetType.html). +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.EnumSetType.html) 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<T>` +/// is guaranteed to be `Repr`. This guarantee is useful for FFI. See [the `EnumSet` documentation +/// under “FFI, Safety and `repr`”][EnumSet#ffi-safety-and-repr] for an example. +pub unsafe trait EnumSetTypeWithRepr: + EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr> +{ + /// The guaranteed representation. + type Repr: EnumSetTypeRepr; +} + +/// 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`). +/// +/// # 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`s serialize by directly writing out the underlying bitset as an integer +/// of the smallest type that can fit in the underlying enum. You can add a +/// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used +/// for serialization. This can be important for avoiding unintentional breaking changes when +/// `EnumSet`s are serialized with formats like `bincode`. +/// +/// By default, unknown bits are ignored and silently removed from the bitset. To override thris +/// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause +/// deserialization to fail if an invalid bit is set. +/// +/// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be +/// instead serialized as a list of enum variants. This requires your enum type implement +/// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change. +/// +/// # FFI, Safety and `repr` +/// +/// If an enum type `T` is annotated with [`#[enumset(repr = "R")]`][derive@EnumSetType#options], +/// then several things happen: +/// +/// * `T` will implement <code>[EnumSetTypeWithRepr]<Repr = R></code> 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<T>`. +/// * The in-memory representation of `EnumSet<T>` is guaranteed to be `R`. +/// +/// That last guarantee makes it sound to send `EnumSet<T>` 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<MyEnum>) -> EnumSet<MyEnum>; +/// } +/// +/// #[derive(Debug, EnumSetType)] +/// #[enumset(repr = "u32")] +/// enum MyEnum { A, B, C } +/// +/// let set: EnumSet<MyEnum> = enum_set!(MyEnum::A | MyEnum::C); +/// +/// let new_set: EnumSet<MyEnum> = unsafe { some_foreign_function(set) }; +/// assert_eq!(new_set, enum_set!(MyEnum::C)); +/// ``` +/// +/// When an `EnumSet<T>` 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`. +#[derive(Copy, Clone, PartialEq, Eq)] +#[repr(transparent)] +pub struct EnumSet<T: EnumSetType> { + #[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, +} +impl<T: EnumSetType> EnumSet<T> { + // Returns all bits valid for the enum + #[inline(always)] + fn all_bits() -> T::Repr { + T::ALL_BITS + } + + /// Creates an empty `EnumSet`. + #[inline(always)] + pub fn new() -> Self { + EnumSet { __priv_repr: T::Repr::empty() } + } + + /// 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 fn empty() -> Self { + Self::new() + } + + /// Returns an `EnumSet` containing all valid variants of the enum. + #[inline(always)] + pub fn all() -> Self { + EnumSet { __priv_repr: Self::all_bits() } + } + + /// 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 fn bit_width() -> u32 { + T::Repr::WIDTH - T::ALL_BITS.leading_zeros() + } + + /// 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 fn variant_count() -> u32 { + T::ALL_BITS.count_ones() + } + + /// 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 & Self::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); + } + + /// 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<T> { + EnumSetIter::new(*self) + } + + /// 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) -> <T as EnumSetTypeWithRepr>::Repr + where T: EnumSetTypeWithRepr { + 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: <T as EnumSetTypeWithRepr>::Repr) -> Self + where T: EnumSetTypeWithRepr { + 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: <T as EnumSetTypeWithRepr>::Repr) -> Self + where T: EnumSetTypeWithRepr { + 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: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self> + where T: EnumSetTypeWithRepr { + 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: <T as EnumSetTypeWithRepr>::Repr) -> Self + where T: EnumSetTypeWithRepr { + 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 <T : EnumSetType> EnumSet<T> {$( + #[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 = "` or contains bits that do not correspond to an enum variant, 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 = "` or contains bits that do not correspond to an enum variant, this method \ + will instead return `None`."] + #[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 or do not correspond \ + to an enum variant."] + #[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<Self> { + let bits = T::Repr::$from_fn_opt(bits); + let mask = Self::all().__priv_repr; + 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 invalid variants."] + #[inline(always)] + pub fn $from_truncated(bits: $underlying) -> Self { + let mask = Self::all().$to_truncated(); + let bits = <T::Repr as EnumSetTypeRepr>::$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: <T::Repr as EnumSetTypeRepr>::$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<T: EnumSetType> Default for EnumSet<T> { + /// Returns an empty set. + fn default() -> Self { + Self::new() + } +} + +impl<T: EnumSetType> IntoIterator for EnumSet<T> { + type Item = T; + type IntoIter = EnumSetIter<T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} +impl<T: EnumSetType> Sum for EnumSet<T> { + fn sum<I: Iterator<Item = Self>>(iter: I) -> Self { + iter.fold(EnumSet::empty(), |a, v| a | v) + } +} +impl<'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> { + fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self { + iter.fold(EnumSet::empty(), |a, v| a | *v) + } +} +impl<T: EnumSetType> Sum<T> for EnumSet<T> { + fn sum<I: Iterator<Item = T>>(iter: I) -> Self { + iter.fold(EnumSet::empty(), |a, v| a | v) + } +} +impl<'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> { + fn sum<I: Iterator<Item = &'a T>>(iter: I) -> Self { + iter.fold(EnumSet::empty(), |a, v| a | *v) + } +} + +impl<T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> { + type Output = Self; + #[inline(always)] + fn sub(self, other: O) -> Self::Output { + self.difference(other.into()) + } +} +impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> { + type Output = Self; + #[inline(always)] + fn bitand(self, other: O) -> Self::Output { + self.intersection(other.into()) + } +} +impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> { + type Output = Self; + #[inline(always)] + fn bitor(self, other: O) -> Self::Output { + self.union(other.into()) + } +} +impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> { + type Output = Self; + #[inline(always)] + fn bitxor(self, other: O) -> Self::Output { + self.symmetrical_difference(other.into()) + } +} + +impl<T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> { + #[inline(always)] + fn sub_assign(&mut self, rhs: O) { + *self = *self - rhs; + } +} +impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> { + #[inline(always)] + fn bitand_assign(&mut self, rhs: O) { + *self = *self & rhs; + } +} +impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> { + #[inline(always)] + fn bitor_assign(&mut self, rhs: O) { + *self = *self | rhs; + } +} +impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> { + #[inline(always)] + fn bitxor_assign(&mut self, rhs: O) { + *self = *self ^ rhs; + } +} + +impl<T: EnumSetType> Not for EnumSet<T> { + type Output = Self; + #[inline(always)] + fn not(self) -> Self::Output { + self.complement() + } +} + +impl<T: EnumSetType> From<T> for EnumSet<T> { + fn from(t: T) -> Self { + EnumSet::only(t) + } +} + +impl<T: EnumSetType> PartialEq<T> for EnumSet<T> { + fn eq(&self, other: &T) -> bool { + self.__priv_repr == EnumSet::only(*other).__priv_repr + } +} +impl<T: EnumSetType + Debug> Debug for EnumSet<T> { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + let mut is_first = true; + 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(()) + } +} + +#[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only. +impl<T: EnumSetType> Hash for EnumSet<T> { + fn hash<H: Hasher>(&self, state: &mut H) { + self.__priv_repr.hash(state) + } +} +impl<T: EnumSetType> PartialOrd for EnumSet<T> { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + self.__priv_repr.partial_cmp(&other.__priv_repr) + } +} +impl<T: EnumSetType> Ord for EnumSet<T> { + fn cmp(&self, other: &Self) -> Ordering { + self.__priv_repr.cmp(&other.__priv_repr) + } +} + +#[cfg(feature = "serde")] +impl<T: EnumSetType> Serialize for EnumSet<T> { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + T::serialize(*self, serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + T::deserialize(deserializer) + } +} + +/// The iterator used by [`EnumSet`]s. +#[derive(Clone, Debug)] +pub struct EnumSetIter<T: EnumSetType> { + set: EnumSet<T>, +} +impl<T: EnumSetType> EnumSetIter<T> { + fn new(set: EnumSet<T>) -> EnumSetIter<T> { + EnumSetIter { set } + } +} + +impl<T: EnumSetType> Iterator for EnumSetIter<T> { + type Item = T; + + fn next(&mut self) -> Option<Self::Item> { + if self.set.is_empty() { + None + } else { + let bit = self.set.__priv_repr.trailing_zeros(); + self.set.__priv_repr.remove_bit(bit); + unsafe { Some(T::enum_from_u32(bit)) } + } + } + fn size_hint(&self) -> (usize, Option<usize>) { + let left = self.set.len(); + (left, Some(left)) + } +} + +impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> { + fn next_back(&mut self) -> Option<Self::Item> { + if self.set.is_empty() { + None + } else { + let bit = T::Repr::WIDTH - 1 - self.set.__priv_repr.leading_zeros(); + self.set.__priv_repr.remove_bit(bit); + unsafe { Some(T::enum_from_u32(bit)) } + } + } +} + +impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {} + +impl<T: EnumSetType> Extend<T> for EnumSet<T> { + fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { + iter.into_iter().for_each(|v| { + self.insert(v); + }); + } +} + +impl<T: EnumSetType> FromIterator<T> for EnumSet<T> { + fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { + let mut set = EnumSet::default(); + set.extend(iter); + set + } +} + +impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> { + fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) { + iter.into_iter().for_each(|v| { + self.insert_all(v); + }); + } +} + +impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> { + fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self { + let mut set = EnumSet::default(); + set.extend(iter); + set + } +} + +/// 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 a 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> = 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 { + ($(|)*) => { + $crate::EnumSet { __priv_repr: 0 } + }; + ($value:path $(|)*) => { + { + #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); + value + } + }; + ($value:path | $($rest:path)|* $(|)*) => { + { + #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only(); + $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)* + value + } + }; +} diff --git a/third_party/rust/enumset/src/repr.rs b/third_party/rust/enumset/src/repr.rs new file mode 100644 index 0000000000..38546aa8c9 --- /dev/null +++ b/third_party/rust/enumset/src/repr.rs @@ -0,0 +1,225 @@ +use core::convert::TryInto; +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. +pub trait EnumSetTypeRepr : + // Basic traits used to derive traits + Copy + + Ord + + Eq + + Debug + + Hash + + // Operations used by enumset + BitAnd<Output = Self> + + BitOr<Output = Self> + + BitXor<Output = Self> + + Not<Output = Self> + +{ + const WIDTH: u32; + + fn is_empty(&self) -> bool; + fn empty() -> Self; + + 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 count_remaining_ones(&self, cursor: u32) -> usize; + fn leading_zeros(&self) -> u32; + fn trailing_zeros(&self) -> u32; + + fn and_not(&self, other: Self) -> Self; + + 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<Self>; + fn from_u16_opt(v: u16) -> Option<Self>; + fn from_u32_opt(v: u32) -> Option<Self>; + fn from_u64_opt(v: u64) -> Option<Self>; + fn from_u128_opt(v: u128) -> Option<Self>; + fn from_usize_opt(v: usize) -> Option<Self>; + + fn to_u8_opt(&self) -> Option<u8>; + fn to_u16_opt(&self) -> Option<u16>; + fn to_u32_opt(&self) -> Option<u32>; + fn to_u64_opt(&self) -> Option<u64>; + fn to_u128_opt(&self) -> Option<u128>; + fn to_usize_opt(&self) -> Option<usize>; +} +macro_rules! prim { + ($name:ty, $width:expr) => { + impl EnumSetTypeRepr for $name { + const WIDTH: u32 = $width; + + #[inline(always)] + fn is_empty(&self) -> bool { + *self == 0 + } + #[inline(always)] + fn empty() -> 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 + } + + #[inline(always)] + fn count_remaining_ones(&self, cursor: u32) -> usize { + let left_mask = !((1 as $name) + .checked_shl(cursor) + .unwrap_or(0) + .wrapping_sub(1)); + (*self & left_mask).count_ones() as usize + } + + #[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<Self> { + v.try_into().ok() + } + #[inline(always)] + fn from_u16_opt(v: u16) -> Option<Self> { + v.try_into().ok() + } + #[inline(always)] + fn from_u32_opt(v: u32) -> Option<Self> { + v.try_into().ok() + } + #[inline(always)] + fn from_u64_opt(v: u64) -> Option<Self> { + v.try_into().ok() + } + #[inline(always)] + fn from_u128_opt(v: u128) -> Option<Self> { + v.try_into().ok() + } + #[inline(always)] + fn from_usize_opt(v: usize) -> Option<Self> { + v.try_into().ok() + } + + #[inline(always)] + fn to_u8_opt(&self) -> Option<u8> { + (*self).try_into().ok() + } + #[inline(always)] + fn to_u16_opt(&self) -> Option<u16> { + (*self).try_into().ok() + } + #[inline(always)] + fn to_u32_opt(&self) -> Option<u32> { + (*self).try_into().ok() + } + #[inline(always)] + fn to_u64_opt(&self) -> Option<u64> { + (*self).try_into().ok() + } + #[inline(always)] + fn to_u128_opt(&self) -> Option<u128> { + (*self).try_into().ok() + } + #[inline(always)] + fn to_usize_opt(&self) -> Option<usize> { + (*self).try_into().ok() + } + } + }; +} +prim!(u8, 8); +prim!(u16, 16); +prim!(u32, 32); +prim!(u64, 64); +prim!(u128, 128); diff --git a/third_party/rust/enumset/tests/compile-fail/variants.rs b/third_party/rust/enumset/tests/compile-fail/variants.rs new file mode 100644 index 0000000000..2b76a40897 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/variants.rs @@ -0,0 +1,65 @@ +use enumset::*; + +#[derive(EnumSetType)] +enum VariantOver127 { + Variant = 128, +} + +#[derive(EnumSetType)] +#[repr(i64)] +enum VariantOverU32 { + Variant = 0x100000000, +} + +#[derive(EnumSetType)] +enum TooManyVariants { + _0, _1, _2, _3, _4, _5, _6, _7, _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, _128, +} + +#[derive(EnumSetType)] +enum NegativeVariant { + Variant = -1, +} + +#[derive(EnumSetType)] +#[repr(usize)] +enum BadRepr { + Variant, +} + +#[derive(EnumSetType)] +enum HasFields { + Variant(u32), +} + +#[derive(EnumSetType)] +#[enumset(serialize_repr = "u8")] +enum BadSerializationRepr { + Variant = 8, +} + +#[derive(EnumSetType)] +struct BadItemType { + +} + +#[derive(EnumSetType)] +#[enumset(repr = "u16")] +enum BadMemRepr { + Variant = 16, +} + +#[derive(EnumSetType)] +enum OkayEnumButCantUseFromRepr { + Variant, +} + +fn main() { + EnumSet::<OkayEnumButCantUseFromRepr>::from_repr(1); +} diff --git a/third_party/rust/enumset/tests/compile-fail/variants.stderr b/third_party/rust/enumset/tests/compile-fail/variants.stderr new file mode 100644 index 0000000000..d243048b92 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/variants.stderr @@ -0,0 +1,77 @@ +error: `#[derive(EnumSetType)]` currently only supports discriminants up to 127. + --> tests/compile-fail/variants.rs:5:5 + | +5 | Variant = 128, + | ^^^^^^^^^^^^^ + +error: Enum set discriminants must be `u32`s. (larger discrimiants are still unsupported with reprs that allow them.) + --> tests/compile-fail/variants.rs:11:15 + | +11 | Variant = 0x100000000, + | ^^^^^^^^^^^ + +error: `#[derive(EnumSetType)]` currently only supports enums up to 128 variants. + --> tests/compile-fail/variants.rs:22:95 + | +22 | _113, _114, _115, _116, _117, _118, _119, _120, _121, _122, _123, _124, _125, _126, _127, _128, + | ^^^^ + +error: Enum set discriminants must be `u32`s. + --> tests/compile-fail/variants.rs:27:5 + | +27 | Variant = -1, + | ^^^^^^^^^^^^ + +error: `#[derive(EnumSetType)]` can only be used on fieldless enums. + --> tests/compile-fail/variants.rs:38:5 + | +38 | Variant(u32), + | ^^^^^^^^^^^^ + +error: serialize_repr cannot be smaller than bitset. + --> tests/compile-fail/variants.rs:41:10 + | +41 | #[derive(EnumSetType)] + | ^^^^^^^^^^^ + | + = note: this error originates in the derive macro `EnumSetType` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: `#[derive(EnumSetType)]` may only be used on enums + --> tests/compile-fail/variants.rs:48:1 + | +48 | / struct BadItemType { +49 | | +50 | | } + | |_^ + +error: repr cannot be smaller than bitset. + --> tests/compile-fail/variants.rs:52:10 + | +52 | #[derive(EnumSetType)] + | ^^^^^^^^^^^ + | + = note: this error originates in the derive macro `EnumSetType` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `OkayEnumButCantUseFromRepr: EnumSetTypeWithRepr` is not satisfied + --> tests/compile-fail/variants.rs:64:5 + | +64 | EnumSet::<OkayEnumButCantUseFromRepr>::from_repr(1); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `EnumSetTypeWithRepr` is not implemented for `OkayEnumButCantUseFromRepr` + | +note: required by a bound in `enumset::EnumSet::<T>::from_repr` + --> src/lib.rs + | + | where T: EnumSetTypeWithRepr { + | ^^^^^^^^^^^^^^^^^^^ required by this bound in `enumset::EnumSet::<T>::from_repr` + +error[E0277]: the trait bound `OkayEnumButCantUseFromRepr: EnumSetTypeWithRepr` is not satisfied + --> tests/compile-fail/variants.rs:64:5 + | +64 | EnumSet::<OkayEnumButCantUseFromRepr>::from_repr(1); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `EnumSetTypeWithRepr` is not implemented for `OkayEnumButCantUseFromRepr` + +error[E0277]: the trait bound `OkayEnumButCantUseFromRepr: EnumSetTypeWithRepr` is not satisfied + --> tests/compile-fail/variants.rs:64:54 + | +64 | EnumSet::<OkayEnumButCantUseFromRepr>::from_repr(1); + | ^ the trait `EnumSetTypeWithRepr` is not implemented for `OkayEnumButCantUseFromRepr` diff --git a/third_party/rust/enumset/tests/compile-pass/no_imports.rs b/third_party/rust/enumset/tests/compile-pass/no_imports.rs new file mode 100644 index 0000000000..ce5bbd1265 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-pass/no_imports.rs @@ -0,0 +1,50 @@ +#![no_std] +#![allow(dead_code)] + +extern crate std as __renamed_std; // so we don't have compile issues, but ::std still errors. + +use enumset::EnumSetType; + +#[derive(EnumSetType)] +pub enum EmptyEnum { } + +#[derive(EnumSetType)] +pub enum Enum1 { + A, +} + +#[derive(EnumSetType)] +pub 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(EnumSetType)] +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)] +pub enum SparseEnum { + A = 0xA, B = 20, C = 30, D = 40, E = 50, F = 60, G = 70, H = 80, +} + +#[repr(u32)] +#[derive(EnumSetType)] +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(C)] +#[derive(EnumSetType)] +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, +} + +pub fn main() { + +} diff --git a/third_party/rust/enumset/tests/compile-pass/no_std.rs b/third_party/rust/enumset/tests/compile-pass/no_std.rs new file mode 100644 index 0000000000..9d389a4acd --- /dev/null +++ b/third_party/rust/enumset/tests/compile-pass/no_std.rs @@ -0,0 +1,50 @@ +#![no_std] +#![allow(dead_code)] + +extern crate std as __renamed_std; // so we don't have compile issues, but ::std still errors. + +use enumset::*; + +#[derive(EnumSetType)] +pub enum EmptyEnum { } + +#[derive(EnumSetType)] +pub enum Enum1 { + A, +} + +#[derive(EnumSetType)] +pub 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(EnumSetType)] +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)] +pub enum SparseEnum { + A = 0xA, B = 20, C = 30, D = 40, E = 50, F = 60, G = 70, H = 80, +} + +#[repr(u32)] +#[derive(EnumSetType)] +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(C)] +#[derive(EnumSetType)] +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, +} + +pub fn main() { + +} diff --git a/third_party/rust/enumset/tests/ops.rs b/third_party/rust/enumset/tests/ops.rs new file mode 100644 index 0000000000..0e71378431 --- /dev/null +++ b/third_party/rust/enumset/tests/ops.rs @@ -0,0 +1,462 @@ +#![allow(dead_code)] + +use enumset::*; +use std::collections::{HashSet, BTreeSet}; + +#[derive(EnumSetType, Debug)] +pub enum EmptyEnum { } + +#[derive(EnumSetType, Debug)] +pub enum Enum1 { + A, +} + +#[derive(EnumSetType, Debug)] +pub 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)] +pub 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)] +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, +} + +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 EMPTY_SET: EnumSet<$e> = enum_set!(); + #[test] + fn const_set() { + assert_eq!(CONST_SET.len(), 2); + assert_eq!(CONST_1_SET.len(), 1); + assert!(CONST_SET.contains($e::A)); + assert!(CONST_SET.contains($e::C)); + assert!(EMPTY_SET.is_empty()); + } + + #[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 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(); + 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); + } + #[test] + fn test_iter_size_hint() { + 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::<EnumSet<_>>(); + 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; + assert_eq!(EnumSet::from_u128(value.as_u128()), 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::<EnumSet<$e>>(), $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)); + +#[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::<ThresholdEnum>::$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::<ThresholdEnum>::$from(invalid_mask); + } + + #[test] + fn try_from_invalid() { + assert!(EnumSet::<ThresholdEnum>::$try_from(0xFF).is_none()); + } + + $( + #[test] + fn try_to_overflow() { + let set: EnumSet<ThresholdEnum> = $too_big_expr.into(); + assert!(set.$try_to().is_none()); + } + )* + + #[test] + fn truncated_overflow() { + let trunc_invalid = EnumSet::<ThresholdEnum>::$from_truncated(0xFE); + assert_eq!(A | B | C | D, trunc_invalid); + $( + let set: EnumSet<ThresholdEnum> = $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_uize_bits, U32, (U128), usize, + as_usize try_as_usize as_usize_truncated + from_usize try_from_usize from_usize_truncated);
\ No newline at end of file diff --git a/third_party/rust/enumset/tests/repr.rs b/third_party/rust/enumset/tests/repr.rs new file mode 100644 index 0000000000..c7d9d7baa6 --- /dev/null +++ b/third_party/rust/enumset/tests/repr.rs @@ -0,0 +1,23 @@ +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::<ReprEnum>::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::<ReprEnum>::from_repr_unchecked(repr) }; + assert_eq!(set, set2); +} diff --git a/third_party/rust/enumset/tests/serde.rs b/third_party/rust/enumset/tests/serde.rs new file mode 100644 index 0000000000..c67ebf3fae --- /dev/null +++ b/third_party/rust/enumset/tests/serde.rs @@ -0,0 +1,90 @@ +#![cfg(feature = "serde")] +#![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_as_list)] +#[serde(crate="serde2")] +pub enum ListEnum { + A, B, C, D, E, 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) => { + #[test] + fn serialize_deserialize_test_bincode() { + let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G; + let serialized = bincode::serialize(&value).unwrap(); + let deserialized = bincode::deserialize::<EnumSet<$e>>(&serialized).unwrap(); + assert_eq!(value, deserialized); + if $ser_size != !0 { + assert_eq!(serialized.len(), $ser_size); + } + } + + #[test] + fn serialize_deserialize_test_json() { + let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G; + let serialized = serde_json::to_string(&value).unwrap(); + let deserialized = serde_json::from_str::<EnumSet<$e>>(&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::<EnumSet<$e>>(&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::<EnumSet<DenyUnknownEnum>>(&serialized); + assert!(deserialized.is_err()); +} + +#[test] +fn test_json_reprs() { + assert_eq!(ListEnum::A | ListEnum::C | ListEnum::F, + serde_json::from_str::<EnumSet<ListEnum>>(r#"["A","C","F"]"#).unwrap()); + assert_eq!(ReprEnum::A | ReprEnum::C | ReprEnum::D, + serde_json::from_str::<EnumSet<ReprEnum>>("13").unwrap()); + assert_eq!(r#"["A","C","F"]"#, + serde_json::to_string(&(ListEnum::A | ListEnum::C | ListEnum::F)).unwrap()); + assert_eq!("13", + serde_json::to_string(&(ReprEnum::A | ReprEnum::C | ReprEnum::D)).unwrap()); +} + +tests!(list_enum, serde_test_simple!(ListEnum, !0)); +tests!(repr_enum, serde_test!(ReprEnum, 16)); +tests!(deny_unknown_enum, serde_test_simple!(DenyUnknownEnum, 16)); diff --git a/third_party/rust/enumset/tests/trybuild.rs b/third_party/rust/enumset/tests/trybuild.rs new file mode 100644 index 0000000000..e3c06924b3 --- /dev/null +++ b/third_party/rust/enumset/tests/trybuild.rs @@ -0,0 +1,7 @@ +#[rustversion::nightly] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/compile-fail/*.rs"); + t.pass("tests/compile-pass/*.rs"); +} |