From 26a029d407be480d791972afb5975cf62c9360a6 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Fri, 19 Apr 2024 02:47:55 +0200 Subject: Adding upstream version 124.0.1. Signed-off-by: Daniel Baumann --- third_party/rust/enum-map/.cargo-checksum.json | 1 + third_party/rust/enum-map/CHANGELOG.md | 285 +++++++++ third_party/rust/enum-map/Cargo.toml | 65 ++ third_party/rust/enum-map/LICENSES/Apache-2.0.txt | 73 +++ third_party/rust/enum-map/LICENSES/CC0-1.0.txt | 121 ++++ third_party/rust/enum-map/LICENSES/MIT.txt | 9 + third_party/rust/enum-map/README.md | 45 ++ third_party/rust/enum-map/src/arbitrary.rs | 28 + third_party/rust/enum-map/src/enum_map_impls.rs | 115 ++++ third_party/rust/enum-map/src/internal.rs | 159 +++++ third_party/rust/enum-map/src/iter.rs | 415 +++++++++++++ third_party/rust/enum-map/src/lib.rs | 509 ++++++++++++++++ third_party/rust/enum-map/src/serde.rs | 98 +++ third_party/rust/enum-map/tests/serde.rs | 115 ++++ third_party/rust/enum-map/tests/test.rs | 696 ++++++++++++++++++++++ 15 files changed, 2734 insertions(+) create mode 100644 third_party/rust/enum-map/.cargo-checksum.json create mode 100644 third_party/rust/enum-map/CHANGELOG.md create mode 100644 third_party/rust/enum-map/Cargo.toml create mode 100644 third_party/rust/enum-map/LICENSES/Apache-2.0.txt create mode 100644 third_party/rust/enum-map/LICENSES/CC0-1.0.txt create mode 100644 third_party/rust/enum-map/LICENSES/MIT.txt create mode 100644 third_party/rust/enum-map/README.md create mode 100644 third_party/rust/enum-map/src/arbitrary.rs create mode 100644 third_party/rust/enum-map/src/enum_map_impls.rs create mode 100644 third_party/rust/enum-map/src/internal.rs create mode 100644 third_party/rust/enum-map/src/iter.rs create mode 100644 third_party/rust/enum-map/src/lib.rs create mode 100644 third_party/rust/enum-map/src/serde.rs create mode 100644 third_party/rust/enum-map/tests/serde.rs create mode 100644 third_party/rust/enum-map/tests/test.rs (limited to 'third_party/rust/enum-map') diff --git a/third_party/rust/enum-map/.cargo-checksum.json b/third_party/rust/enum-map/.cargo-checksum.json new file mode 100644 index 0000000000..d964247865 --- /dev/null +++ b/third_party/rust/enum-map/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"d64d088715bcbff31fb85a6694fbbaef2802ab19ff91d5f0d71ac715d1fa4417","Cargo.toml":"94a380dc0296261c3f80d1ef71a7c1355757bb67ca902367432084bde5b87233","LICENSES/Apache-2.0.txt":"074e6e32c86a4c0ef8b3ed25b721ca23aca83df277cd88106ef7177c354615ff","LICENSES/CC0-1.0.txt":"a2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499","LICENSES/MIT.txt":"b85dcd3e453d05982552c52b5fc9e0bdd6d23c6f8e844b984a88af32570b0cc0","README.md":"eec9d4461de2e1e0f26251a98fd53feaad8582e6614a5a23be17a5b0c9491637","src/arbitrary.rs":"30e90bc431c4e74f756a619f432b30ccadc9b3288fc85f2d4bd160a374d0dfdb","src/enum_map_impls.rs":"9a03bf2500215e3c2dcb7e93cfc4d466bd767bdb9b83673b013f7ef50ac08d04","src/internal.rs":"ea03c0ca57eb52012e77dc3928ba5407109c5d24d373b7d7359ba037d890716f","src/iter.rs":"cc75658ea4c61ed63b35bf12c8f14534e36b2d3c9b1a29ab2efc028de0181d44","src/lib.rs":"3e34c9461dfb5b102d620b0196b30dab2d8d429e801e193f8e2e78adfef9039e","src/serde.rs":"f3a9919e2f6c0721a7e1fa386eb712875c5fce01d4f01d5d4775bc246d45ba90","tests/serde.rs":"98b788415b99c7b764ce2271260a4c38feeec9e539e8d8b01909b052ed41db85","tests/test.rs":"bfab8d9752b73de9085e0c59cc478ad09f87014a2c84b7b8bc16ecedf128b559"},"package":"6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9"} \ No newline at end of file diff --git a/third_party/rust/enum-map/CHANGELOG.md b/third_party/rust/enum-map/CHANGELOG.md new file mode 100644 index 0000000000..84dacb8bd0 --- /dev/null +++ b/third_party/rust/enum-map/CHANGELOG.md @@ -0,0 +1,285 @@ + + +# Version 2.7.3 + +## Other changes + +- Fixed [a regression introduced in 2.7.2 that caused `#[derive(Enum)]` to + generate incorrect code when dealing with enums containing + fields](https://codeberg.org/xfix/enum-map/issues/112). + +# Version 2.7.2 + +## Other changes + +- Reduced RAM usage and improved compilation times when using `derive(Enum)` + for large enums with `overflow-checks` enabled. + +# Version 2.7.1 + +## Other changes + +- Updated author name. + +# Version 2.7.0 + +## New features + +- Implemented `EnumMap::from_fn`. + +# Version 2.6.3 + +## Other changes + +- Updated the repository URL as the project was migrated from GitHub + to Codeberg. + +- This project is now compliant with the REUSE Specification. + +# Version 2.6.2 + +## Other changes + +- Hide `out_of_bounds` reexport from documentation. + +# Version 2.6.1 + +## Other changes + +- Provide better panic message when providing out-of-bounds index + to `Enum::from_usize``. + +# Version 2.6.0 + +## New features + +- `EnumMap::as_array` is now usable in const contexts. + +## Other changes + +- This crate now follows "N minus two" MSRV policy. This means that + it supports the current Rust release, as well as the two before + that. + +- Upgraded syn to 2.0.0. + +# Version 2.5.0 + +## New features + +- Implemented `EnumMap::as_array` and `EnumMap::as_mut_array` + (implemented by [@Fuuzetsu](https://github.com/Fuuzetsu)). + +- Implemented `PartialOrd` and `Ord` for `EnumMap` (implemented by + [@nicarran](https://github.com/nicarran)). + +# Version 2.4.2 + +## Other changes + +- Added license files to crate tarball. +- Added changelog to crate tarball. + +# Version 2.4.1 + +## Other changes + +- Improved performance of code generated for `from_usize` when + deriving `Enum`. + +# Version 2.4.0 + +## New features + +- Implemented `Enum` for `()` (unit type) and `core::cmp::Ordering` + (implemented by [@phimuemue](https://github.com/phimuemue)). + +- Implemented `EnumMap::into_array`. + +# Version 2.3.0 + +## New features + +- `EnumMap::len` is now usable in const contexts. + +## Other changes + +- `Enum` derive now can deal with re-definitions of `usize` and + `unimplemented`. + +# Version 2.2.0 + +## New features + +- `EnumMap::from_array` is now usable in const contexts. + +# Version 2.1.0 + +## New features + +- Implemented `DoubleEndedIterator` for `IntoIter`. + +- Implemented `EnumMap::into_values`. + +## Other changes + +- Changed behavior of `IntoIter` so that it drops rest of the elements + when one destructor panics. + +# Version 2.0.3 + +## Other changes + +- Optimized performance of `enum_map!` macro. + +# Version 2.0.2 + +## Other changes + +- Fixed safety problem when using `enum_map!` macro with enums that + incorrectly implemented `Enum` trait. + +# Version 2.0.1 + +## Other changes + +- Adjusted crate metadata to avoid lib.rs warnings. + +# Version 2.0.0 + +## New features + +- Implemented `FromIterator` for `EnumMap` (implemented by @bit_network + on GitLab). + +- Implemented `EnumMap::map`. + +- Derives support product types in addition to sum types (implemented + by @bzim on GitLab). + +- It's now possible to access enum length by accessing `LENGTH` in + `Enum` trait. + +## Breaking changes + +- `Enum` trait was split into two traits, `Enum` and `EnumArray`. + +# Version 1.1.1 + +## Other changes + +- Worked around a bug in Clippy that caused false positives when using + `use_self` lint for code that derived `Enum` trait. + +# Version 1.1.0 + +## New features + +- Implemented `Arbitrary` for maps where the value type also implements + `Arbitrary`. (You have to enable the "arbitrary" feature.) + +# Version 1.0.0 + +## New features + +- It's now possible to use `return` and `?` within `macro_rules!` macro. + +- `Enum` trait is much simpler having two methods only. + +## Other changes + +- Removed previously deprecated features. + +- Renamed `to_usize` to `into_usize` matching the naming convention + used in Rust programming language. + +# Version 0.6.5 + +## Other changes + +- Deprecated `EnumMap::is_empty` and `EnumMap::new`. `EnumMap::new` usages + can be replaced with `EnumMap::default`. + +# Version 0.6.4 + +## Other changes + +- Deprecated `EnumMap::as_ptr` and `EnumMap::as_mut_ptr`. + +# Version 0.6.3 + +## New features + +- `Iter` and `Values` now implements `Clone` (added by @amanieu). + +# Version 0.6.2. + +## New features + +- Added `EnumMap#clear` method (added by @Riey, thanks :)). + +# Version 0.6.0 + +## Incompatible changes + +- Now requires Rust 1.36. + +# Version 0.5.0 + +- Fixed the issue where an aliasing `From` trait implementation caused + compilation errors with `enum_map!` macro. + +## Incompatible changes + +- Now requires Rust 1.31. + +# Version 0.4.1 + +## New features + +- Default `serde` features are disabled. This allows enabling serde feature when + compiling without `std`. + +# Version 0.4.0 + +Change of `#[derive(EnumMap)]` to `#[derive(Enum)]` was supposed to appear in 0.3.0, +but it was forgotten about. This release fixes just that. + +## Incompatible changes + +- Changed `#[derive(EnumMap)]` to `#[derive(Enum)]` to match trait name. + +# Version 0.3.1 + +- Updated README use `#[derive(EnumMap)]` instead of `#[derive(Enum)]`. + +# Version 0.3.0 + +## New features + +- Implemented compact serde serialization for binary formats like bincode. + +- Iterator traits with exception now implement `FusedIterator`. + +## Incompatible changes + +- Increased required Rust version to 1.26.0. + +- Renamed `Internal` trait to `Enum`. + +- Added new associated constant `POSSIBLE_VALUES` to `Enum` trait, + representing the number of possible values the type can have. Manual + implementations are required to provide it. + +- Removed `Enum` implementation for `Option`. + +- Implemented compact serialization, for formats like `bincode`. This + makes it impossible to deserialize non-compact representation used by + enum-map 0.2.0. + +- `values` method returns `Values` as opposed to `slice::Iter`. diff --git a/third_party/rust/enum-map/Cargo.toml b/third_party/rust/enum-map/Cargo.toml new file mode 100644 index 0000000000..f3f0523e71 --- /dev/null +++ b/third_party/rust/enum-map/Cargo.toml @@ -0,0 +1,65 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.61" +name = "enum-map" +version = "2.7.3" +authors = ["Kamila Borowska "] +description = "A map with C-like enum keys represented internally as an array" +documentation = "https://docs.rs/enum-map" +readme = "README.md" +keywords = [ + "data-structure", + "no_std", + "enum", +] +categories = [ + "data-structures", + "no-std", +] +license = "MIT OR Apache-2.0" +repository = "https://codeberg.org/xfix/enum-map" + +[package.metadata.docs.rs] +features = [ + "arbitrary", + "serde", +] + +[dependencies.arbitrary] +version = "1.0.0" +optional = true + +[dependencies.enum-map-derive] +version = "0.17.0" + +[dependencies.serde] +version = "1.0.16" +optional = true +default-features = false + +[dev-dependencies.bincode] +version = "1.0.0" + +[dev-dependencies.serde] +version = "1.0.103" +features = ["derive"] + +[dev-dependencies.serde_json] +version = "1.0.2" + +[dev-dependencies.serde_test] +version = "1.0.19" + +[badges.maintenance] +status = "passively-maintained" diff --git a/third_party/rust/enum-map/LICENSES/Apache-2.0.txt b/third_party/rust/enum-map/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000000..137069b823 --- /dev/null +++ b/third_party/rust/enum-map/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +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/enum-map/LICENSES/CC0-1.0.txt b/third_party/rust/enum-map/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000000..0e259d42c9 --- /dev/null +++ b/third_party/rust/enum-map/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/third_party/rust/enum-map/LICENSES/MIT.txt b/third_party/rust/enum-map/LICENSES/MIT.txt new file mode 100644 index 0000000000..2071b23b0e --- /dev/null +++ b/third_party/rust/enum-map/LICENSES/MIT.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) + +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/enum-map/README.md b/third_party/rust/enum-map/README.md new file mode 100644 index 0000000000..ca83e020cc --- /dev/null +++ b/third_party/rust/enum-map/README.md @@ -0,0 +1,45 @@ + + +# enum-map + +A library providing enum map providing type safe enum array. It is +implemented using regular Rust arrays, so using them is as fast +as using regular Rust arrays. + +This crate follows the "N minus two" MSRV policy. This means that it +supports the current Rust release, as well as the two before that. + +## Examples + +```rust +#[macro_use] +extern crate enum_map; + +use enum_map::EnumMap; + +#[derive(Debug, Enum)] +enum Example { + A, + B, + C, +} + +fn main() { + let mut map = enum_map! { + Example::A => 1, + Example::B => 2, + Example::C => 3, + }; + map[Example::C] = 4; + + assert_eq!(map[Example::A], 1); + + for (key, &value) in &map { + println!("{:?} has {} as value.", key, value); + } +} +``` diff --git a/third_party/rust/enum-map/src/arbitrary.rs b/third_party/rust/enum-map/src/arbitrary.rs new file mode 100644 index 0000000000..e8c988d292 --- /dev/null +++ b/third_party/rust/enum-map/src/arbitrary.rs @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann +// SPDX-FileCopyrightText: 2021 Kamila Borowska +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::{enum_map, EnumArray, EnumMap}; +use arbitrary::{Arbitrary, Result, Unstructured}; + +/// Requires crate feature `"arbitrary"` +impl<'a, K: EnumArray, V: Arbitrary<'a>> Arbitrary<'a> for EnumMap { + fn arbitrary(u: &mut Unstructured<'a>) -> Result> { + Ok(enum_map! { + _ => Arbitrary::arbitrary(u)?, + }) + } + + fn size_hint(depth: usize) -> (usize, Option) { + if K::LENGTH == 0 { + (0, Some(0)) + } else { + let (lo, hi) = V::size_hint(depth); + ( + lo.saturating_mul(K::LENGTH), + hi.and_then(|hi| hi.checked_mul(K::LENGTH)), + ) + } + } +} diff --git a/third_party/rust/enum-map/src/enum_map_impls.rs b/third_party/rust/enum-map/src/enum_map_impls.rs new file mode 100644 index 0000000000..545ff33ddc --- /dev/null +++ b/third_party/rust/enum-map/src/enum_map_impls.rs @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: 2017 - 2021 Kamila Borowska +// SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann +// SPDX-FileCopyrightText: 2021 micycle +// SPDX-FileCopyrightText: 2023 Nicolas Carranza +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::{enum_map, EnumArray, EnumMap}; +use core::fmt::{self, Debug, Formatter}; +use core::hash::{Hash, Hasher}; +use core::iter::{Extend, FromIterator}; +use core::ops::{Index, IndexMut}; + +impl + Debug, V: Debug> Debug for EnumMap { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + f.debug_map().entries(self).finish() + } +} + +impl, V> Extend<(K, V)> for EnumMap { + fn extend>(&mut self, iter: I) { + for (key, value) in iter { + self[key] = value; + } + } +} + +impl<'a, K, V> Extend<(&'a K, &'a V)> for EnumMap +where + K: EnumArray + Copy, + V: Copy, +{ + fn extend>(&mut self, iter: I) { + self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); + } +} + +impl FromIterator<(K, V)> for EnumMap +where + Self: Default, + K: EnumArray, +{ + fn from_iter>(iter: I) -> Self { + let mut map = EnumMap::default(); + map.extend(iter); + map + } +} + +impl, V> Index for EnumMap { + type Output = V; + + #[inline] + fn index(&self, key: K) -> &V { + &self.as_slice()[key.into_usize()] + } +} + +impl, V> IndexMut for EnumMap { + #[inline] + fn index_mut(&mut self, key: K) -> &mut V { + &mut self.as_mut_slice()[key.into_usize()] + } +} + +// Implementations provided by derive attribute are too specific, and put requirements on K. +// This is caused by rust-lang/rust#26925. +impl, V> Clone for EnumMap +where + K::Array: Clone, +{ + #[inline] + fn clone(&self) -> Self { + EnumMap { + array: self.array.clone(), + } + } +} + +impl, V> Copy for EnumMap where K::Array: Copy {} + +impl, V: PartialEq> PartialEq for EnumMap { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.as_slice() == other.as_slice() + } +} + +impl, V: Eq> Eq for EnumMap {} + +impl, V: Hash> Hash for EnumMap { + #[inline] + fn hash(&self, state: &mut H) { + self.as_slice().hash(state); + } +} + +impl, V: Default> Default for EnumMap { + #[inline] + fn default() -> Self { + enum_map! { _ => V::default() } + } +} + +impl, V: PartialOrd> PartialOrd for EnumMap { + fn partial_cmp(&self, other: &Self) -> Option { + self.as_slice().partial_cmp(other.as_slice()) + } +} + +impl, V: Ord> Ord for EnumMap { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.as_slice().cmp(other.as_slice()) + } +} diff --git a/third_party/rust/enum-map/src/internal.rs b/third_party/rust/enum-map/src/internal.rs new file mode 100644 index 0000000000..2a6235d09d --- /dev/null +++ b/third_party/rust/enum-map/src/internal.rs @@ -0,0 +1,159 @@ +// SPDX-FileCopyrightText: 2017 - 2023 Kamila Borowska +// SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann +// SPDX-FileCopyrightText: 2022 philipp +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use core::cmp::Ordering; +use core::convert::Infallible; + +/// Enum mapping type. +/// +/// This trait is implemented by `#[derive(Enum)]`. +/// +/// This trait is also implemented by `bool` and `u8`. While `u8` is +/// strictly speaking not an actual enum, there are good reasons to consider +/// it like one, as array of `u8` keys is a relatively common pattern. +pub trait Enum: Sized { + /// Length of the enum. + const LENGTH: usize; + + /// Takes an usize, and returns an element matching `into_usize` function. + fn from_usize(value: usize) -> Self; + /// Returns an unique identifier for a value within range of `0..Array::LENGTH`. + fn into_usize(self) -> usize; +} + +/// Trait associating enum with an array. +/// +/// This exists due to limitations of Rust compiler that prevent arrays from using +/// associated constants in structures. The array length must match `LENGTH` of an +/// `Enum`. +pub trait EnumArray: Enum { + /// Representation of an enum map for type `V`. + type Array: Array; +} + +/// Array for enum-map storage. +/// +/// This trait is inteded for primitive array types (with fixed length). +/// +/// # Safety +/// +/// The array length needs to match actual storage. +pub unsafe trait Array { + // This is necessary duplication because the length in Enum trait can be + // provided by user and may not be trustworthy for unsafe code. + const LENGTH: usize; +} + +unsafe impl Array for [V; N] { + const LENGTH: usize = N; +} + +#[doc(hidden)] +#[inline] +pub fn out_of_bounds() -> ! { + panic!("index out of range for Enum::from_usize"); +} + +impl Enum for bool { + const LENGTH: usize = 2; + + #[inline] + fn from_usize(value: usize) -> Self { + match value { + 0 => false, + 1 => true, + _ => out_of_bounds(), + } + } + #[inline] + fn into_usize(self) -> usize { + usize::from(self) + } +} + +impl EnumArray for bool { + type Array = [T; Self::LENGTH]; +} + +impl Enum for () { + const LENGTH: usize = 1; + + #[inline] + fn from_usize(value: usize) -> Self { + match value { + 0 => (), + _ => out_of_bounds(), + } + } + #[inline] + fn into_usize(self) -> usize { + 0 + } +} + +impl EnumArray for () { + type Array = [T; Self::LENGTH]; +} + +impl Enum for u8 { + const LENGTH: usize = 256; + + #[inline] + fn from_usize(value: usize) -> Self { + value.try_into().unwrap_or_else(|_| out_of_bounds()) + } + #[inline] + fn into_usize(self) -> usize { + usize::from(self) + } +} + +impl EnumArray for u8 { + type Array = [T; Self::LENGTH]; +} + +impl Enum for Infallible { + const LENGTH: usize = 0; + + #[inline] + fn from_usize(_: usize) -> Self { + out_of_bounds(); + } + #[inline] + fn into_usize(self) -> usize { + match self {} + } +} + +impl EnumArray for Infallible { + type Array = [T; Self::LENGTH]; +} + +impl Enum for Ordering { + const LENGTH: usize = 3; + + #[inline] + fn from_usize(value: usize) -> Self { + match value { + 0 => Ordering::Less, + 1 => Ordering::Equal, + 2 => Ordering::Greater, + _ => out_of_bounds(), + } + } + #[inline] + fn into_usize(self) -> usize { + match self { + Ordering::Less => 0, + Ordering::Equal => 1, + Ordering::Greater => 2, + } + } +} + +impl EnumArray for Ordering { + type Array = [T; Self::LENGTH]; +} diff --git a/third_party/rust/enum-map/src/iter.rs b/third_party/rust/enum-map/src/iter.rs new file mode 100644 index 0000000000..393d8d1027 --- /dev/null +++ b/third_party/rust/enum-map/src/iter.rs @@ -0,0 +1,415 @@ +#![allow(clippy::module_name_repetitions)] + +// SPDX-FileCopyrightText: 2017 - 2022 Kamila Borowska +// SPDX-FileCopyrightText: 2020 Amanieu d'Antras +// SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::{EnumArray, EnumMap}; +use core::iter::{Enumerate, FusedIterator}; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::ops::Range; +use core::ptr; +use core::slice; + +/// Immutable enum map iterator +/// +/// This struct is created by `iter` method or `into_iter` on a reference +/// to `EnumMap`. +/// +/// # Examples +/// +/// ``` +/// use enum_map::{enum_map, Enum}; +/// +/// #[derive(Enum)] +/// enum Example { +/// A, +/// B, +/// C, +/// } +/// +/// let mut map = enum_map! { Example::A => 3, _ => 0 }; +/// assert_eq!(map[Example::A], 3); +/// for (key, &value) in &map { +/// assert_eq!(value, match key { +/// Example::A => 3, +/// _ => 0, +/// }); +/// } +/// ``` +#[derive(Debug)] +pub struct Iter<'a, K, V: 'a> { + _phantom: PhantomData K>, + iterator: Enumerate>, +} + +impl<'a, K: EnumArray, V> Clone for Iter<'a, K, V> { + fn clone(&self) -> Self { + Iter { + _phantom: PhantomData, + iterator: self.iterator.clone(), + } + } +} + +impl<'a, K: EnumArray, V> Iterator for Iter<'a, K, V> { + type Item = (K, &'a V); + #[inline] + fn next(&mut self) -> Option { + self.iterator + .next() + .map(|(index, item)| (K::from_usize(index), item)) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iterator.size_hint() + } + + fn fold(self, init: B, f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + self.iterator + .map(|(index, item)| (K::from_usize(index), item)) + .fold(init, f) + } +} + +impl<'a, K: EnumArray, V> DoubleEndedIterator for Iter<'a, K, V> { + #[inline] + fn next_back(&mut self) -> Option { + self.iterator + .next_back() + .map(|(index, item)| (K::from_usize(index), item)) + } +} + +impl<'a, K: EnumArray, V> ExactSizeIterator for Iter<'a, K, V> {} + +impl<'a, K: EnumArray, V> FusedIterator for Iter<'a, K, V> {} + +impl<'a, K: EnumArray, V> IntoIterator for &'a EnumMap { + type Item = (K, &'a V); + type IntoIter = Iter<'a, K, V>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + Iter { + _phantom: PhantomData, + iterator: self.as_slice().iter().enumerate(), + } + } +} + +/// Mutable map iterator +/// +/// This struct is created by `iter_mut` method or `into_iter` on a mutable +/// reference to `EnumMap`. +/// +/// # Examples +/// +/// ``` +/// use enum_map::{enum_map, Enum}; +/// +/// #[derive(Debug, Enum)] +/// enum Example { +/// A, +/// B, +/// C, +/// } +/// +/// let mut map = enum_map! { Example::A => 3, _ => 0 }; +/// for (_, value) in &mut map { +/// *value += 1; +/// } +/// assert_eq!(map, enum_map! { Example::A => 4, _ => 1 }); +/// ``` +#[derive(Debug)] +pub struct IterMut<'a, K, V: 'a> { + _phantom: PhantomData K>, + iterator: Enumerate>, +} + +impl<'a, K: EnumArray, V> Iterator for IterMut<'a, K, V> { + type Item = (K, &'a mut V); + #[inline] + fn next(&mut self) -> Option { + self.iterator + .next() + .map(|(index, item)| (K::from_usize(index), item)) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iterator.size_hint() + } + + fn fold(self, init: B, f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + self.iterator + .map(|(index, item)| (K::from_usize(index), item)) + .fold(init, f) + } +} + +impl<'a, K: EnumArray, V> DoubleEndedIterator for IterMut<'a, K, V> { + #[inline] + fn next_back(&mut self) -> Option { + self.iterator + .next_back() + .map(|(index, item)| (K::from_usize(index), item)) + } +} + +impl<'a, K: EnumArray, V> ExactSizeIterator for IterMut<'a, K, V> {} + +impl<'a, K: EnumArray, V> FusedIterator for IterMut<'a, K, V> {} + +impl<'a, K: EnumArray, V> IntoIterator for &'a mut EnumMap { + type Item = (K, &'a mut V); + type IntoIter = IterMut<'a, K, V>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + IterMut { + _phantom: PhantomData, + iterator: self.as_mut_slice().iter_mut().enumerate(), + } + } +} + +/// A map iterator that moves out of map. +/// +/// This struct is created by `into_iter` on `EnumMap`. +/// +/// # Examples +/// +/// ``` +/// use enum_map::{enum_map, Enum}; +/// +/// #[derive(Debug, Enum)] +/// enum Example { +/// A, +/// B, +/// } +/// +/// let map = enum_map! { Example::A | Example::B => String::from("123") }; +/// for (_, value) in map { +/// assert_eq!(value + "4", "1234"); +/// } +/// ``` +pub struct IntoIter, V> { + map: ManuallyDrop>, + alive: Range, +} + +impl, V> Iterator for IntoIter { + type Item = (K, V); + fn next(&mut self) -> Option<(K, V)> { + let position = self.alive.next()?; + Some((K::from_usize(position), unsafe { + ptr::read(&self.map.as_slice()[position]) + })) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.alive.size_hint() + } +} + +impl, V> DoubleEndedIterator for IntoIter { + fn next_back(&mut self) -> Option<(K, V)> { + let position = self.alive.next_back()?; + Some((K::from_usize(position), unsafe { + ptr::read(&self.map.as_slice()[position]) + })) + } +} + +impl, V> ExactSizeIterator for IntoIter {} + +impl, V> FusedIterator for IntoIter {} + +impl, V> Drop for IntoIter { + #[inline] + fn drop(&mut self) { + unsafe { + ptr::drop_in_place(&mut self.map.as_mut_slice()[self.alive.clone()]); + } + } +} + +impl, V> IntoIterator for EnumMap { + type Item = (K, V); + type IntoIter = IntoIter; + #[inline] + fn into_iter(self) -> Self::IntoIter { + let len = self.len(); + IntoIter { + map: ManuallyDrop::new(self), + alive: 0..len, + } + } +} + +impl, V> EnumMap { + /// An iterator visiting all values. The iterator type is `&V`. + /// + /// # Examples + /// + /// ``` + /// use enum_map::enum_map; + /// + /// let map = enum_map! { false => 3, true => 4 }; + /// let mut values = map.values(); + /// assert_eq!(values.next(), Some(&3)); + /// assert_eq!(values.next(), Some(&4)); + /// assert_eq!(values.next(), None); + /// ``` + #[inline] + pub fn values(&self) -> Values { + Values(self.as_slice().iter()) + } + + /// An iterator visiting all values mutably. The iterator type is `&mut V`. + /// + /// # Examples + /// + /// ``` + /// use enum_map::enum_map; + /// + /// let mut map = enum_map! { _ => 2 }; + /// for value in map.values_mut() { + /// *value += 2; + /// } + /// assert_eq!(map[false], 4); + /// assert_eq!(map[true], 4); + /// ``` + #[inline] + pub fn values_mut(&mut self) -> ValuesMut { + ValuesMut(self.as_mut_slice().iter_mut()) + } + + /// Creates a consuming iterator visiting all the values. The map + /// cannot be used after calling this. The iterator element type + /// is `V`. + /// + /// # Examples + /// + /// ``` + /// use enum_map::enum_map; + /// + /// let mut map = enum_map! { false => "hello", true => "goodbye" }; + /// assert_eq!(map.into_values().collect::>(), ["hello", "goodbye"]); + /// ``` + #[inline] + pub fn into_values(self) -> IntoValues { + IntoValues { + inner: self.into_iter(), + } + } +} + +/// An iterator over the values of `EnumMap`. +/// +/// This `struct` is created by the `values` method of `EnumMap`. +/// See its documentation for more. +pub struct Values<'a, V: 'a>(slice::Iter<'a, V>); + +impl<'a, V> Clone for Values<'a, V> { + fn clone(&self) -> Self { + Values(self.0.clone()) + } +} + +impl<'a, V: 'a> Iterator for Values<'a, V> { + type Item = &'a V; + #[inline] + fn next(&mut self) -> Option<&'a V> { + self.0.next() + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.0.size_hint() + } +} + +impl<'a, V: 'a> DoubleEndedIterator for Values<'a, V> { + #[inline] + fn next_back(&mut self) -> Option<&'a V> { + self.0.next_back() + } +} + +impl<'a, V: 'a> ExactSizeIterator for Values<'a, V> {} + +impl<'a, V: 'a> FusedIterator for Values<'a, V> {} + +/// A mutable iterator over the values of `EnumMap`. +/// +/// This `struct` is created by the `values_mut` method of `EnumMap`. +/// See its documentation for more. +pub struct ValuesMut<'a, V: 'a>(slice::IterMut<'a, V>); + +impl<'a, V: 'a> Iterator for ValuesMut<'a, V> { + type Item = &'a mut V; + #[inline] + fn next(&mut self) -> Option<&'a mut V> { + self.0.next() + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.0.size_hint() + } +} + +impl<'a, V: 'a> DoubleEndedIterator for ValuesMut<'a, V> { + #[inline] + fn next_back(&mut self) -> Option<&'a mut V> { + self.0.next_back() + } +} + +impl<'a, V: 'a> ExactSizeIterator for ValuesMut<'a, V> {} + +impl<'a, V: 'a> FusedIterator for ValuesMut<'a, V> {} + +/// An owning iterator over the values of an `EnumMap`. +/// +/// This `struct` is created by the `into_values` method of `EnumMap`. +/// See its documentation for more. +pub struct IntoValues, V> { + inner: IntoIter, +} + +impl Iterator for IntoValues +where + K: EnumArray, +{ + type Item = V; + + fn next(&mut self) -> Option { + Some(self.inner.next()?.1) + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +impl, V> DoubleEndedIterator for IntoValues { + fn next_back(&mut self) -> Option { + Some(self.inner.next_back()?.1) + } +} + +impl ExactSizeIterator for IntoValues where K: EnumArray {} + +impl FusedIterator for IntoValues where K: EnumArray {} diff --git a/third_party/rust/enum-map/src/lib.rs b/third_party/rust/enum-map/src/lib.rs new file mode 100644 index 0000000000..cb933a3a5c --- /dev/null +++ b/third_party/rust/enum-map/src/lib.rs @@ -0,0 +1,509 @@ +// SPDX-FileCopyrightText: 2017 - 2023 Kamila Borowska +// SPDX-FileCopyrightText: 2019 Riey +// SPDX-FileCopyrightText: 2021 Alex Sayers +// SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann +// SPDX-FileCopyrightText: 2022 Cass Fridkin +// SPDX-FileCopyrightText: 2022 Mateusz Kowalczyk +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! An enum mapping type. +//! +//! It is implemented using an array type, so using it is as fast as using Rust +//! arrays. +//! +//! # Examples +//! +//! ``` +//! use enum_map::{enum_map, Enum, EnumMap}; +//! +//! #[derive(Debug, Enum)] +//! enum Example { +//! A(bool), +//! B, +//! C, +//! } +//! +//! let mut map = enum_map! { +//! Example::A(false) => 0, +//! Example::A(true) => 1, +//! Example::B => 2, +//! Example::C => 3, +//! }; +//! map[Example::C] = 4; +//! +//! assert_eq!(map[Example::A(true)], 1); +//! +//! for (key, &value) in &map { +//! println!("{:?} has {} as value.", key, value); +//! } +//! ``` + +#![no_std] +#![deny(missing_docs)] +#![warn(clippy::pedantic)] + +#[cfg(feature = "arbitrary")] +mod arbitrary; +mod enum_map_impls; +mod internal; +mod iter; +#[cfg(feature = "serde")] +mod serde; + +#[doc(hidden)] +pub use core::mem::{self, ManuallyDrop, MaybeUninit}; +#[doc(hidden)] +pub use core::primitive::usize; +use core::slice; +#[doc(hidden)] +// unreachable needs to be exported for compatibility with older versions of enum-map-derive +pub use core::{panic, ptr, unreachable}; +pub use enum_map_derive::Enum; +#[doc(hidden)] +pub use internal::out_of_bounds; +use internal::Array; +pub use internal::{Enum, EnumArray}; +pub use iter::{IntoIter, IntoValues, Iter, IterMut, Values, ValuesMut}; + +// SAFETY: initialized needs to represent number of initialized elements +#[doc(hidden)] +pub struct Guard<'a, K, V> +where + K: EnumArray, +{ + array_mut: &'a mut MaybeUninit, + initialized: usize, +} + +impl Drop for Guard<'_, K, V> +where + K: EnumArray, +{ + fn drop(&mut self) { + // This is safe as arr[..len] is initialized due to + // Guard's type invariant. + unsafe { + ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.initialized).drop_in_place(); + } + } +} + +impl<'a, K, V> Guard<'a, K, V> +where + K: EnumArray, +{ + #[doc(hidden)] + pub fn as_mut_ptr(&mut self) -> *mut V { + self.array_mut.as_mut_ptr().cast::() + } + + #[doc(hidden)] + #[must_use] + pub fn new(array_mut: &'a mut MaybeUninit) -> Self { + Self { + array_mut, + initialized: 0, + } + } + + #[doc(hidden)] + #[must_use] + #[allow(clippy::unused_self)] + pub fn storage_length(&self) -> usize { + // SAFETY: We need to use LENGTH from K::Array, as K::LENGTH is + // untrustworthy. + K::Array::LENGTH + } + + #[doc(hidden)] + #[must_use] + pub fn get_key(&self) -> K { + K::from_usize(self.initialized) + } + + #[doc(hidden)] + // Unsafe as it can write out of bounds. + pub unsafe fn push(&mut self, value: V) { + self.as_mut_ptr().add(self.initialized).write(value); + self.initialized += 1; + } +} + +#[doc(hidden)] +pub struct TypeEqualizer<'a, K, V> +where + K: EnumArray, +{ + pub enum_map: [EnumMap; 0], + pub guard: Guard<'a, K, V>, +} + +/// Enum map constructor. +/// +/// This macro allows to create a new enum map in a type safe way. It takes +/// a list of `,` separated pairs separated by `=>`. Left side is `|` +/// separated list of enum keys, or `_` to match all unmatched enum keys, +/// while right side is a value. +/// +/// The iteration order when using this macro is not guaranteed to be +/// consistent. Future releases of this crate may change it, and this is not +/// considered to be a breaking change. +/// +/// # Examples +/// +/// ``` +/// use enum_map::{enum_map, Enum}; +/// +/// #[derive(Enum)] +/// enum Example { +/// A, +/// B, +/// C, +/// D, +/// } +/// +/// let enum_map = enum_map! { +/// Example::A | Example::B => 1, +/// Example::C => 2, +/// _ => 3, +/// }; +/// assert_eq!(enum_map[Example::A], 1); +/// assert_eq!(enum_map[Example::B], 1); +/// assert_eq!(enum_map[Example::C], 2); +/// assert_eq!(enum_map[Example::D], 3); +/// ``` +#[macro_export] +macro_rules! enum_map { + {$($t:tt)*} => {{ + let mut uninit = $crate::MaybeUninit::uninit(); + let mut eq = $crate::TypeEqualizer { + enum_map: [], + guard: $crate::Guard::new(&mut uninit), + }; + if false { + // Safe because this code is unreachable + unsafe { (&mut eq.enum_map).as_mut_ptr().read() } + } else { + for _ in 0..(&eq.guard).storage_length() { + struct __PleaseDoNotUseBreakWithoutLabel; + let _please_do_not_use_continue_without_label; + let value; + #[allow(unreachable_code)] + loop { + _please_do_not_use_continue_without_label = (); + value = match (&eq.guard).get_key() { $($t)* }; + break __PleaseDoNotUseBreakWithoutLabel; + }; + + unsafe { (&mut eq.guard).push(value); } + } + $crate::mem::forget(eq); + // Safe because the array was fully initialized. + $crate::EnumMap::from_array(unsafe { uninit.assume_init() }) + } + }}; +} + +/// An enum mapping. +/// +/// This internally uses an array which stores a value for each possible +/// enum value. To work, it requires implementation of internal (private, +/// although public due to macro limitations) trait which allows extracting +/// information about an enum, which can be automatically generated using +/// `#[derive(Enum)]` macro. +/// +/// Additionally, `bool` and `u8` automatically derives from `Enum`. While +/// `u8` is not technically an enum, it's convenient to consider it like one. +/// In particular, [reverse-complement in benchmark game] could be using `u8` +/// as an enum. +/// +/// # Examples +/// +/// ``` +/// use enum_map::{enum_map, Enum, EnumMap}; +/// +/// #[derive(Enum)] +/// enum Example { +/// A, +/// B, +/// C, +/// } +/// +/// let mut map = EnumMap::default(); +/// // new initializes map with default values +/// assert_eq!(map[Example::A], 0); +/// map[Example::A] = 3; +/// assert_eq!(map[Example::A], 3); +/// ``` +/// +/// [reverse-complement in benchmark game]: +/// http://benchmarksgame.alioth.debian.org/u64q/program.php?test=revcomp&lang=rust&id=2 +pub struct EnumMap, V> { + array: K::Array, +} + +impl, V: Default> EnumMap { + /// Clear enum map with default values. + /// + /// # Examples + /// + /// ``` + /// use enum_map::{Enum, EnumMap}; + /// + /// #[derive(Enum)] + /// enum Example { + /// A, + /// B, + /// } + /// + /// let mut enum_map = EnumMap::<_, String>::default(); + /// enum_map[Example::B] = "foo".into(); + /// enum_map.clear(); + /// assert_eq!(enum_map[Example::A], ""); + /// assert_eq!(enum_map[Example::B], ""); + /// ``` + #[inline] + pub fn clear(&mut self) { + for v in self.as_mut_slice() { + *v = V::default(); + } + } +} + +#[allow(clippy::len_without_is_empty)] +impl, V> EnumMap { + /// Creates an enum map from array. + #[inline] + pub const fn from_array(array: K::Array) -> EnumMap { + EnumMap { array } + } + + /// Create an enum map, where each value is the returned value from `cb` + /// using provided enum key. + /// + /// ``` + /// # use enum_map_derive::*; + /// use enum_map::{enum_map, Enum, EnumMap}; + /// + /// #[derive(Enum, PartialEq, Debug)] + /// enum Example { + /// A, + /// B, + /// } + /// + /// let map = EnumMap::from_fn(|k| k == Example::A); + /// assert_eq!(map, enum_map! { Example::A => true, Example::B => false }) + /// ``` + pub fn from_fn(mut cb: F) -> Self + where + F: FnMut(K) -> V, + { + enum_map! { k => cb(k) } + } + + /// Returns an iterator over enum map. + /// + /// The iteration order is deterministic, and when using [macro@Enum] derive + /// it will be the order in which enum variants are declared. + /// + /// # Examples + /// + /// ``` + /// use enum_map::{enum_map, Enum}; + /// + /// #[derive(Enum, PartialEq)] + /// enum E { + /// A, + /// B, + /// C, + /// } + /// + /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; + /// assert!(map.iter().eq([(E::A, &1), (E::B, &2), (E::C, &3)])); + /// ``` + #[inline] + pub fn iter(&self) -> Iter { + self.into_iter() + } + + /// Returns a mutable iterator over enum map. + #[inline] + pub fn iter_mut(&mut self) -> IterMut { + self.into_iter() + } + + /// Returns number of elements in enum map. + #[inline] + #[allow(clippy::unused_self)] + pub const fn len(&self) -> usize { + K::Array::LENGTH + } + + /// Swaps two indexes. + /// + /// # Examples + /// + /// ``` + /// use enum_map::enum_map; + /// + /// let mut map = enum_map! { false => 0, true => 1 }; + /// map.swap(false, true); + /// assert_eq!(map[false], 1); + /// assert_eq!(map[true], 0); + /// ``` + #[inline] + pub fn swap(&mut self, a: K, b: K) { + self.as_mut_slice().swap(a.into_usize(), b.into_usize()); + } + + /// Consumes an enum map and returns the underlying array. + /// + /// The order of elements is deterministic, and when using [macro@Enum] + /// derive it will be the order in which enum variants are declared. + /// + /// # Examples + /// + /// ``` + /// use enum_map::{enum_map, Enum}; + /// + /// #[derive(Enum, PartialEq)] + /// enum E { + /// A, + /// B, + /// C, + /// } + /// + /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; + /// assert_eq!(map.into_array(), [1, 2, 3]); + /// ``` + pub fn into_array(self) -> K::Array { + self.array + } + + /// Returns a reference to the underlying array. + /// + /// The order of elements is deterministic, and when using [macro@Enum] + /// derive it will be the order in which enum variants are declared. + /// + /// # Examples + /// + /// ``` + /// use enum_map::{enum_map, Enum}; + /// + /// #[derive(Enum, PartialEq)] + /// enum E { + /// A, + /// B, + /// C, + /// } + /// + /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; + /// assert_eq!(map.as_array(), &[1, 2, 3]); + /// ``` + pub const fn as_array(&self) -> &K::Array { + &self.array + } + + /// Returns a mutable reference to the underlying array. + /// + /// The order of elements is deterministic, and when using [macro@Enum] + /// derive it will be the order in which enum variants are declared. + /// + /// # Examples + /// + /// ``` + /// use enum_map::{enum_map, Enum}; + /// + /// #[derive(Enum, PartialEq)] + /// enum E { + /// A, + /// B, + /// C, + /// } + /// + /// let mut map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; + /// map.as_mut_array()[1] = 42; + /// assert_eq!(map.as_array(), &[1, 42, 3]); + /// ``` + pub fn as_mut_array(&mut self) -> &mut K::Array { + &mut self.array + } + + /// Converts an enum map to a slice representing values. + /// + /// The order of elements is deterministic, and when using [macro@Enum] + /// derive it will be the order in which enum variants are declared. + /// + /// # Examples + /// + /// ``` + /// use enum_map::{enum_map, Enum}; + /// + /// #[derive(Enum, PartialEq)] + /// enum E { + /// A, + /// B, + /// C, + /// } + /// + /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; + /// assert_eq!(map.as_slice(), &[1, 2, 3]); + /// ``` + #[inline] + pub fn as_slice(&self) -> &[V] { + unsafe { slice::from_raw_parts(ptr::addr_of!(self.array).cast(), K::Array::LENGTH) } + } + + /// Converts a mutable enum map to a mutable slice representing values. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [V] { + unsafe { slice::from_raw_parts_mut(ptr::addr_of_mut!(self.array).cast(), K::Array::LENGTH) } + } + + /// Returns an enum map with function `f` applied to each element in order. + /// + /// # Examples + /// + /// ``` + /// use enum_map::enum_map; + /// + /// let a = enum_map! { false => 0, true => 1 }; + /// let b = a.map(|_, x| f64::from(x) + 0.5); + /// assert_eq!(b, enum_map! { false => 0.5, true => 1.5 }); + /// ``` + pub fn map(self, mut f: F) -> EnumMap + where + F: FnMut(K, V) -> T, + K: EnumArray, + { + struct DropOnPanic + where + K: EnumArray, + { + position: usize, + map: ManuallyDrop>, + } + impl Drop for DropOnPanic + where + K: EnumArray, + { + fn drop(&mut self) { + unsafe { + ptr::drop_in_place(&mut self.map.as_mut_slice()[self.position..]); + } + } + } + let mut drop_protect = DropOnPanic { + position: 0, + map: ManuallyDrop::new(self), + }; + enum_map! { + k => { + let value = unsafe { ptr::read(&drop_protect.map.as_slice()[drop_protect.position]) }; + drop_protect.position += 1; + f(k, value) + } + } + } +} diff --git a/third_party/rust/enum-map/src/serde.rs b/third_party/rust/enum-map/src/serde.rs new file mode 100644 index 0000000000..9ac434d5d0 --- /dev/null +++ b/third_party/rust/enum-map/src/serde.rs @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: 2017 - 2023 Kamila Borowska +// SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::{enum_map, EnumArray, EnumMap}; +use core::fmt; +use core::marker::PhantomData; +use serde::de::{self, Deserialize, Deserializer, Error, MapAccess, SeqAccess}; +use serde::ser::{Serialize, SerializeTuple, Serializer}; + +/// Requires crate feature `"serde"` +impl + Serialize, V: Serialize> Serialize for EnumMap { + fn serialize(&self, serializer: S) -> Result { + if serializer.is_human_readable() { + serializer.collect_map(self) + } else { + let mut tup = serializer.serialize_tuple(self.len())?; + for value in self.values() { + tup.serialize_element(value)?; + } + tup.end() + } + } +} + +/// Requires crate feature `"serde"` +impl<'de, K, V> Deserialize<'de> for EnumMap +where + K: EnumArray + EnumArray> + Deserialize<'de>, + V: Deserialize<'de>, +{ + fn deserialize>(deserializer: D) -> Result { + if deserializer.is_human_readable() { + deserializer.deserialize_map(HumanReadableVisitor(PhantomData)) + } else { + deserializer.deserialize_tuple(K::LENGTH, CompactVisitor(PhantomData)) + } + } +} + +struct HumanReadableVisitor(PhantomData<(K, V)>); + +impl<'de, K, V> de::Visitor<'de> for HumanReadableVisitor +where + K: EnumArray + EnumArray> + Deserialize<'de>, + V: Deserialize<'de>, +{ + type Value = EnumMap; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "a map") + } + + fn visit_map>(self, mut access: M) -> Result { + let mut entries = EnumMap::default(); + while let Some((key, value)) = access.next_entry()? { + entries[key] = Some(value); + } + for value in entries.values() { + value + .as_ref() + .ok_or_else(|| M::Error::custom("key not specified"))?; + } + Ok(enum_map! { key => entries[key].take().unwrap() }) + } +} + +struct CompactVisitor(PhantomData<(K, V)>); + +impl<'de, K, V> de::Visitor<'de> for CompactVisitor +where + K: EnumArray + EnumArray> + Deserialize<'de>, + V: Deserialize<'de>, +{ + type Value = EnumMap; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "a sequence") + } + + fn visit_seq>(self, mut access: M) -> Result { + let mut entries = EnumMap::default(); + let len = entries.len(); + { + let mut iter = entries.values_mut(); + while let Some(place) = iter.next() { + *place = Some(access.next_element()?.ok_or_else(|| { + M::Error::invalid_length( + len - iter.len() - 1, + &"a sequence with as many elements as there are variants", + ) + })?); + } + } + Ok(enum_map! { key => entries[key].take().unwrap() }) + } +} diff --git a/third_party/rust/enum-map/tests/serde.rs b/third_party/rust/enum-map/tests/serde.rs new file mode 100644 index 0000000000..062ffe246a --- /dev/null +++ b/third_party/rust/enum-map/tests/serde.rs @@ -0,0 +1,115 @@ +#![cfg(feature = "serde")] + +// SPDX-FileCopyrightText: 2017 - 2022 Kamila Borowska +// SPDX-FileCopyrightText: 2022 Cass Fridkin +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use enum_map::{enum_map, Enum, EnumMap}; +use serde::{Deserialize, Serialize}; +use serde_test::{assert_de_tokens_error, assert_tokens, Compact, Configure, Token}; + +#[derive(Debug, Enum, Deserialize, Serialize)] +enum Example { + A, + B, +} + +#[test] +fn serialization() { + let map = enum_map! { Example::A => 5, Example::B => 10 }; + assert_tokens( + &map.readable(), + &[ + Token::Map { len: Some(2) }, + Token::UnitVariant { + name: "Example", + variant: "A", + }, + Token::I32(5), + Token::UnitVariant { + name: "Example", + variant: "B", + }, + Token::I32(10), + Token::MapEnd, + ], + ); +} + +#[test] +fn compact_serialization() { + let map = enum_map! { Example::A => 5, Example::B => 10 }; + assert_tokens( + &map.compact(), + &[ + Token::Tuple { len: 2 }, + Token::I32(5), + Token::I32(10), + Token::TupleEnd, + ], + ); +} + +#[test] +fn invalid_compact_deserialization() { + assert_de_tokens_error::>>( + &[Token::I32(4)], + "invalid type: integer `4`, expected a sequence", + ); +} + +#[test] +fn too_short_compact_deserialization() { + assert_de_tokens_error::>>( + &[Token::Seq { len: None }, Token::Bool(true), Token::SeqEnd], + "invalid length 1, expected a sequence with as many elements as there are variants", + ); +} + +const JSON: &str = r#"{"A":5,"B":10}"#; + +#[test] +fn json_serialization() { + let map = enum_map! { Example::A => 5, Example::B => 10 }; + assert_eq!(serde_json::to_string(&map).unwrap(), String::from(JSON)); +} + +#[test] +fn json_deserialization() { + let example: EnumMap = serde_json::from_str(JSON).unwrap(); + assert_eq!(example, enum_map! { Example::A => 5, Example::B => 10 }); +} + +#[test] +fn json_invalid_deserialization() { + let example: Result, _> = serde_json::from_str(r"{}"); + assert!(example.is_err()); +} + +#[test] +fn json_invalid_type() { + let example: Result, _> = serde_json::from_str("4"); + assert!(example.is_err()); +} + +#[test] +fn json_invalid_key() { + let example: Result, _> = + serde_json::from_str(r#"{"a": 5, "b": 10, "c": 6}"#); + assert!(example.is_err()); +} + +#[test] +fn bincode_serialization() { + let example = enum_map! { false => 3u8, true => 4u8 }; + let serialized = bincode::serialize(&example).unwrap(); + assert_eq!(example, bincode::deserialize(&serialized).unwrap()); +} + +#[test] +fn bincode_too_short_deserialization() { + assert!( + bincode::deserialize::>(&bincode::serialize(&()).unwrap()).is_err() + ); +} diff --git a/third_party/rust/enum-map/tests/test.rs b/third_party/rust/enum-map/tests/test.rs new file mode 100644 index 0000000000..66cea1fd1b --- /dev/null +++ b/third_party/rust/enum-map/tests/test.rs @@ -0,0 +1,696 @@ +// SPDX-FileCopyrightText: 2018 - 2022 Kamila Borowska +// SPDX-FileCopyrightText: 2019 Riey +// SPDX-FileCopyrightText: 2020 Amanieu d'Antras +// SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann +// SPDX-FileCopyrightText: 2021 micycle +// SPDX-FileCopyrightText: 2022 Cass Fridkin +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +#[macro_use] +extern crate enum_map; + +use enum_map::{Enum, EnumArray, EnumMap, IntoIter}; + +use std::cell::{Cell, RefCell}; +use std::collections::HashSet; +use std::convert::Infallible; +use std::marker::PhantomData; +use std::num::ParseIntError; +use std::panic::{catch_unwind, UnwindSafe}; + +trait From: Sized { + fn from(_: T) -> Self { + unreachable!(); + } +} + +impl From for U {} + +#[derive(Copy, Clone, Debug, Enum, PartialEq)] +enum Example { + A, + B, + C, +} + +#[test] +fn test_bool() { + let mut map = enum_map! { false => 24, true => 42 }; + assert_eq!(map[false], 24); + assert_eq!(map[true], 42); + map[false] += 1; + assert_eq!(map[false], 25); + for (key, item) in &mut map { + if !key { + *item += 1; + } + } + assert_eq!(map[false], 26); + assert_eq!(map[true], 42); +} + +#[test] +fn test_clone() { + let map = enum_map! { false => 3, true => 5 }; + assert_eq!(map.clone(), map); +} + +#[test] +fn test_debug() { + let map = enum_map! { false => 3, true => 5 }; + assert_eq!(format!("{:?}", map), "{false: 3, true: 5}"); +} + +#[test] +fn test_hash() { + let map = enum_map! { false => 3, true => 5 }; + let mut set = HashSet::new(); + set.insert(map); + assert!(set.contains(&map)); +} + +#[test] +fn test_clear() { + let mut map = enum_map! { false => 1, true => 2 }; + map.clear(); + assert_eq!(map[true], 0); + assert_eq!(map[false], 0); +} + +#[test] +fn struct_of_enum() { + #[derive(Copy, Clone, Debug, Enum, PartialEq)] + struct Product { + example: Example, + is_done: bool, + } + + let mut map = enum_map! { + Product { example: Example::A, is_done: false } => "foo", + Product { example: Example::B, is_done: false } => "bar", + Product { example: Example::C, is_done: false } => "baz", + Product { example: Example::A, is_done: true } => "done foo", + Product { example: Example::B, is_done: true } => "bar done", + Product { example: Example::C, is_done: true } => "doooozne", + }; + + assert_eq!( + map[Product { + example: Example::B, + is_done: false + }], + "bar" + ); + assert_eq!( + map[Product { + example: Example::C, + is_done: false + }], + "baz" + ); + assert_eq!( + map[Product { + example: Example::B, + is_done: true + }], + "bar done" + ); + + map[Product { + example: Example::B, + is_done: true, + }] = "not really done"; + assert_eq!( + map[Product { + example: Example::B, + is_done: false + }], + "bar" + ); + assert_eq!( + map[Product { + example: Example::C, + is_done: false + }], + "baz" + ); + assert_eq!( + map[Product { + example: Example::B, + is_done: true + }], + "not really done" + ); +} + +#[test] +fn tuple_struct_of_enum() { + #[derive(Copy, Clone, Debug, Enum, PartialEq)] + struct Product(Example, bool); + + let mut map = enum_map! { + Product(Example::A, false) => "foo", + Product(Example::B, false) => "bar", + Product(Example::C, false) => "baz", + Product(Example::A, true) => "done foo", + Product(Example::B, true) => "bar done", + Product(Example::C, true) => "doooozne", + }; + + assert_eq!(map[Product(Example::B, false)], "bar"); + assert_eq!(map[Product(Example::C, false)], "baz"); + assert_eq!(map[Product(Example::B, true)], "bar done"); + + map[Product(Example::B, true)] = "not really done"; + assert_eq!(map[Product(Example::B, false)], "bar"); + assert_eq!(map[Product(Example::C, false)], "baz"); + assert_eq!(map[Product(Example::B, true)], "not really done"); +} + +#[test] +fn discriminants() { + #[derive(Debug, Enum, PartialEq)] + enum Discriminants { + A = 2000, + B = 3000, + C = 1000, + } + let mut map = EnumMap::default(); + map[Discriminants::A] = 3; + map[Discriminants::B] = 2; + map[Discriminants::C] = 1; + let mut pairs = map.iter(); + assert_eq!(pairs.next(), Some((Discriminants::A, &3))); + assert_eq!(pairs.next(), Some((Discriminants::B, &2))); + assert_eq!(pairs.next(), Some((Discriminants::C, &1))); + assert_eq!(pairs.next(), None); +} + +#[test] +fn extend() { + let mut map = enum_map! { _ => 0 }; + map.extend(vec![(Example::A, 3)]); + map.extend(vec![(&Example::B, &4)]); + assert_eq!( + map, + enum_map! { Example::A => 3, Example::B => 4, Example::C => 0 } + ); +} + +#[test] +fn collect() { + let iter = vec![(Example::A, 5), (Example::B, 7)] + .into_iter() + .map(|(k, v)| (k, v + 1)); + assert_eq!( + iter.collect::>(), + enum_map! { Example::A => 6, Example::B => 8, Example::C => 0 } + ); +} + +#[test] +fn huge_enum() { + #[derive(Enum)] + enum Example { + 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, + Aa, + Bb, + Cc, + Dd, + Ee, + Ff, + Gg, + Hh, + Ii, + Jj, + Kk, + Ll, + Mm, + Nn, + Oo, + Pp, + Qq, + Rr, + Ss, + Tt, + Uu, + Vv, + Ww, + Xx, + Yy, + Zz, + } + + let map = enum_map! { _ => 2 }; + assert_eq!(map[Example::Xx], 2); +} + +#[test] +fn iterator_len() { + assert_eq!( + enum_map! { Example::A | Example::B | Example::C => 0 } + .iter() + .len(), + 3 + ); +} + +#[test] +fn iter_mut_len() { + assert_eq!( + enum_map! { Example::A | Example::B | Example::C => 0 } + .iter_mut() + .len(), + 3 + ); +} + +#[test] +fn into_iter_len() { + assert_eq!(enum_map! { Example::A | _ => 0 }.into_iter().len(), 3); +} + +#[test] +fn iterator_next_back() { + assert_eq!( + enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } + .iter() + .next_back(), + Some((Example::C, &3)) + ); +} + +#[test] +fn iter_mut_next_back() { + assert_eq!( + enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } + .iter_mut() + .next_back(), + Some((Example::C, &mut 3)) + ); +} + +#[test] +fn into_iter() { + let mut iter = enum_map! { true => 5, false => 7 }.into_iter(); + assert_eq!(iter.next(), Some((false, 7))); + assert_eq!(iter.next(), Some((true, 5))); + assert_eq!(iter.next(), None); + assert_eq!(iter.next(), None); +} + +#[test] +fn into_iter_u8() { + assert_eq!( + enum_map! { i => i }.into_iter().collect::>(), + (0..256).map(|x| (x as u8, x as u8)).collect::>() + ); +} + +struct DropReporter<'a> { + into: &'a RefCell>, + value: usize, +} + +impl<'a> Drop for DropReporter<'a> { + fn drop(&mut self) { + self.into.borrow_mut().push(self.value); + } +} + +#[test] +fn into_iter_drop() { + let dropped = RefCell::new(Vec::default()); + let mut a: IntoIter = enum_map! { + k => DropReporter { + into: &dropped, + value: k as usize, + }, + } + .into_iter(); + assert_eq!(a.next().unwrap().0, Example::A); + assert_eq!(*dropped.borrow(), &[0]); + drop(a); + assert_eq!(*dropped.borrow(), &[0, 1, 2]); +} + +#[test] +fn into_iter_double_ended_iterator() { + let mut iter = enum_map! { 0 => 5, 255 => 7, _ => 0 }.into_iter(); + assert_eq!(iter.next(), Some((0, 5))); + assert_eq!(iter.next_back(), Some((255, 7))); + assert_eq!(iter.next(), Some((1, 0))); + assert_eq!(iter.next_back(), Some((254, 0))); + assert!(iter.rev().eq((2..254).rev().map(|i| (i, 0)))); +} + +#[test] +fn values_rev_collect() { + assert_eq!( + vec![3, 2, 1], + enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } + .values() + .rev() + .cloned() + .collect::>() + ); +} + +#[test] +fn values_len() { + assert_eq!(enum_map! { false => 0, true => 1 }.values().len(), 2); +} + +#[test] +fn into_values_rev_collect() { + assert_eq!( + vec![3, 2, 1], + enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } + .into_values() + .rev() + .collect::>() + ); +} + +#[test] +fn into_values_len() { + assert_eq!(enum_map! { false => 0, true => 1 }.into_values().len(), 2); +} + +#[test] +fn values_mut_next_back() { + let mut map = enum_map! { false => 0, true => 1 }; + assert_eq!(map.values_mut().next_back(), Some(&mut 1)); +} +#[test] +fn test_u8() { + let mut map = enum_map! { b'a' => 4, _ => 0 }; + map[b'c'] = 3; + assert_eq!(map[b'a'], 4); + assert_eq!(map[b'b'], 0); + assert_eq!(map[b'c'], 3); + assert_eq!(map.iter().next(), Some((0, &0))); +} + +#[derive(Enum)] +enum Void {} + +#[test] +fn empty_map() { + let void: EnumMap = enum_map! {}; + assert_eq!(void.len(), 0); +} + +#[test] +#[should_panic] +fn empty_value() { + let _void: EnumMap = enum_map! { _ => unreachable!() }; +} + +#[test] +fn empty_infallible_map() { + let void: EnumMap = enum_map! {}; + assert_eq!(void.len(), 0); +} + +#[derive(Clone, Copy)] +enum X { + A(PhantomData<*const ()>), +} + +impl Enum for X { + const LENGTH: usize = 1; + + fn from_usize(arg: usize) -> X { + assert_eq!(arg, 0); + X::A(PhantomData) + } + + fn into_usize(self) -> usize { + 0 + } +} + +impl EnumArray for X { + type Array = [V; Self::LENGTH]; +} + +fn assert_sync_send(_: T) {} + +#[test] +fn assert_enum_map_does_not_copy_sync_send_dependency_of_keys() { + let mut map = enum_map! { X::A(PhantomData) => true }; + assert_sync_send(map); + assert_sync_send(&map); + assert_sync_send(&mut map); + assert_sync_send(map.iter()); + assert_sync_send(map.iter_mut()); + assert_sync_send(map.into_iter()); + assert!(map[X::A(PhantomData)]); +} + +#[test] +fn test_sum() { + assert_eq!( + enum_map! { i => u8::into(i) } + .iter() + .map(|(_, v)| v) + .sum::(), + 32_640 + ); +} + +#[test] +fn test_sum_mut() { + assert_eq!( + enum_map! { i => u8::into(i) } + .iter_mut() + .map(|(_, &mut v)| -> u32 { v }) + .sum::(), + 32_640 + ); +} + +#[test] +fn test_iter_clone() { + struct S(u8); + let map = enum_map! { + Example::A => S(3), + Example::B => S(4), + Example::C => S(1), + }; + let iter = map.iter(); + assert_eq!(iter.clone().map(|(_, S(v))| v).sum::(), 8); + assert_eq!(iter.map(|(_, S(v))| v).sum::(), 8); + let values = map.values(); + assert_eq!(values.clone().map(|S(v)| v).sum::(), 8); + assert_eq!(values.map(|S(v)| v).sum::(), 8); +} + +#[test] +fn question_mark() -> Result<(), ParseIntError> { + let map = enum_map! { false => "2".parse()?, true => "5".parse()? }; + assert_eq!(map, enum_map! { false => 2, true => 5 }); + Ok(()) +} + +#[test] +fn question_mark_failure() { + struct IncOnDrop<'a>(&'a Cell); + + impl Drop for IncOnDrop<'_> { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + + fn failible() -> Result, &'static str> { + Err("ERROR!") + } + + fn try_block(inc: &Cell) -> Result<(), &'static str> { + enum_map! { + 32 => failible()?, + _ => { + IncOnDrop(inc) + } + }; + Ok(()) + } + let value = Cell::new(0); + assert_eq!(try_block(&value), Err("ERROR!")); + assert_eq!(value.get(), 32); +} + +#[test] +#[should_panic = "Intentional panic"] +fn map_panic() { + let map: EnumMap = enum_map! { i => i.to_string() }; + map.map(|k, v| { + if k == 2 { + panic!("Intentional panic"); + } + v + " modified" + }); +} + +macro_rules! make_enum_map_macro_safety_test { + ($a:tt $b:tt) => { + // This is misuse of an API, however we need to test that to ensure safety + // as we use unsafe code. + enum E { + A, + B, + C, + } + + impl Enum for E { + const LENGTH: usize = $a; + + fn from_usize(value: usize) -> E { + match value { + 0 => E::A, + 1 => E::B, + 2 => E::C, + _ => unimplemented!(), + } + } + + fn into_usize(self) -> usize { + self as usize + } + } + + impl EnumArray for E { + type Array = [V; $b]; + } + + let map: EnumMap = enum_map! { _ => "Hello, world!".into() }; + map.into_iter(); + }; +} + +#[test] +fn enum_map_macro_safety_under() { + make_enum_map_macro_safety_test!(2 3); +} + +#[test] +fn enum_map_macro_safety_over() { + make_enum_map_macro_safety_test!(3 2); +} + +#[test] +fn drop_panic_into_iter() { + struct DropHandler<'a>(&'a Cell); + impl Drop for DropHandler<'_> { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + impl UnwindSafe for DropHandler<'_> {} + struct Storage<'a> { + should_panic: bool, + _drop_handler: DropHandler<'a>, + } + impl Drop for Storage<'_> { + fn drop(&mut self) { + if self.should_panic { + panic!(); + } + } + } + let cell = Cell::new(0); + let map: EnumMap = enum_map! { + v => Storage { should_panic: v == Example::B, _drop_handler: DropHandler(&cell) }, + }; + assert!(catch_unwind(|| { + map.into_iter(); + }) + .is_err()); + assert_eq!(cell.get(), 3); +} + +#[test] +fn test_const_enum_map_from_array() { + const CONST_ENUM_MAP_FROM_ARRAY: EnumMap = EnumMap::from_array([4, 8]); + assert_eq!( + CONST_ENUM_MAP_FROM_ARRAY, + enum_map! { false => 4, true => 8 }, + ); +} + +#[test] +fn usize_override() { + #[allow(non_camel_case_types, dead_code)] + type usize = (); + #[derive(Enum)] + enum X { + A, + B, + } +} + +// Regression test for https://codeberg.org/xfix/enum-map/issues/112 +#[test] +fn test_issue_112() { + #[derive(Enum, PartialEq, Debug)] + enum Inner { + Inner1, + Inner2, + } + + #[derive(Enum, PartialEq, Debug)] + enum Outer { + A, + B(Inner), + C, + D(Inner, Inner), + E, + } + + assert_eq!(Outer::A.into_usize(), 0); + assert_eq!(Outer::A, Outer::from_usize(0)); + assert_eq!(Outer::B(Inner::Inner1).into_usize(), 1); + assert_eq!(Outer::B(Inner::Inner1), Outer::from_usize(1)); + assert_eq!(Outer::B(Inner::Inner2).into_usize(), 2); + assert_eq!(Outer::B(Inner::Inner2), Outer::from_usize(2)); + assert_eq!(Outer::C.into_usize(), 3); + assert_eq!(Outer::C, Outer::from_usize(3)); + assert_eq!(Outer::D(Inner::Inner1, Inner::Inner1).into_usize(), 4); + assert_eq!(Outer::D(Inner::Inner1, Inner::Inner1), Outer::from_usize(4)); + assert_eq!(Outer::D(Inner::Inner2, Inner::Inner1).into_usize(), 5); + assert_eq!(Outer::D(Inner::Inner2, Inner::Inner1), Outer::from_usize(5)); + assert_eq!(Outer::D(Inner::Inner1, Inner::Inner2).into_usize(), 6); + assert_eq!(Outer::D(Inner::Inner1, Inner::Inner2), Outer::from_usize(6)); + assert_eq!(Outer::D(Inner::Inner2, Inner::Inner2).into_usize(), 7); + assert_eq!(Outer::D(Inner::Inner2, Inner::Inner2), Outer::from_usize(7)); + assert_eq!(Outer::E.into_usize(), 8); + assert_eq!(Outer::E, Outer::from_usize(8)); +} -- cgit v1.2.3