diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /third_party/rust/enumset | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/enumset')
27 files changed, 3650 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..fd9b8a8cbc --- /dev/null +++ b/third_party/rust/enumset/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"f173fbd9ad98e0eb5077ec8d2fa39321e3c634500c7b1c5f1e7c792e47a590c8","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7405fdff2ff8682a5384da664436b9b2aca47557572513f5b27686a5347f9b8e","README.md":"d909f3ef0b7937f6d6d0a8171e056671f717561f2679c6da43254a528711d285","src/lib.rs":"3bb0f56eb0e15acc4f99db31f17567c0479d3b364743f94d132d7d4c6c07db5c","src/macros.rs":"01d43156f78cb32caee75263cf613d5018a30fbaafdcd403dd0abb15aa28abca","src/repr/array.rs":"8c082259fcbd0842ea52844b03c88b98f39ed59a381c83b278e574357b972d58","src/repr/mod.rs":"88fa5138818c5246539814da6bd1b27c790abf64f003af4ce05c83f3e8c4e5d2","src/repr/primitive.rs":"1d6e97c7990e7028f6860ac2acf080f247c894d4c050818d36a55f017edaa956","src/set.rs":"7546fd252fbd2b9d1eb6f86b6c0cfcdd69573528335cbcdfe8006de5236ed5bd","src/traits.rs":"533a2e62c09e956538013bc9a852d0ae336d4bf0a0f8f0494fbf5743bbd27da9","tests/compile-fail-serde/deprecation.rs":"fa6be473bffb4f37ad9407f8712a98c30d32ced00f52749a21d127167037a58a","tests/compile-fail-serde/deprecation.stderr":"7639d3599c3bbbbfe7763dac33307037ba8fa7914f2e1c3502271dad4a0663a7","tests/compile-fail/explicit_repr.rs":"8d3afa63274224c8f526df3a1b5a0435de51343fc4e7b5cbf717d15c38f7f5c5","tests/compile-fail/explicit_repr.stderr":"beaf53132cafb18c58ad8f66ff276bb2b51e34bc9c6880dbe5cdb125422c6f2f","tests/compile-fail/syntax.rs":"eab09b5f611c60e086299a5bfb3aa7e6622b736524e4480a5b7c55a6efe2f34f","tests/compile-fail/syntax.stderr":"9892d3eed892a9dadb7abf308257d5b38bf67902430b7cb07aa0c2c61bfba823","tests/compile-fail/variants.rs":"2e9d69cce5f53addda5352588168882cc47833f765e8db631ba1fd9162271e67","tests/compile-fail/variants.stderr":"47f7a545c8bcaea3b8f31a17395abd98c4b4f1799e0d9ad9389e973e26be13e5","tests/compile-pass/no_imports.rs":"6fa96d43c3970e25dd1e216820dd79f22f5bfe416ce7d6a6df86781797279297","tests/compile-pass/no_std.rs":"e8a402ae12562e6eab4ac531c084278a9dda4ac9b4e64b7a37bb87ce890738e7","tests/conversions.rs":"06683f3f89bb580c1feb9e2c3482b5d9df5e18d1f5d0c2fe1abf4ebfcba5d12e","tests/ops.rs":"ce2b5f7979c72c3f2952a2e4cd4c94cc1895100c594ff19c97edd09e631c6cdf","tests/repr.rs":"a1b792a3b6f71db62b7b26b9b880783b4fd6c905c170c35a0e4b90ccc2a701c9","tests/serde.rs":"f8ea3b9a5f944c48a35a2ad68c7b61a7e1ef4ad60dd3f5523feec3a51edfdba5","tests/trybuild.rs":"5bdb2e3777c1162ffb3b00475130c5032c7d34a2c4f822b898bc79eef722ba97"},"package":"e875f1719c16de097dee81ed675e2d9bb63096823ed3f0ca827b7dea3028bbbb"}
\ 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..7a67ada566 --- /dev/null +++ b/third_party/rust/enumset/Cargo.toml @@ -0,0 +1,77 @@ +# 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" +name = "enumset" +version = "1.1.2" +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" +resolver = "1" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = [ + "--cfg", + "docsrs", +] + +[dependencies.enumset_derive] +version = "0.8.0" + +[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..eff1d96975 --- /dev/null +++ b/third_party/rust/enumset/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) 2017-2023 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..260c59e5c6 --- /dev/null +++ b/third_party/rust/enumset/README.md @@ -0,0 +1,29 @@ +# 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.56+](https://img.shields.io/badge/rustc-1.56+-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. diff --git a/third_party/rust/enumset/src/lib.rs b/third_party/rust/enumset/src/lib.rs new file mode 100644 index 0000000000..ee509a611c --- /dev/null +++ b/third_party/rust/enumset/src/lib.rs @@ -0,0 +1,199 @@ +#![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. +//! +//! The following feature flags may be used for this crate: +//! +//! * `serde` enables serialization support for [`EnumSet`]. +//! * `alloc` enables functions that require allocation. +//! +//! # 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); +//! ``` + +#[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; diff --git a/third_party/rust/enumset/src/macros.rs b/third_party/rust/enumset/src/macros.rs new file mode 100644 index 0000000000..f306063a8f --- /dev/null +++ b/third_party/rust/enumset/src/macros.rs @@ -0,0 +1,60 @@ +/// 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 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 { + ($(|)*) => { + EnumSet::EMPTY + }; + ($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/array.rs b/third_party/rust/enumset/src/repr/array.rs new file mode 100644 index 0000000000..cc302ef842 --- /dev/null +++ b/third_party/rust/enumset/src/repr/array.rs @@ -0,0 +1,335 @@ +use 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<const N: usize>(pub [u64; N]); +impl<const N: usize> ArrayRepr<N> { + fn split_bit(bit: u32) -> (usize, u32) { + (bit as usize / 64, bit % 64) + } +} + +impl<const N: usize> BitAnd for ArrayRepr<N> { + type Output = Self; + fn bitand(mut self, rhs: Self) -> Self::Output { + for i in 0..N { + self.0[i] &= rhs.0[i]; + } + self + } +} +impl<const N: usize> BitOr for ArrayRepr<N> { + type Output = Self; + fn bitor(mut self, rhs: Self) -> Self::Output { + for i in 0..N { + self.0[i] |= rhs.0[i]; + } + self + } +} +impl<const N: usize> BitXor for ArrayRepr<N> { + type Output = Self; + fn bitxor(mut self, rhs: Self) -> Self::Output { + for i in 0..N { + self.0[i] ^= rhs.0[i]; + } + self + } +} +impl<const N: usize> Not for ArrayRepr<N> { + type Output = Self; + fn not(mut self) -> Self::Output { + for i in 0..N { + self.0[i] = !self.0[i]; + } + self + } +} + +impl<const N: usize> EnumSetTypeRepr for ArrayRepr<N> { + 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<N>; + 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<Self> { + Some(Self::from_u8(v)) + } + fn from_u16_opt(v: u16) -> Option<Self> { + Some(Self::from_u16(v)) + } + fn from_u32_opt(v: u32) -> Option<Self> { + Some(Self::from_u32(v)) + } + fn from_u64_opt(v: u64) -> Option<Self> { + Some(Self::from_u64(v)) + } + fn from_u128_opt(v: u128) -> Option<Self> { + if N == 1 && (v >> 64) != 0 { + None + } else { + Some(Self::from_u128(v)) + } + } + fn from_usize_opt(v: usize) -> Option<Self> { + 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<u8> { + self.to_u64_opt().and_then(|x| x.to_u8_opt()) + } + fn to_u16_opt(&self) -> Option<u16> { + self.to_u64_opt().and_then(|x| x.to_u16_opt()) + } + fn to_u32_opt(&self) -> Option<u32> { + self.to_u64_opt().and_then(|x| x.to_u32_opt()) + } + fn to_u64_opt(&self) -> Option<u64> { + for i in 1..N { + if self.0[i] != 0 { + return None; + } + } + Some(self.to_u64()) + } + fn to_u128_opt(&self) -> Option<u128> { + for i in 2..N { + if self.0[i] != 0 { + return None; + } + } + Some(self.to_u128()) + } + fn to_usize_opt(&self) -> Option<usize> { + self.to_u64_opt().and_then(|x| x.to_usize_opt()) + } + + fn to_u64_array<const O: usize>(&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<const O: usize>(&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<const O: usize>(v: [u64; O]) -> Self { + ArrayRepr(ArrayRepr::<O>(v).to_u64_array::<N>()) + } + fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self> { + ArrayRepr::<O>(v).to_u64_array_opt::<N>().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<Self> { + 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<const N: usize> { + data: [PrimitiveIter<u64>; N], + done: bool, + idx_f: usize, + idx_r: usize, +} + +impl<const N: usize> ArrayIter<N> { + pub fn new(array: ArrayRepr<N>) -> 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<const N: usize> Iterator for ArrayIter<N> { + type Item = u32; + + fn next(&mut self) -> Option<Self::Item> { + 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<usize>) { + 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<const N: usize> DoubleEndedIterator for ArrayIter<N> { + fn next_back(&mut self) -> Option<Self::Item> { + 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 + } +} diff --git a/third_party/rust/enumset/src/repr/mod.rs b/third_party/rust/enumset/src/repr/mod.rs new file mode 100644 index 0000000000..b5bf23ffec --- /dev/null +++ b/third_party/rust/enumset/src/repr/mod.rs @@ -0,0 +1,92 @@ +#![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<Output = Self> + + BitOr<Output = Self> + + BitXor<Output = Self> + + Not<Output = Self> + +{ + 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<Item = u32> + 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<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>; + + fn to_u64_array<const O: usize>(&self) -> [u64; O]; + fn to_u64_array_opt<const O: usize>(&self) -> Option<[u64; O]>; + + fn from_u64_array<const O: usize>(v: [u64; O]) -> Self; + fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self>; + + 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<Self>; +} + +pub use array::ArrayRepr; diff --git a/third_party/rust/enumset/src/repr/primitive.rs b/third_party/rust/enumset/src/repr/primitive.rs new file mode 100644 index 0000000000..ef44adaa79 --- /dev/null +++ b/third_party/rust/enumset/src/repr/primitive.rs @@ -0,0 +1,300 @@ +use 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<Self>; + 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<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() + } + + #[inline(always)] + fn to_u64_array<const O: usize>(&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<const O: usize>(&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<const O: usize>(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<const O: usize>(v: [u64; O]) -> Option<Self> { + 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<Self> { + 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<T: EnumSetTypeRepr>(pub T); + +impl<T: EnumSetTypeRepr> Iterator for PrimitiveIter<T> { + type Item = u32; + + fn next(&mut self) -> Option<Self::Item> { + 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<usize>) { + let left = self.0.count_ones() as usize; + (left, Some(left)) + } +} + +impl<T: EnumSetTypeRepr> DoubleEndedIterator for PrimitiveIter<T> { + fn next_back(&mut self) -> Option<Self::Item> { + if self.0.is_empty() { + None + } else { + let bit = T::WIDTH - 1 - self.0.leading_zeros(); + self.0.remove_bit(bit); + Some(bit) + } + } +} diff --git a/third_party/rust/enumset/src/set.rs b/third_party/rust/enumset/src/set.rs new file mode 100644 index 0000000000..11421f9add --- /dev/null +++ b/third_party/rust/enumset/src/set.rs @@ -0,0 +1,856 @@ +use crate::repr::EnumSetTypeRepr; +use crate::traits::EnumSetType; +use crate::EnumSetTypeWithRepr; +use core::cmp::Ordering; +use core::fmt::{Debug, 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 +/// <code>[EnumSetTypeWithRepr](crate::traits::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`. +#[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<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, +} + +//region EnumSet operations +impl<T: EnumSetType> EnumSet<T> { + /// An empty `EnumSet`. + /// + /// This is available as a constant for use in constant expressions. + pub const EMPTY: Self = EnumSet { __priv_repr: T::Repr::EMPTY }; + + /// An `EnumSet` containing all valid variants of the enum. + /// + /// This is available as a constant for use in constant expressions. + pub const ALL: Self = EnumSet { __priv_repr: T::ALL_BITS }; + + /// Creates an empty `EnumSet`. + #[inline(always)] + pub fn new() -> Self { + Self::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::EMPTY + } + + /// Returns an `EnumSet` containing all valid variants of the enum. + #[inline(always)] + pub fn all() -> Self { + Self::ALL + } + + /// 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::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 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); + } +} + +impl<T: EnumSetType> Default for EnumSet<T> { + /// Returns an empty set. + fn default() -> Self { + Self::new() + } +} + +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<'_>) -> core::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::derived_hash_with_manual_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) + } +} +//endregion + +//region EnumSet conversions +impl<T: EnumSetType + EnumSetTypeWithRepr> EnumSet<T> { + /// 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 { + 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 { + 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 { + 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> { + 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 { + 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 = "`, 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<Self> { + 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 = <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> EnumSet<T> { + /// 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<const O: usize>(&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<const O: usize>(&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<const O: usize>(&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<const O: usize>(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<const O: usize>(bits: [u64; O]) -> Option<Self> { + let bits = T::Repr::from_u64_array_opt::<O>(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<const O: usize>(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<const O: usize>(bits: [u64; O]) -> Self { + EnumSet { __priv_repr: T::Repr::from_u64_array(bits) } + } + + /// Returns a `Vec<u64>` representing the elements of this set. + #[cfg(feature = "alloc")] + #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] + pub fn to_vec(&self) -> alloc::vec::Vec<u64> { + 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<Self> { + 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<T: EnumSetType> { + iter: <T::Repr as EnumSetTypeRepr>::Iter, +} +impl<T: EnumSetType> EnumSetIter<T> { + fn new(set: EnumSet<T>) -> EnumSetIter<T> { + EnumSetIter { iter: set.__priv_repr.iter() } + } +} + +impl<T: EnumSetType> EnumSet<T> { + /// 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) + } +} + +impl<T: EnumSetType> Iterator for EnumSetIter<T> { + type Item = T; + + fn next(&mut self) -> Option<Self::Item> { + self.iter.next().map(|x| unsafe { T::enum_from_u32(x) }) + } + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } +} + +impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> { + fn next_back(&mut self) -> Option<Self::Item> { + self.iter + .next_back() + .map(|x| unsafe { T::enum_from_u32(x) }) + } +} + +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 + } +} + +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) + } +} +//endregion diff --git a/third_party/rust/enumset/src/traits.rs b/third_party/rust/enumset/src/traits.rs new file mode 100644 index 0000000000..76730aa24b --- /dev/null +++ b/third_party/rust/enumset/src/traits.rs @@ -0,0 +1,62 @@ +use 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<T>` +/// 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 = <Self as EnumSetTypeWithRepr>::Repr> +{ + /// The guaranteed representation. + type Repr: EnumSetTypeRepr; +} + +/// 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; + /// 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<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; +} diff --git a/third_party/rust/enumset/tests/compile-fail-serde/deprecation.rs b/third_party/rust/enumset/tests/compile-fail-serde/deprecation.rs new file mode 100644 index 0000000000..72c19e29db --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail-serde/deprecation.rs @@ -0,0 +1,20 @@ +#![deny(deprecated)] + +use enumset::*; +use serde_derive::*; + +#[derive(Serialize, Deserialize, EnumSetType, Debug)] +#[enumset(serialize_as_map)] +#[serde(crate="enumset::__internal::serde")] +pub enum MapEnum { + A, B, C, D, E, F, G, H, +} + +#[derive(Serialize, Deserialize, EnumSetType, Debug)] +#[enumset(serialize_as_list)] +#[serde(crate="enumset::__internal::serde")] +pub enum ListEnum { + A, B, C, D, E, F, G, H, +} + +fn main() {} diff --git a/third_party/rust/enumset/tests/compile-fail-serde/deprecation.stderr b/third_party/rust/enumset/tests/compile-fail-serde/deprecation.stderr new file mode 100644 index 0000000000..d514000952 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail-serde/deprecation.stderr @@ -0,0 +1,17 @@ +error: use of deprecated constant `_::__enumset_derive__generated_warnings::_w`: #[enumset(serialize_as_map)] is deprecated. Use `#[enumset(serialize_repr = "map")]` instead. + --> tests/compile-fail-serde/deprecation.rs:7:11 + | +7 | #[enumset(serialize_as_map)] + | ^^^^^^^^^^^^^^^^ + | +note: the lint level is defined here + --> tests/compile-fail-serde/deprecation.rs:1:9 + | +1 | #![deny(deprecated)] + | ^^^^^^^^^^ + +error: use of deprecated constant `_::__enumset_derive__generated_warnings::_w`: #[enumset(serialize_as_list)] is deprecated. Use `#[enumset(serialize_repr = "list")]` instead. + --> tests/compile-fail-serde/deprecation.rs:14:11 + | +14 | #[enumset(serialize_as_list)] + | ^^^^^^^^^^^^^^^^^ diff --git a/third_party/rust/enumset/tests/compile-fail/explicit_repr.rs b/third_party/rust/enumset/tests/compile-fail/explicit_repr.rs new file mode 100644 index 0000000000..445cc61136 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/explicit_repr.rs @@ -0,0 +1,17 @@ +use enumset::*; + +#[derive(EnumSetType)] +enum OkayEnumButCantUseFromRepr { + Variant, +} + +#[derive(EnumSetType)] +#[enumset(repr = "array")] +enum OkayEnumButCantUseFromReprArray { + Variant, +} + +fn main() { + EnumSet::<OkayEnumButCantUseFromRepr>::from_repr(1); + EnumSet::<OkayEnumButCantUseFromReprArray>::from_repr([1]); +} diff --git a/third_party/rust/enumset/tests/compile-fail/explicit_repr.stderr b/third_party/rust/enumset/tests/compile-fail/explicit_repr.stderr new file mode 100644 index 0000000000..93979448c9 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/explicit_repr.stderr @@ -0,0 +1,45 @@ +error[E0599]: the function or associated item `from_repr` exists for struct `EnumSet<OkayEnumButCantUseFromRepr>`, but its trait bounds were not satisfied + --> tests/compile-fail/explicit_repr.rs:15:44 + | +4 | enum OkayEnumButCantUseFromRepr { + | ------------------------------- + | | + | doesn't satisfy `<_ as EnumSetTypePrivate>::Repr = <OkayEnumButCantUseFromRepr as EnumSetTypeWithRepr>::Repr` + | doesn't satisfy `OkayEnumButCantUseFromRepr: EnumSetTypeWithRepr` +... +15 | EnumSet::<OkayEnumButCantUseFromRepr>::from_repr(1); + | ^^^^^^^^^ function or associated item cannot be called on `EnumSet<OkayEnumButCantUseFromRepr>` due to unsatisfied trait bounds + | + = note: the following trait bounds were not satisfied: + `OkayEnumButCantUseFromRepr: EnumSetTypeWithRepr` + `<OkayEnumButCantUseFromRepr as EnumSetTypePrivate>::Repr = <OkayEnumButCantUseFromRepr as EnumSetTypeWithRepr>::Repr` + which is required by `OkayEnumButCantUseFromRepr: EnumSetTypeWithRepr` +note: the trait `EnumSetTypeWithRepr` must be implemented + --> src/traits.rs + | + | / pub unsafe trait EnumSetTypeWithRepr: + | | EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr> + | |________________________________________________________________________________^ + +error[E0599]: the function or associated item `from_repr` exists for struct `EnumSet<OkayEnumButCantUseFromReprArray>`, but its trait bounds were not satisfied + --> tests/compile-fail/explicit_repr.rs:16:49 + | +10 | enum OkayEnumButCantUseFromReprArray { + | ------------------------------------ + | | + | doesn't satisfy `<_ as EnumSetTypePrivate>::Repr = <OkayEnumButCantUseFromReprArray as EnumSetTypeWithRepr>::Repr` + | doesn't satisfy `_: EnumSetTypeWithRepr` +... +16 | EnumSet::<OkayEnumButCantUseFromReprArray>::from_repr([1]); + | ^^^^^^^^^ function or associated item cannot be called on `EnumSet<OkayEnumButCantUseFromReprArray>` due to unsatisfied trait bounds + | + = note: the following trait bounds were not satisfied: + `OkayEnumButCantUseFromReprArray: EnumSetTypeWithRepr` + `<OkayEnumButCantUseFromReprArray as EnumSetTypePrivate>::Repr = <OkayEnumButCantUseFromReprArray as EnumSetTypeWithRepr>::Repr` + which is required by `OkayEnumButCantUseFromReprArray: EnumSetTypeWithRepr` +note: the trait `EnumSetTypeWithRepr` must be implemented + --> src/traits.rs + | + | / pub unsafe trait EnumSetTypeWithRepr: + | | EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr> + | |________________________________________________________________________________^ diff --git a/third_party/rust/enumset/tests/compile-fail/syntax.rs b/third_party/rust/enumset/tests/compile-fail/syntax.rs new file mode 100644 index 0000000000..33ff972101 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/syntax.rs @@ -0,0 +1,39 @@ +use enumset::*; + +#[derive(EnumSetType)] +#[repr(usize)] +enum BadRepr { + Variant, +} + +#[derive(EnumSetType)] +#[repr(usize)] +enum GenericEnum<T> { + Variant, + FieldBlah(T), +} + +#[derive(EnumSetType)] +struct BadItemType { + +} + +#[derive(EnumSetType)] +#[enumset(repr = "u8", repr = "u16")] +enum MultipleReprs { + Variant, +} + +#[derive(EnumSetType)] +#[enumset(repr = "abcdef")] +enum InvalidRepr { + Variant, +} + +#[derive(EnumSetType)] +#[enumset(serialize_repr = "abcdef")] +enum InvalidSerdeRepr { + Variant, +} + +fn main() {}
\ No newline at end of file diff --git a/third_party/rust/enumset/tests/compile-fail/syntax.stderr b/third_party/rust/enumset/tests/compile-fail/syntax.stderr new file mode 100644 index 0000000000..bd929d53e9 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/syntax.stderr @@ -0,0 +1,31 @@ +error: `#[derive(EnumSetType)]` cannot be used on enums with type parameters. + --> tests/compile-fail/syntax.rs:11:17 + | +11 | enum GenericEnum<T> { + | ^^^ + +error: `#[derive(EnumSetType)]` may only be used on enums + --> tests/compile-fail/syntax.rs:17:1 + | +17 | / struct BadItemType { +18 | | +19 | | } + | |_^ + +error: Duplicate field `repr` + --> tests/compile-fail/syntax.rs:22:24 + | +22 | #[enumset(repr = "u8", repr = "u16")] + | ^^^^^^^^^^^^ + +error: `abcdef` is not a valid internal enumset representation. + --> tests/compile-fail/syntax.rs:28:18 + | +28 | #[enumset(repr = "abcdef")] + | ^^^^^^^^ + +error: `abcdef` is not a valid serialized representation. + --> tests/compile-fail/syntax.rs:34:28 + | +34 | #[enumset(serialize_repr = "abcdef")] + | ^^^^^^^^ 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..202d34028f --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/variants.rs @@ -0,0 +1,41 @@ +use enumset::*; + +#[derive(EnumSetType)] +enum NegativeVariant { + Variant = -1, +} + +#[derive(EnumSetType)] +enum HasFields { + Variant(u32), +} + +#[derive(EnumSetType)] +#[enumset(repr = "u128")] +enum BadExplicitRepr { + Variant = 128, +} + +#[derive(EnumSetType)] +#[enumset(serialize_repr = "u8")] +enum BadSerializationRepr { + Variant = 8, +} + +#[derive(EnumSetType)] +enum NonLiteralRepr { + Variant = 1 + 1, +} + +#[derive(EnumSetType)] +#[enumset(repr = "u16")] +enum BadMemRepr { + Variant = 16, +} + +#[derive(EnumSetType)] +enum ExcessiveReprSize { + Variant = 0xFFFFFFD0, +} + +fn main() {} 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..635fa56c86 --- /dev/null +++ b/third_party/rust/enumset/tests/compile-fail/variants.stderr @@ -0,0 +1,41 @@ +error: Enum discriminants must not be negative. + --> tests/compile-fail/variants.rs:5:15 + | +5 | Variant = -1, + | ^^ + +error: `#[derive(EnumSetType)]` can only be used on fieldless enums. + --> tests/compile-fail/variants.rs:10:5 + | +10 | Variant(u32), + | ^^^^^^^^^^^^ + +error: `repr` is too small to contain the largest discriminant. + --> tests/compile-fail/variants.rs:16:5 + | +16 | Variant = 128, + | ^^^^^^^^^^^^^ + +error: `serialize_repr` is too small to contain the largest discriminant. + --> tests/compile-fail/variants.rs:22:5 + | +22 | Variant = 8, + | ^^^^^^^^^^^ + +error: Enum discriminants must be literal expressions. + --> tests/compile-fail/variants.rs:27:5 + | +27 | Variant = 1 + 1, + | ^^^^^^^^^^^^^^^ + +error: `repr` is too small to contain the largest discriminant. + --> tests/compile-fail/variants.rs:33:5 + | +33 | Variant = 16, + | ^^^^^^^^^^^^ + +error: Maximum discriminant allowed is `0xFFFFFFBF`. + --> tests/compile-fail/variants.rs:38:5 + | +38 | Variant = 0xFFFFFFD0, + | ^^^^^^^^^^^^^^^^^^^^ 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/conversions.rs b/third_party/rust/enumset/tests/conversions.rs new file mode 100644 index 0000000000..054ef8f8b8 --- /dev/null +++ b/third_party/rust/enumset/tests/conversions.rs @@ -0,0 +1,360 @@ +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); diff --git a/third_party/rust/enumset/tests/ops.rs b/third_party/rust/enumset/tests/ops.rs new file mode 100644 index 0000000000..f9eef88f11 --- /dev/null +++ b/third_party/rust/enumset/tests/ops.rs @@ -0,0 +1,530 @@ +#![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)] +#[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 EMPTY_SET: EnumSet<$e> = EnumSet::EMPTY; + #[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 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::<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; + 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::<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)); +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::<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_usize_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..42c1cab06c --- /dev/null +++ b/third_party/rust/enumset/tests/serde.rs @@ -0,0 +1,137 @@ +#![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_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::<EnumSet<$e>>(&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::<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_basic() { + assert_eq!(ListEnum::A | ListEnum::C | ListEnum::F, + serde_json::from_str::<EnumSet<ListEnum>>(r#"["A","C","F"]"#).unwrap()); + assert_eq!(MapEnum::A | MapEnum::C | MapEnum::F, + serde_json::from_str::<EnumSet<MapEnum>>(r#"{"A":true,"C":true,"F":true}"#).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!(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::<EnumSet<MapEnum>>(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::<EnumSet<LargeEnum>>(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)); diff --git a/third_party/rust/enumset/tests/trybuild.rs b/third_party/rust/enumset/tests/trybuild.rs new file mode 100644 index 0000000000..cd3ad2ec35 --- /dev/null +++ b/third_party/rust/enumset/tests/trybuild.rs @@ -0,0 +1,11 @@ +#[rustversion::nightly] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + + t.compile_fail("tests/compile-fail/*.rs"); + t.pass("tests/compile-pass/*.rs"); + + #[cfg(feature = "serde")] + t.compile_fail("tests/compile-fail-serde/*.rs"); +} |