├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ └── dependency-review.yml ├── .gitignore ├── .reuse └── dep5 ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.lock.license ├── Cargo.toml ├── LICENSES ├── Apache-2.0.txt ├── CC0-1.0.txt └── MIT.txt ├── README.md ├── enum-map-derive ├── Cargo.toml ├── LICENSES ├── README.md └── src │ ├── derive_enum.rs │ ├── derive_struct.rs │ └── lib.rs └── enum-map ├── CHANGELOG.md ├── Cargo.toml ├── LICENSES ├── README.md ├── src ├── arbitrary.rs ├── enum_map_impls.rs ├── internal.rs ├── iter.rs ├── lib.rs └── serde.rs └── tests ├── serde.rs └── test.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 - 2023 Konrad Borowski 2 | # 3 | # SPDX-License-Identifier: MIT OR Apache-2.0 4 | 5 | version: 2 6 | updates: 7 | - package-ecosystem: cargo 8 | directory: / 9 | schedule: 10 | interval: daily 11 | ignore: 12 | - dependency-name: "*" 13 | update-types: 14 | - "version-update:semver-minor" 15 | - "version-update:semver-patch" 16 | - package-ecosystem: github-actions 17 | directory: / 18 | schedule: 19 | interval: daily 20 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 - 2023 Konrad Borowski 2 | # 3 | # SPDX-License-Identifier: MIT OR Apache-2.0 4 | 5 | name: CI 6 | 7 | on: 8 | push: 9 | pull_request: 10 | 11 | jobs: 12 | test: 13 | name: Test 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | toolchain: 18 | - 1.61 19 | - stable 20 | - beta 21 | - nightly 22 | steps: 23 | - uses: actions/checkout@v4 24 | - uses: dtolnay/rust-toolchain@master 25 | with: 26 | toolchain: ${{ matrix.toolchain }} 27 | - run: cargo build --verbose 28 | - run: cargo test --verbose 29 | 30 | rustfmt: 31 | name: Rustfmt 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v4 35 | - uses: dtolnay/rust-toolchain@stable 36 | with: 37 | components: rustfmt 38 | - run: cargo fmt --all --check 39 | 40 | msrv: 41 | name: Verify MSRV 42 | runs-on: ubuntu-latest 43 | steps: 44 | - uses: actions/checkout@v4 45 | - uses: cachix/install-nix-action@v23 46 | with: 47 | nix_path: nixpkgs=channel:nixos-unstable 48 | - run: nix-env -iA cargo-msrv -f '' 49 | - run: cargo msrv --path=enum-map verify 50 | - run: cargo msrv --path=enum-map-derive verify 51 | 52 | reuse-lint: 53 | name: Verify REUSE compliance 54 | runs-on: ubuntu-latest 55 | steps: 56 | - uses: actions/checkout@v4 57 | - uses: fsfe/reuse-action@v2 58 | -------------------------------------------------------------------------------- /.github/workflows/dependency-review.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Konrad Borowski 2 | # 3 | # SPDX-License-Identifier: MIT OR Apache-2.0 4 | 5 | name: Dependency Review 6 | on: [pull_request] 7 | jobs: 8 | dependency-review: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - uses: actions/dependency-review-action@v3 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 - 2023 Konrad Borowski 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 or MIT OR Apache-2.0 4 | 5 | target/ 6 | **/*.rs.bk 7 | -------------------------------------------------------------------------------- /.reuse/dep5: -------------------------------------------------------------------------------- 1 | Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: enum-map 3 | Upstream-Contact: Konrad Borowski 4 | Source: https://github.com/xfix/enum-map 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | # Version 2.6.2 9 | 10 | ## Other changes 11 | 12 | - Hide `out_of_bounds` reexport from documentation. 13 | 14 | # Version 2.6.1 15 | 16 | ## Other changes 17 | 18 | - Provide better panic message when providing out-of-bounds index 19 | to `Enum::from_usize``. 20 | 21 | # Version 2.6.0 22 | 23 | ## New features 24 | 25 | - `EnumMap::as_array` is now usable in const contexts. 26 | 27 | ## Other changes 28 | 29 | - This crate now follows "N minus two" MSRV policy. This means that 30 | it supports the current Rust release, as well as the two before 31 | that. 32 | 33 | - Upgraded syn to 2.0.0. 34 | 35 | # Version 2.5.0 36 | 37 | ## New features 38 | 39 | - Implemented `EnumMap::as_array` and `EnumMap::as_mut_array` 40 | (implemented by [@Fuuzetsu](https://github.com/Fuuzetsu)). 41 | 42 | - Implemented `PartialOrd` and `Ord` for `EnumMap` (implemented by 43 | [@nicarran](https://github.com/nicarran)). 44 | 45 | # Version 2.4.2 46 | 47 | ## Other changes 48 | 49 | - Added license files to crate tarball. 50 | - Added changelog to crate tarball. 51 | 52 | # Version 2.4.1 53 | 54 | ## Other changes 55 | 56 | - Improved performance of code generated for `from_usize` when 57 | deriving `Enum`. 58 | 59 | # Version 2.4.0 60 | 61 | ## New features 62 | 63 | - Implemented `Enum` for `()` (unit type) and `core::cmp::Ordering` 64 | (implemented by [@phimuemue](https://github.com/phimuemue)). 65 | 66 | - Implemented `EnumMap::into_array`. 67 | 68 | # Version 2.3.0 69 | 70 | ## New features 71 | 72 | - `EnumMap::len` is now usable in const contexts. 73 | 74 | ## Other changes 75 | 76 | - `Enum` derive now can deal with re-definitions of `usize` and 77 | `unimplemented`. 78 | 79 | # Version 2.2.0 80 | 81 | ## New features 82 | 83 | - `EnumMap::from_array` is now usable in const contexts. 84 | 85 | # Version 2.1.0 86 | 87 | ## New features 88 | 89 | - Implemented `DoubleEndedIterator` for `IntoIter`. 90 | 91 | - Implemented `EnumMap::into_values`. 92 | 93 | ## Other changes 94 | 95 | - Changed behavior of `IntoIter` so that it drops rest of the elements 96 | when one destructor panics. 97 | 98 | # Version 2.0.3 99 | 100 | ## Other changes 101 | 102 | - Optimized performance of `enum_map!` macro. 103 | 104 | # Version 2.0.2 105 | 106 | ## Other changes 107 | 108 | - Fixed safety problem when using `enum_map!` macro with enums that 109 | incorrectly implemented `Enum` trait. 110 | 111 | # Version 2.0.1 112 | 113 | ## Other changes 114 | 115 | - Adjusted crate metadata to avoid lib.rs warnings. 116 | 117 | # Version 2.0.0 118 | 119 | ## New features 120 | 121 | - Implemented `FromIterator` for `EnumMap` (implemented by @bit_network 122 | on GitLab). 123 | 124 | - Implemented `EnumMap::map`. 125 | 126 | - Derives support product types in addition to sum types (implemented 127 | by @bzim on GitLab). 128 | 129 | - It's now possible to access enum length by accessing `LENGTH` in 130 | `Enum` trait. 131 | 132 | ## Breaking changes 133 | 134 | - `Enum` trait was split into two traits, `Enum` and `EnumArray`. 135 | 136 | # Version 1.1.1 137 | 138 | ## Other changes 139 | 140 | - Worked around a bug in Clippy that caused false positives when using 141 | `use_self` lint for code that derived `Enum` trait. 142 | 143 | # Version 1.1.0 144 | 145 | ## New features 146 | 147 | - Implemented `Arbitrary` for maps where the value type also implements 148 | `Arbitrary`. (You have to enable the "arbitrary" feature.) 149 | 150 | # Version 1.0.0 151 | 152 | ## New features 153 | 154 | - It's now possible to use `return` and `?` within `macro_rules!` macro. 155 | 156 | - `Enum` trait is much simpler having two methods only. 157 | 158 | ## Other changes 159 | 160 | - Removed previously deprecated features. 161 | 162 | - Renamed `to_usize` to `into_usize` matching the naming convention 163 | used in Rust programming language. 164 | 165 | # Version 0.6.5 166 | 167 | ## Other changes 168 | 169 | - Deprecated `EnumMap::is_empty` and `EnumMap::new`. `EnumMap::new` usages 170 | can be replaced with `EnumMap::default`. 171 | 172 | # Version 0.6.4 173 | 174 | ## Other changes 175 | 176 | - Deprecated `EnumMap::as_ptr` and `EnumMap::as_mut_ptr`. 177 | 178 | # Version 0.6.3 179 | 180 | ## New features 181 | 182 | - `Iter` and `Values` now implements `Clone` (added by @amanieu). 183 | 184 | # Version 0.6.2. 185 | 186 | ## New features 187 | 188 | - Added `EnumMap#clear` method (added by @Riey, thanks :)). 189 | 190 | # Version 0.6.0 191 | 192 | ## Incompatible changes 193 | 194 | - Now requires Rust 1.36. 195 | 196 | # Version 0.5.0 197 | 198 | - Fixed the issue where an aliasing `From` trait implementation caused 199 | compilation errors with `enum_map!` macro. 200 | 201 | ## Incompatible changes 202 | 203 | - Now requires Rust 1.31. 204 | 205 | # Version 0.4.1 206 | 207 | ## New features 208 | 209 | - Default `serde` features are disabled. This allows enabling serde feature when 210 | compiling without `std`. 211 | 212 | # Version 0.4.0 213 | 214 | Change of `#[derive(EnumMap)]` to `#[derive(Enum)]` was supposed to appear in 0.3.0, 215 | but it was forgotten about. This release fixes just that. 216 | 217 | ## Incompatible changes 218 | 219 | - Changed `#[derive(EnumMap)]` to `#[derive(Enum)]` to match trait name. 220 | 221 | # Version 0.3.1 222 | 223 | - Updated README use `#[derive(EnumMap)]` instead of `#[derive(Enum)]`. 224 | 225 | # Version 0.3.0 226 | 227 | ## New features 228 | 229 | - Implemented compact serde serialization for binary formats like bincode. 230 | 231 | - Iterator traits with exception now implement `FusedIterator`. 232 | 233 | ## Incompatible changes 234 | 235 | - Increased required Rust version to 1.26.0. 236 | 237 | - Renamed `Internal` trait to `Enum`. 238 | 239 | - Added new associated constant `POSSIBLE_VALUES` to `Enum` trait, 240 | representing the number of possible values the type can have. Manual 241 | implementations are required to provide it. 242 | 243 | - Removed `Enum` implementation for `Option`. 244 | 245 | - Implemented compact serialization, for formats like `bincode`. This 246 | makes it impossible to deserialize non-compact representation used by 247 | enum-map 0.2.0. 248 | 249 | - `values` method returns `Values` as opposed to `slice::Iter`. 250 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "arbitrary" 7 | version = "1.3.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "e2d098ff73c1ca148721f37baad5ea6a465a13f9573aba8641fbbbae8164a54e" 10 | 11 | [[package]] 12 | name = "bincode" 13 | version = "1.3.3" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" 16 | dependencies = [ 17 | "serde", 18 | ] 19 | 20 | [[package]] 21 | name = "enum-map" 22 | version = "2.6.2" 23 | dependencies = [ 24 | "arbitrary", 25 | "bincode", 26 | "enum-map-derive", 27 | "serde", 28 | "serde_json", 29 | "serde_test", 30 | ] 31 | 32 | [[package]] 33 | name = "enum-map-derive" 34 | version = "0.13.0" 35 | dependencies = [ 36 | "enum-map", 37 | "proc-macro2", 38 | "quote", 39 | "syn", 40 | ] 41 | 42 | [[package]] 43 | name = "itoa" 44 | version = "1.0.9" 45 | source = "registry+https://github.com/rust-lang/crates.io-index" 46 | checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" 47 | 48 | [[package]] 49 | name = "proc-macro2" 50 | version = "1.0.66" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" 53 | dependencies = [ 54 | "unicode-ident", 55 | ] 56 | 57 | [[package]] 58 | name = "quote" 59 | version = "1.0.33" 60 | source = "registry+https://github.com/rust-lang/crates.io-index" 61 | checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" 62 | dependencies = [ 63 | "proc-macro2", 64 | ] 65 | 66 | [[package]] 67 | name = "ryu" 68 | version = "1.0.15" 69 | source = "registry+https://github.com/rust-lang/crates.io-index" 70 | checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" 71 | 72 | [[package]] 73 | name = "serde" 74 | version = "1.0.188" 75 | source = "registry+https://github.com/rust-lang/crates.io-index" 76 | checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" 77 | dependencies = [ 78 | "serde_derive", 79 | ] 80 | 81 | [[package]] 82 | name = "serde_derive" 83 | version = "1.0.188" 84 | source = "registry+https://github.com/rust-lang/crates.io-index" 85 | checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" 86 | dependencies = [ 87 | "proc-macro2", 88 | "quote", 89 | "syn", 90 | ] 91 | 92 | [[package]] 93 | name = "serde_json" 94 | version = "1.0.105" 95 | source = "registry+https://github.com/rust-lang/crates.io-index" 96 | checksum = "693151e1ac27563d6dbcec9dee9fbd5da8539b20fa14ad3752b2e6d363ace360" 97 | dependencies = [ 98 | "itoa", 99 | "ryu", 100 | "serde", 101 | ] 102 | 103 | [[package]] 104 | name = "serde_test" 105 | version = "1.0.176" 106 | source = "registry+https://github.com/rust-lang/crates.io-index" 107 | checksum = "5a2f49ace1498612d14f7e0b8245519584db8299541dfe31a06374a828d620ab" 108 | dependencies = [ 109 | "serde", 110 | ] 111 | 112 | [[package]] 113 | name = "syn" 114 | version = "2.0.29" 115 | source = "registry+https://github.com/rust-lang/crates.io-index" 116 | checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a" 117 | dependencies = [ 118 | "proc-macro2", 119 | "quote", 120 | "unicode-ident", 121 | ] 122 | 123 | [[package]] 124 | name = "unicode-ident" 125 | version = "1.0.11" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" 128 | -------------------------------------------------------------------------------- /Cargo.lock.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2023 Konrad Borowski 2 | 3 | SPDX-License-Identifier: CC0-1.0 or MIT OR Apache-2.0 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 - 2019 Konrad Borowski 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 or MIT OR Apache-2.0 4 | 5 | [workspace] 6 | members = [ 7 | "enum-map", 8 | "enum-map-derive", 9 | ] 10 | -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "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. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "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. 20 | 21 | "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). 22 | 23 | "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. 24 | 25 | "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." 26 | 27 | "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. 28 | 29 | 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. 30 | 31 | 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. 32 | 33 | 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: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (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 40 | 41 | (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. 42 | 43 | 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. 44 | 45 | 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. 46 | 47 | 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. 48 | 49 | 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. 50 | 51 | 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. 52 | 53 | 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. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | 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. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | -------------------------------------------------------------------------------- /LICENSES/CC0-1.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /LICENSES/MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 4 | 5 | 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: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | 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. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | This repository was migrated to Codeberg: https://codeberg.org/xfix/enum-map. 8 | -------------------------------------------------------------------------------- /enum-map-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 - 2023 Konrad Borowski 2 | # SPDX-FileCopyrightText: 2018 hcpl 3 | # 4 | # SPDX-License-Identifier: MIT OR Apache-2.0 5 | 6 | [package] 7 | name = "enum-map-derive" 8 | version = "0.13.0" 9 | authors = ["Konrad Borowski "] 10 | edition = "2021" 11 | rust-version = "1.61" 12 | repository = "https://github.com/xfix/enum-map" 13 | license = "MIT OR Apache-2.0" 14 | description = "Macros 1.1 implementation of #[derive(Enum)]" 15 | keywords = ["data-structure", "no_std", "enum"] 16 | categories = ["data-structures", "no-std"] 17 | 18 | [badges] 19 | maintenance = { status = "passively-maintained" } 20 | 21 | [lib] 22 | proc-macro = true 23 | 24 | [dependencies] 25 | proc-macro2 = "1.0.60" 26 | quote = "1.0.7" 27 | syn = { version = "2.0.0", default-features = false, features = ["derive", "parsing", "printing", "proc-macro"] } 28 | 29 | [dev-dependencies] 30 | enum-map = { path = "../enum-map" } 31 | -------------------------------------------------------------------------------- /enum-map-derive/LICENSES: -------------------------------------------------------------------------------- 1 | ../LICENSES -------------------------------------------------------------------------------- /enum-map-derive/README.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | # enum-map-derive 8 | 9 | This is a derive macro for `enum-map`. You don't need to specify it 10 | in dependencies as `enum-map` crate re-exports it. 11 | -------------------------------------------------------------------------------- /enum-map-derive/src/derive_enum.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2021 - 2023 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 3 | // 4 | // SPDX-License-Identifier: MIT OR Apache-2.0 5 | 6 | use crate::type_length; 7 | use proc_macro2::TokenStream; 8 | use quote::{format_ident, quote}; 9 | use syn::{DataEnum, Fields, FieldsNamed, FieldsUnnamed, Ident, Variant}; 10 | 11 | pub fn generate(name: Ident, data_enum: DataEnum) -> TokenStream { 12 | let mut generator = EnumGenerator::empty(); 13 | for variant in &data_enum.variants { 14 | generator.handle_variant(variant); 15 | } 16 | generator.finish(&name) 17 | } 18 | 19 | /// Total length is the sum of each variant's length. To represent a variant, its number is added to 20 | /// the sum of previous variant lengths. 21 | #[derive(Debug)] 22 | struct EnumGenerator { 23 | length: TokenStream, 24 | from_usize_arms: TokenStream, 25 | into_usize_arms: TokenStream, 26 | } 27 | 28 | impl EnumGenerator { 29 | fn empty() -> Self { 30 | Self { 31 | length: quote! { 0usize }, 32 | from_usize_arms: quote! {}, 33 | into_usize_arms: quote! {}, 34 | } 35 | } 36 | 37 | fn finish(&self, name: &Ident) -> TokenStream { 38 | let length = &self.length; 39 | let from_usize_arms = &self.from_usize_arms; 40 | let into_usize_arms = &self.into_usize_arms; 41 | 42 | quote! { 43 | #[automatically_derived] 44 | impl ::enum_map::Enum for #name { 45 | const LENGTH: ::enum_map::usize = #length; 46 | 47 | #[inline] 48 | fn from_usize(value: ::enum_map::usize) -> Self { 49 | #from_usize_arms { 50 | ::enum_map::out_of_bounds() 51 | } 52 | } 53 | 54 | #[inline] 55 | fn into_usize(self) -> ::enum_map::usize { 56 | match self { 57 | #into_usize_arms 58 | } 59 | } 60 | } 61 | 62 | #[automatically_derived] 63 | impl ::enum_map::EnumArray for #name { 64 | type Array = [V; #length]; 65 | } 66 | } 67 | } 68 | 69 | fn handle_variant(&mut self, variant: &Variant) { 70 | match &variant.fields { 71 | Fields::Unit => self.handle_unit_variant(&variant.ident), 72 | Fields::Unnamed(fields) => self.handle_unnamed_variant(&variant.ident, fields), 73 | Fields::Named(fields) => self.handle_named_variant(&variant.ident, fields), 74 | } 75 | } 76 | 77 | /// Becomes simply `1` in counting, since this is the size of the unit. 78 | fn handle_unit_variant(&mut self, variant: &Ident) { 79 | let into_arms = &self.into_usize_arms; 80 | let length = &self.length; 81 | self.into_usize_arms = quote! { #into_arms Self::#variant => #length, }; 82 | let from_arms = &self.from_usize_arms; 83 | self.from_usize_arms = quote! { 84 | #from_arms if value == #length { 85 | Self::#variant 86 | } else 87 | }; 88 | self.length = quote! { (#length + 1) }; 89 | } 90 | 91 | /// Its size is the product of the sizes of its members. To represent this variant, one can 92 | /// think of this as representing a little-endian number. First member is simply added, but 93 | /// next members are multiplied before being added. 94 | fn handle_unnamed_variant(&mut self, variant: &Ident, fields: &FieldsUnnamed) { 95 | let length = &self.length; 96 | let mut expr_into = quote! { #length }; 97 | let mut fields_length = quote! { 1usize }; 98 | let mut params_from = quote! {}; 99 | for (i, field) in fields.unnamed.iter().enumerate() { 100 | let ident = format_ident!("p{}", i); 101 | let ty = &field.ty; 102 | let field_length = type_length(ty); 103 | 104 | expr_into = quote! { 105 | (#expr_into + #fields_length * ::enum_map::Enum::into_usize(#ident)) 106 | }; 107 | 108 | params_from = quote! { 109 | #params_from <#ty as ::enum_map::Enum>::from_usize( 110 | (value - #length) / #fields_length % #field_length 111 | ), 112 | }; 113 | 114 | fields_length = quote! { (#fields_length * #field_length) }; 115 | } 116 | 117 | self.length = quote! { (#length + #fields_length) }; 118 | 119 | let length = &self.length; 120 | let from_arms = &self.from_usize_arms; 121 | self.from_usize_arms = quote! { 122 | #from_arms if value < #length { 123 | Self::#variant(#params_from) 124 | } else 125 | }; 126 | 127 | let mut params_into = quote! {}; 128 | for i in 0..fields.unnamed.len() { 129 | let ident = format_ident!("p{}", i); 130 | params_into = quote! { #params_into #ident, }; 131 | } 132 | 133 | let into_arms = &self.into_usize_arms; 134 | self.into_usize_arms = quote! { 135 | #into_arms Self::#variant(#params_into) => #expr_into, 136 | }; 137 | } 138 | 139 | /// Its size is the product of the sizes of its members. To represent this variant, one can 140 | /// think of this as representing a little-endian number. First member is simply added, but 141 | /// next members are multiplied before being added. 142 | fn handle_named_variant(&mut self, variant: &Ident, fields: &FieldsNamed) { 143 | let length = &self.length; 144 | let mut expr_into = quote! { #length }; 145 | let mut fields_length = quote! { 1usize }; 146 | let mut params_from = quote! {}; 147 | 148 | for field in fields.named.iter() { 149 | let ident = field.ident.as_ref().unwrap(); 150 | let ty = &field.ty; 151 | let field_length = type_length(ty); 152 | 153 | expr_into = quote! { 154 | (#expr_into + #fields_length * ::enum_map::Enum::into_usize(#ident)) 155 | }; 156 | 157 | params_from = quote! { 158 | #params_from #ident: <#ty as ::enum_map::Enum>::from_usize( 159 | (value - #length) / #fields_length % #field_length 160 | ), 161 | }; 162 | 163 | fields_length = quote! { (#fields_length * #field_length) }; 164 | } 165 | 166 | self.length = quote! { (#length + #fields_length) }; 167 | 168 | let length = &self.length; 169 | let from_arms = &self.from_usize_arms; 170 | self.from_usize_arms = quote! { 171 | #from_arms if value < #length { 172 | Self::#variant { #params_from } 173 | } else 174 | }; 175 | 176 | let mut params_into = quote! {}; 177 | for field in fields.named.iter() { 178 | let ident = field.ident.as_ref().unwrap(); 179 | params_into = quote! { #params_into #ident, }; 180 | } 181 | 182 | let into_arms = &self.into_usize_arms; 183 | self.into_usize_arms = quote! { 184 | #into_arms Self::#variant { #params_into } => #expr_into, 185 | }; 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /enum-map-derive/src/derive_struct.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2021 - 2022 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 3 | // 4 | // SPDX-License-Identifier: MIT OR Apache-2.0 5 | 6 | use crate::type_length; 7 | use proc_macro2::TokenStream; 8 | use quote::quote; 9 | use syn::{DataStruct, Fields, FieldsNamed, FieldsUnnamed, Ident, Index}; 10 | 11 | pub fn generate(name: Ident, data_struct: DataStruct) -> TokenStream { 12 | StructGenerator::from_fields(&data_struct.fields).finish(&name) 13 | } 14 | 15 | /// Total length is the product of each member's length. To represent a struct, one can 16 | /// think of this as representing a little-endian number. First member is simply added, but 17 | /// next members are multiplied before being added. 18 | #[derive(Debug)] 19 | struct StructGenerator { 20 | length: TokenStream, 21 | from_usize: TokenStream, 22 | into_usize: TokenStream, 23 | } 24 | 25 | impl StructGenerator { 26 | fn from_fields(fields: &Fields) -> Self { 27 | match fields { 28 | Fields::Unit => Self::from_unit_fields(), 29 | Fields::Unnamed(fields_data) => Self::from_unnamed_fields(fields_data), 30 | Fields::Named(fields_data) => Self::from_named_fields(fields_data), 31 | } 32 | } 33 | 34 | fn from_unit_fields() -> Self { 35 | Self { 36 | length: quote! { 1usize }, 37 | from_usize: quote! { Self }, 38 | into_usize: quote! { 0usize }, 39 | } 40 | } 41 | 42 | fn from_unnamed_fields(fields: &FieldsUnnamed) -> Self { 43 | let mut params_from = quote! {}; 44 | let mut into_usize = quote! { 0usize }; 45 | let mut length = quote! { 1usize }; 46 | for (i, field) in fields.unnamed.iter().enumerate() { 47 | let ty = &field.ty; 48 | let index_ident = Index::from(i); 49 | let field_length = type_length(ty); 50 | 51 | into_usize = quote! { 52 | (#into_usize + #length * ::enum_map::Enum::into_usize(self.#index_ident)) 53 | }; 54 | 55 | params_from = quote! { 56 | #params_from <#ty as ::enum_map::Enum>::from_usize( 57 | value / #length % #field_length 58 | ), 59 | }; 60 | 61 | length = quote! { (#length * #field_length) }; 62 | } 63 | 64 | let from_usize = quote! { Self(#params_from) }; 65 | Self { 66 | length, 67 | from_usize, 68 | into_usize, 69 | } 70 | } 71 | 72 | fn from_named_fields(fields: &FieldsNamed) -> Self { 73 | let mut params_from = quote! {}; 74 | let mut into_usize = quote! { 0usize }; 75 | let mut length = quote! { 1usize }; 76 | for field in fields.named.iter() { 77 | let ty = &field.ty; 78 | let ident = field.ident.as_ref().unwrap(); 79 | let field_length = type_length(ty); 80 | 81 | into_usize = quote! { 82 | (#into_usize + #length * ::enum_map::Enum::into_usize(self.#ident)) 83 | }; 84 | 85 | params_from = quote! { 86 | #params_from #ident: <#ty as ::enum_map::Enum>::from_usize( 87 | value / #length % #field_length 88 | ), 89 | }; 90 | 91 | length = quote! { (#field_length * #length) }; 92 | } 93 | 94 | let from_usize = quote! { Self { #params_from } }; 95 | Self { 96 | length, 97 | from_usize, 98 | into_usize, 99 | } 100 | } 101 | 102 | fn finish(&self, name: &Ident) -> TokenStream { 103 | let length = &self.length; 104 | let from_usize = &self.from_usize; 105 | let into_usize = &self.into_usize; 106 | 107 | quote! { 108 | #[automatically_derived] 109 | impl ::enum_map::Enum for #name { 110 | const LENGTH: ::enum_map::usize = #length; 111 | 112 | #[inline] 113 | fn from_usize(value: ::enum_map::usize) -> Self { 114 | #from_usize 115 | } 116 | 117 | #[inline] 118 | fn into_usize(self) -> ::enum_map::usize { 119 | #into_usize 120 | } 121 | } 122 | 123 | #[automatically_derived] 124 | impl ::enum_map::EnumArray for #name { 125 | type Array = [V; #length]; 126 | } 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /enum-map-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2017 - 2022 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2018 hcpl 3 | // SPDX-FileCopyrightText: 2019 mara 4 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 5 | // SPDX-FileCopyrightText: 2021 Dietrich 6 | // 7 | // SPDX-License-Identifier: MIT OR Apache-2.0 8 | 9 | //! Procedural macro implementing `#[derive(Enum)]` 10 | //! 11 | //! This is supposed to used with `enum-map` crate, which provides the 12 | //! actual usage documentation. 13 | 14 | mod derive_enum; 15 | mod derive_struct; 16 | 17 | use proc_macro2::TokenStream; 18 | use quote::quote; 19 | use syn::{Data, DeriveInput, Type}; 20 | 21 | /// Derive macro generating an implementation of trait `Enum`. 22 | /// 23 | /// When using a derive, enum maps are maintained in the order in which 24 | /// enum variants are declared. This is reflected in the value returned 25 | /// by `Enum::into_usize`, iterators of enum map as well as 26 | /// `EnumMap::as_slice` method. 27 | /// 28 | /// # Examples 29 | /// 30 | /// ## Enums Without Payload 31 | /// ``` 32 | /// use enum_map::Enum; 33 | /// 34 | /// #[derive(Enum, Debug, PartialEq, Eq)] 35 | /// enum A { 36 | /// B, 37 | /// C, 38 | /// D, 39 | /// } 40 | /// 41 | /// assert_eq!(A::B.into_usize(), 0); 42 | /// assert_eq!(A::C.into_usize(), 1); 43 | /// assert_eq!(A::D.into_usize(), 2); 44 | /// 45 | /// assert_eq!(A::from_usize(0), A::B); 46 | /// assert_eq!(A::from_usize(1), A::C); 47 | /// assert_eq!(A::from_usize(2), A::D); 48 | /// ``` 49 | /// 50 | /// ## Enums With Payload 51 | /// 52 | /// ``` 53 | /// use enum_map::Enum; 54 | /// 55 | /// #[derive(Enum, Debug, PartialEq, Eq)] 56 | /// enum A { 57 | /// B, 58 | /// C, 59 | /// D, 60 | /// } 61 | /// 62 | /// #[derive(Enum, Debug, PartialEq, Eq)] 63 | /// enum X { 64 | /// Y, 65 | /// Z, 66 | /// } 67 | /// 68 | /// #[derive(Enum, Debug, PartialEq, Eq)] 69 | /// enum Foo { 70 | /// Bar(bool, A), 71 | /// Empty, 72 | /// Baz { fa: A, fx: X }, 73 | /// } 74 | /// 75 | /// assert_eq!(Foo::Bar(false, A::B).into_usize(), 0); 76 | /// assert_eq!(Foo::Bar(false, A::D).into_usize(), 4); 77 | /// assert_eq!(Foo::Bar(true, A::B).into_usize(), 1); 78 | /// assert_eq!(Foo::Bar(true, A::C).into_usize(), 3); 79 | /// assert_eq!(Foo::Empty.into_usize(), 6); 80 | /// assert_eq!(Foo::Baz { fa: A::B, fx: X::Y }.into_usize(), 7); 81 | /// assert_eq!(Foo::Baz { fa: A::B, fx: X::Z }.into_usize(), 10); 82 | /// assert_eq!(Foo::Baz { fa: A::D, fx: X::Y }.into_usize(), 9); 83 | /// 84 | /// assert_eq!(Foo::from_usize(0), Foo::Bar(false, A::B)); 85 | /// assert_eq!(Foo::from_usize(4), Foo::Bar(false, A::D)); 86 | /// assert_eq!(Foo::from_usize(1), Foo::Bar(true, A::B)); 87 | /// assert_eq!(Foo::from_usize(3), Foo::Bar(true, A::C)); 88 | /// assert_eq!(Foo::from_usize(6), Foo::Empty); 89 | /// assert_eq!(Foo::from_usize(7), Foo::Baz { fa: A::B, fx: X::Y }); 90 | /// assert_eq!(Foo::from_usize(10), Foo::Baz { fa: A::B, fx: X::Z }); 91 | /// assert_eq!(Foo::from_usize(9), Foo::Baz { fa: A::D, fx: X::Y }); 92 | /// 93 | /// ``` 94 | /// 95 | /// ## Structs 96 | /// 97 | /// ``` 98 | /// use enum_map::Enum; 99 | /// 100 | /// #[derive(Enum, Debug, PartialEq, Eq)] 101 | /// enum A { 102 | /// B, 103 | /// C, 104 | /// D, 105 | /// } 106 | /// 107 | /// #[derive(Enum, Debug, PartialEq, Eq)] 108 | /// enum X { 109 | /// Y, 110 | /// Z, 111 | /// } 112 | /// 113 | /// #[derive(Enum, Debug, PartialEq, Eq)] 114 | /// struct Foo { 115 | /// bar: bool, 116 | /// baz: A, 117 | /// end: X, 118 | /// } 119 | /// 120 | /// assert_eq!(Foo { bar: false, baz: A::B, end: X::Y }.into_usize(), 0); 121 | /// assert_eq!(Foo { bar: true, baz: A::B, end: X::Y }.into_usize(), 1); 122 | /// assert_eq!(Foo { bar: false, baz: A::D, end: X::Y }.into_usize(), 4); 123 | /// assert_eq!(Foo { bar: true, baz: A::C, end: X::Z }.into_usize(), 9); 124 | /// 125 | /// assert_eq!(Foo::from_usize(0), Foo { bar: false, baz: A::B, end: X::Y }); 126 | /// assert_eq!(Foo::from_usize(1), Foo { bar: true, baz: A::B, end: X::Y }); 127 | /// assert_eq!(Foo::from_usize(4), Foo { bar: false, baz: A::D, end: X::Y }); 128 | /// assert_eq!(Foo::from_usize(9), Foo { bar: true, baz: A::C, end: X::Z }); 129 | /// ``` 130 | /// 131 | /// ## Tuple Structs 132 | /// 133 | /// ``` 134 | /// use enum_map::Enum; 135 | /// 136 | /// #[derive(Enum, Debug, PartialEq, Eq)] 137 | /// enum A { 138 | /// B, 139 | /// C, 140 | /// D, 141 | /// } 142 | /// 143 | /// #[derive(Enum, Debug, PartialEq, Eq)] 144 | /// enum X { 145 | /// Y, 146 | /// Z, 147 | /// } 148 | /// 149 | /// #[derive(Enum, Debug, PartialEq, Eq)] 150 | /// struct Foo(bool, A, X); 151 | /// 152 | /// assert_eq!(Foo(false, A::B, X::Y ).into_usize(), 0); 153 | /// assert_eq!(Foo(true, A::B, X::Y ).into_usize(), 1); 154 | /// assert_eq!(Foo(false, A::D, X::Y ).into_usize(), 4); 155 | /// assert_eq!(Foo(true, A::C, X::Z ).into_usize(), 9); 156 | /// 157 | /// assert_eq!(Foo::from_usize(0), Foo(false, A::B, X::Y)); 158 | /// assert_eq!(Foo::from_usize(1), Foo(true, A::B, X::Y)); 159 | /// assert_eq!(Foo::from_usize(4), Foo(false, A::D, X::Y)); 160 | /// assert_eq!(Foo::from_usize(9), Foo(true, A::C, X::Z)); 161 | #[proc_macro_derive(Enum)] 162 | pub fn derive_enum_map(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 163 | let input: DeriveInput = syn::parse(input).unwrap(); 164 | 165 | let result = match input.data { 166 | Data::Enum(data_enum) => derive_enum::generate(input.ident, data_enum), 167 | Data::Struct(data_struct) => derive_struct::generate(input.ident, data_struct), 168 | _ => quote! { compile_error! {"#[derive(Enum)] is only defined for enums and structs"} }, 169 | }; 170 | 171 | result.into() 172 | } 173 | 174 | fn type_length(ty: &Type) -> TokenStream { 175 | quote! { 176 | <#ty as ::enum_map::Enum>::LENGTH 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /enum-map/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ../CHANGELOG.md -------------------------------------------------------------------------------- /enum-map/Cargo.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 - 2023 Konrad Borowski 2 | # SPDX-FileCopyrightText: 2021 Alex Sayers 3 | # 4 | # SPDX-License-Identifier: MIT OR Apache-2.0 5 | 6 | [package] 7 | name = "enum-map" 8 | version = "2.6.2" 9 | authors = ["Konrad Borowski "] 10 | edition = "2021" 11 | rust-version = "1.61" 12 | repository = "https://github.com/xfix/enum-map" 13 | license = "MIT OR Apache-2.0" 14 | description = "A map with C-like enum keys represented internally as an array" 15 | keywords = ["data-structure", "no_std", "enum"] 16 | categories = ["data-structures", "no-std"] 17 | documentation = "https://docs.rs/enum-map" 18 | readme = "README.md" 19 | 20 | [badges] 21 | maintenance = { status = "passively-maintained" } 22 | 23 | [dependencies] 24 | arbitrary = { version = "1.0.0", optional = true } 25 | enum-map-derive = { version = "0.13.0", path = "../enum-map-derive" } 26 | serde = { version = "1.0.16", optional = true, default-features = false } 27 | 28 | [dev-dependencies] 29 | bincode = "1.0.0" 30 | serde = { version = "1.0.103", features = ["derive"] } 31 | serde_test = "1.0.19" 32 | serde_json = "1.0.2" 33 | 34 | [package.metadata.docs.rs] 35 | features = ["arbitrary", "serde"] 36 | -------------------------------------------------------------------------------- /enum-map/LICENSES: -------------------------------------------------------------------------------- 1 | ../LICENSES -------------------------------------------------------------------------------- /enum-map/README.md: -------------------------------------------------------------------------------- 1 | ../README.md -------------------------------------------------------------------------------- /enum-map/src/arbitrary.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 2 | // SPDX-FileCopyrightText: 2021 Konrad Borowski 3 | // 4 | // SPDX-License-Identifier: MIT OR Apache-2.0 5 | 6 | use crate::{enum_map, EnumArray, EnumMap}; 7 | use arbitrary::{Arbitrary, Result, Unstructured}; 8 | 9 | /// Requires crate feature `"arbitrary"` 10 | impl<'a, K: EnumArray, V: Arbitrary<'a>> Arbitrary<'a> for EnumMap { 11 | fn arbitrary(u: &mut Unstructured<'a>) -> Result> { 12 | Ok(enum_map! { 13 | _ => Arbitrary::arbitrary(u)?, 14 | }) 15 | } 16 | 17 | fn size_hint(depth: usize) -> (usize, Option) { 18 | if K::LENGTH == 0 { 19 | (0, Some(0)) 20 | } else { 21 | let (lo, hi) = V::size_hint(depth); 22 | ( 23 | lo.saturating_mul(K::LENGTH), 24 | hi.and_then(|hi| hi.checked_mul(K::LENGTH)), 25 | ) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /enum-map/src/enum_map_impls.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2017 - 2021 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 3 | // SPDX-FileCopyrightText: 2021 micycle 4 | // SPDX-FileCopyrightText: 2023 Nicolas Carranza 5 | // 6 | // SPDX-License-Identifier: MIT OR Apache-2.0 7 | 8 | use crate::{enum_map, EnumArray, EnumMap}; 9 | use core::fmt::{self, Debug, Formatter}; 10 | use core::hash::{Hash, Hasher}; 11 | use core::iter::{Extend, FromIterator}; 12 | use core::ops::{Index, IndexMut}; 13 | 14 | impl + Debug, V: Debug> Debug for EnumMap { 15 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 16 | f.debug_map().entries(self).finish() 17 | } 18 | } 19 | 20 | impl, V> Extend<(K, V)> for EnumMap { 21 | fn extend>(&mut self, iter: I) { 22 | for (key, value) in iter { 23 | self[key] = value; 24 | } 25 | } 26 | } 27 | 28 | impl<'a, K, V> Extend<(&'a K, &'a V)> for EnumMap 29 | where 30 | K: EnumArray + Copy, 31 | V: Copy, 32 | { 33 | fn extend>(&mut self, iter: I) { 34 | self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); 35 | } 36 | } 37 | 38 | impl FromIterator<(K, V)> for EnumMap 39 | where 40 | Self: Default, 41 | K: EnumArray, 42 | { 43 | fn from_iter>(iter: I) -> Self { 44 | let mut map = EnumMap::default(); 45 | map.extend(iter); 46 | map 47 | } 48 | } 49 | 50 | impl, V> Index for EnumMap { 51 | type Output = V; 52 | 53 | #[inline] 54 | fn index(&self, key: K) -> &V { 55 | &self.as_slice()[key.into_usize()] 56 | } 57 | } 58 | 59 | impl, V> IndexMut for EnumMap { 60 | #[inline] 61 | fn index_mut(&mut self, key: K) -> &mut V { 62 | &mut self.as_mut_slice()[key.into_usize()] 63 | } 64 | } 65 | 66 | // Implementations provided by derive attribute are too specific, and put requirements on K. 67 | // This is caused by rust-lang/rust#26925. 68 | impl, V> Clone for EnumMap 69 | where 70 | K::Array: Clone, 71 | { 72 | #[inline] 73 | fn clone(&self) -> Self { 74 | EnumMap { 75 | array: self.array.clone(), 76 | } 77 | } 78 | } 79 | 80 | impl, V> Copy for EnumMap where K::Array: Copy {} 81 | 82 | impl, V: PartialEq> PartialEq for EnumMap { 83 | #[inline] 84 | fn eq(&self, other: &Self) -> bool { 85 | self.as_slice() == other.as_slice() 86 | } 87 | } 88 | 89 | impl, V: Eq> Eq for EnumMap {} 90 | 91 | impl, V: Hash> Hash for EnumMap { 92 | #[inline] 93 | fn hash(&self, state: &mut H) { 94 | self.as_slice().hash(state); 95 | } 96 | } 97 | 98 | impl, V: Default> Default for EnumMap { 99 | #[inline] 100 | fn default() -> Self { 101 | enum_map! { _ => V::default() } 102 | } 103 | } 104 | 105 | impl, V: PartialOrd> PartialOrd for EnumMap { 106 | fn partial_cmp(&self, other: &Self) -> Option { 107 | self.as_slice().partial_cmp(other.as_slice()) 108 | } 109 | } 110 | 111 | impl, V: Ord> Ord for EnumMap { 112 | fn cmp(&self, other: &Self) -> core::cmp::Ordering { 113 | self.as_slice().cmp(other.as_slice()) 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /enum-map/src/internal.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2017 - 2023 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 3 | // SPDX-FileCopyrightText: 2022 philipp 4 | // 5 | // SPDX-License-Identifier: MIT OR Apache-2.0 6 | 7 | use core::cmp::Ordering; 8 | use core::convert::Infallible; 9 | 10 | /// Enum mapping type. 11 | /// 12 | /// This trait is implemented by `#[derive(Enum)]`. 13 | /// 14 | /// This trait is also implemented by `bool` and `u8`. While `u8` is 15 | /// strictly speaking not an actual enum, there are good reasons to consider 16 | /// it like one, as array of `u8` keys is a relatively common pattern. 17 | pub trait Enum: Sized { 18 | /// Length of the enum. 19 | const LENGTH: usize; 20 | 21 | /// Takes an usize, and returns an element matching `into_usize` function. 22 | fn from_usize(value: usize) -> Self; 23 | /// Returns an unique identifier for a value within range of `0..Array::LENGTH`. 24 | fn into_usize(self) -> usize; 25 | } 26 | 27 | /// Trait associating enum with an array. 28 | /// 29 | /// This exists due to limitations of Rust compiler that prevent arrays from using 30 | /// associated constants in structures. The array length must match `LENGTH` of an 31 | /// `Enum`. 32 | pub trait EnumArray: Enum { 33 | /// Representation of an enum map for type `V`. 34 | type Array: Array; 35 | } 36 | 37 | /// Array for enum-map storage. 38 | /// 39 | /// This trait is inteded for primitive array types (with fixed length). 40 | /// 41 | /// # Safety 42 | /// 43 | /// The array length needs to match actual storage. 44 | pub unsafe trait Array { 45 | // This is necessary duplication because the length in Enum trait can be 46 | // provided by user and may not be trustworthy for unsafe code. 47 | const LENGTH: usize; 48 | } 49 | 50 | unsafe impl Array for [V; N] { 51 | const LENGTH: usize = N; 52 | } 53 | 54 | #[doc(hidden)] 55 | #[inline] 56 | pub fn out_of_bounds() -> ! { 57 | panic!("index out of range for Enum::from_usize"); 58 | } 59 | 60 | impl Enum for bool { 61 | const LENGTH: usize = 2; 62 | 63 | #[inline] 64 | fn from_usize(value: usize) -> Self { 65 | match value { 66 | 0 => false, 67 | 1 => true, 68 | _ => out_of_bounds(), 69 | } 70 | } 71 | #[inline] 72 | fn into_usize(self) -> usize { 73 | usize::from(self) 74 | } 75 | } 76 | 77 | impl EnumArray for bool { 78 | type Array = [T; Self::LENGTH]; 79 | } 80 | 81 | impl Enum for () { 82 | const LENGTH: usize = 1; 83 | 84 | #[inline] 85 | fn from_usize(value: usize) -> Self { 86 | match value { 87 | 0 => (), 88 | _ => out_of_bounds(), 89 | } 90 | } 91 | #[inline] 92 | fn into_usize(self) -> usize { 93 | 0 94 | } 95 | } 96 | 97 | impl EnumArray for () { 98 | type Array = [T; Self::LENGTH]; 99 | } 100 | 101 | impl Enum for u8 { 102 | const LENGTH: usize = 256; 103 | 104 | #[inline] 105 | fn from_usize(value: usize) -> Self { 106 | value.try_into().unwrap_or_else(|_| out_of_bounds()) 107 | } 108 | #[inline] 109 | fn into_usize(self) -> usize { 110 | usize::from(self) 111 | } 112 | } 113 | 114 | impl EnumArray for u8 { 115 | type Array = [T; Self::LENGTH]; 116 | } 117 | 118 | impl Enum for Infallible { 119 | const LENGTH: usize = 0; 120 | 121 | #[inline] 122 | fn from_usize(_: usize) -> Self { 123 | out_of_bounds(); 124 | } 125 | #[inline] 126 | fn into_usize(self) -> usize { 127 | match self {} 128 | } 129 | } 130 | 131 | impl EnumArray for Infallible { 132 | type Array = [T; Self::LENGTH]; 133 | } 134 | 135 | impl Enum for Ordering { 136 | const LENGTH: usize = 3; 137 | 138 | #[inline] 139 | fn from_usize(value: usize) -> Self { 140 | match value { 141 | 0 => Ordering::Less, 142 | 1 => Ordering::Equal, 143 | 2 => Ordering::Greater, 144 | _ => out_of_bounds(), 145 | } 146 | } 147 | #[inline] 148 | fn into_usize(self) -> usize { 149 | match self { 150 | Ordering::Less => 0, 151 | Ordering::Equal => 1, 152 | Ordering::Greater => 2, 153 | } 154 | } 155 | } 156 | 157 | impl EnumArray for Ordering { 158 | type Array = [T; Self::LENGTH]; 159 | } 160 | -------------------------------------------------------------------------------- /enum-map/src/iter.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::module_name_repetitions)] 2 | 3 | // SPDX-FileCopyrightText: 2017 - 2022 Konrad Borowski 4 | // SPDX-FileCopyrightText: 2020 Amanieu d'Antras 5 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 6 | // 7 | // SPDX-License-Identifier: MIT OR Apache-2.0 8 | 9 | use crate::{EnumArray, EnumMap}; 10 | use core::iter::{Enumerate, FusedIterator}; 11 | use core::marker::PhantomData; 12 | use core::mem::ManuallyDrop; 13 | use core::ops::Range; 14 | use core::ptr; 15 | use core::slice; 16 | 17 | /// Immutable enum map iterator 18 | /// 19 | /// This struct is created by `iter` method or `into_iter` on a reference 20 | /// to `EnumMap`. 21 | /// 22 | /// # Examples 23 | /// 24 | /// ``` 25 | /// use enum_map::{enum_map, Enum}; 26 | /// 27 | /// #[derive(Enum)] 28 | /// enum Example { 29 | /// A, 30 | /// B, 31 | /// C, 32 | /// } 33 | /// 34 | /// let mut map = enum_map! { Example::A => 3, _ => 0 }; 35 | /// assert_eq!(map[Example::A], 3); 36 | /// for (key, &value) in &map { 37 | /// assert_eq!(value, match key { 38 | /// Example::A => 3, 39 | /// _ => 0, 40 | /// }); 41 | /// } 42 | /// ``` 43 | #[derive(Debug)] 44 | pub struct Iter<'a, K, V: 'a> { 45 | _phantom: PhantomData K>, 46 | iterator: Enumerate>, 47 | } 48 | 49 | impl<'a, K: EnumArray, V> Clone for Iter<'a, K, V> { 50 | fn clone(&self) -> Self { 51 | Iter { 52 | _phantom: PhantomData, 53 | iterator: self.iterator.clone(), 54 | } 55 | } 56 | } 57 | 58 | impl<'a, K: EnumArray, V> Iterator for Iter<'a, K, V> { 59 | type Item = (K, &'a V); 60 | #[inline] 61 | fn next(&mut self) -> Option { 62 | self.iterator 63 | .next() 64 | .map(|(index, item)| (K::from_usize(index), item)) 65 | } 66 | 67 | #[inline] 68 | fn size_hint(&self) -> (usize, Option) { 69 | self.iterator.size_hint() 70 | } 71 | 72 | fn fold(self, init: B, f: F) -> B 73 | where 74 | F: FnMut(B, Self::Item) -> B, 75 | { 76 | self.iterator 77 | .map(|(index, item)| (K::from_usize(index), item)) 78 | .fold(init, f) 79 | } 80 | } 81 | 82 | impl<'a, K: EnumArray, V> DoubleEndedIterator for Iter<'a, K, V> { 83 | #[inline] 84 | fn next_back(&mut self) -> Option { 85 | self.iterator 86 | .next_back() 87 | .map(|(index, item)| (K::from_usize(index), item)) 88 | } 89 | } 90 | 91 | impl<'a, K: EnumArray, V> ExactSizeIterator for Iter<'a, K, V> {} 92 | 93 | impl<'a, K: EnumArray, V> FusedIterator for Iter<'a, K, V> {} 94 | 95 | impl<'a, K: EnumArray, V> IntoIterator for &'a EnumMap { 96 | type Item = (K, &'a V); 97 | type IntoIter = Iter<'a, K, V>; 98 | #[inline] 99 | fn into_iter(self) -> Self::IntoIter { 100 | Iter { 101 | _phantom: PhantomData, 102 | iterator: self.as_slice().iter().enumerate(), 103 | } 104 | } 105 | } 106 | 107 | /// Mutable map iterator 108 | /// 109 | /// This struct is created by `iter_mut` method or `into_iter` on a mutable 110 | /// reference to `EnumMap`. 111 | /// 112 | /// # Examples 113 | /// 114 | /// ``` 115 | /// use enum_map::{enum_map, Enum}; 116 | /// 117 | /// #[derive(Debug, Enum)] 118 | /// enum Example { 119 | /// A, 120 | /// B, 121 | /// C, 122 | /// } 123 | /// 124 | /// let mut map = enum_map! { Example::A => 3, _ => 0 }; 125 | /// for (_, value) in &mut map { 126 | /// *value += 1; 127 | /// } 128 | /// assert_eq!(map, enum_map! { Example::A => 4, _ => 1 }); 129 | /// ``` 130 | #[derive(Debug)] 131 | pub struct IterMut<'a, K, V: 'a> { 132 | _phantom: PhantomData K>, 133 | iterator: Enumerate>, 134 | } 135 | 136 | impl<'a, K: EnumArray, V> Iterator for IterMut<'a, K, V> { 137 | type Item = (K, &'a mut V); 138 | #[inline] 139 | fn next(&mut self) -> Option { 140 | self.iterator 141 | .next() 142 | .map(|(index, item)| (K::from_usize(index), item)) 143 | } 144 | 145 | #[inline] 146 | fn size_hint(&self) -> (usize, Option) { 147 | self.iterator.size_hint() 148 | } 149 | 150 | fn fold(self, init: B, f: F) -> B 151 | where 152 | F: FnMut(B, Self::Item) -> B, 153 | { 154 | self.iterator 155 | .map(|(index, item)| (K::from_usize(index), item)) 156 | .fold(init, f) 157 | } 158 | } 159 | 160 | impl<'a, K: EnumArray, V> DoubleEndedIterator for IterMut<'a, K, V> { 161 | #[inline] 162 | fn next_back(&mut self) -> Option { 163 | self.iterator 164 | .next_back() 165 | .map(|(index, item)| (K::from_usize(index), item)) 166 | } 167 | } 168 | 169 | impl<'a, K: EnumArray, V> ExactSizeIterator for IterMut<'a, K, V> {} 170 | 171 | impl<'a, K: EnumArray, V> FusedIterator for IterMut<'a, K, V> {} 172 | 173 | impl<'a, K: EnumArray, V> IntoIterator for &'a mut EnumMap { 174 | type Item = (K, &'a mut V); 175 | type IntoIter = IterMut<'a, K, V>; 176 | #[inline] 177 | fn into_iter(self) -> Self::IntoIter { 178 | IterMut { 179 | _phantom: PhantomData, 180 | iterator: self.as_mut_slice().iter_mut().enumerate(), 181 | } 182 | } 183 | } 184 | 185 | /// A map iterator that moves out of map. 186 | /// 187 | /// This struct is created by `into_iter` on `EnumMap`. 188 | /// 189 | /// # Examples 190 | /// 191 | /// ``` 192 | /// use enum_map::{enum_map, Enum}; 193 | /// 194 | /// #[derive(Debug, Enum)] 195 | /// enum Example { 196 | /// A, 197 | /// B, 198 | /// } 199 | /// 200 | /// let map = enum_map! { Example::A | Example::B => String::from("123") }; 201 | /// for (_, value) in map { 202 | /// assert_eq!(value + "4", "1234"); 203 | /// } 204 | /// ``` 205 | pub struct IntoIter, V> { 206 | map: ManuallyDrop>, 207 | alive: Range, 208 | } 209 | 210 | impl, V> Iterator for IntoIter { 211 | type Item = (K, V); 212 | fn next(&mut self) -> Option<(K, V)> { 213 | let position = self.alive.next()?; 214 | Some((K::from_usize(position), unsafe { 215 | ptr::read(&self.map.as_slice()[position]) 216 | })) 217 | } 218 | 219 | #[inline] 220 | fn size_hint(&self) -> (usize, Option) { 221 | self.alive.size_hint() 222 | } 223 | } 224 | 225 | impl, V> DoubleEndedIterator for IntoIter { 226 | fn next_back(&mut self) -> Option<(K, V)> { 227 | let position = self.alive.next_back()?; 228 | Some((K::from_usize(position), unsafe { 229 | ptr::read(&self.map.as_slice()[position]) 230 | })) 231 | } 232 | } 233 | 234 | impl, V> ExactSizeIterator for IntoIter {} 235 | 236 | impl, V> FusedIterator for IntoIter {} 237 | 238 | impl, V> Drop for IntoIter { 239 | #[inline] 240 | fn drop(&mut self) { 241 | unsafe { 242 | ptr::drop_in_place(&mut self.map.as_mut_slice()[self.alive.clone()]); 243 | } 244 | } 245 | } 246 | 247 | impl, V> IntoIterator for EnumMap { 248 | type Item = (K, V); 249 | type IntoIter = IntoIter; 250 | #[inline] 251 | fn into_iter(self) -> Self::IntoIter { 252 | let len = self.len(); 253 | IntoIter { 254 | map: ManuallyDrop::new(self), 255 | alive: 0..len, 256 | } 257 | } 258 | } 259 | 260 | impl, V> EnumMap { 261 | /// An iterator visiting all values. The iterator type is `&V`. 262 | /// 263 | /// # Examples 264 | /// 265 | /// ``` 266 | /// use enum_map::enum_map; 267 | /// 268 | /// let map = enum_map! { false => 3, true => 4 }; 269 | /// let mut values = map.values(); 270 | /// assert_eq!(values.next(), Some(&3)); 271 | /// assert_eq!(values.next(), Some(&4)); 272 | /// assert_eq!(values.next(), None); 273 | /// ``` 274 | #[inline] 275 | pub fn values(&self) -> Values { 276 | Values(self.as_slice().iter()) 277 | } 278 | 279 | /// An iterator visiting all values mutably. The iterator type is `&mut V`. 280 | /// 281 | /// # Examples 282 | /// 283 | /// ``` 284 | /// use enum_map::enum_map; 285 | /// 286 | /// let mut map = enum_map! { _ => 2 }; 287 | /// for value in map.values_mut() { 288 | /// *value += 2; 289 | /// } 290 | /// assert_eq!(map[false], 4); 291 | /// assert_eq!(map[true], 4); 292 | /// ``` 293 | #[inline] 294 | pub fn values_mut(&mut self) -> ValuesMut { 295 | ValuesMut(self.as_mut_slice().iter_mut()) 296 | } 297 | 298 | /// Creates a consuming iterator visiting all the values. The map 299 | /// cannot be used after calling this. The iterator element type 300 | /// is `V`. 301 | /// 302 | /// # Examples 303 | /// 304 | /// ``` 305 | /// use enum_map::enum_map; 306 | /// 307 | /// let mut map = enum_map! { false => "hello", true => "goodbye" }; 308 | /// assert_eq!(map.into_values().collect::>(), ["hello", "goodbye"]); 309 | /// ``` 310 | #[inline] 311 | pub fn into_values(self) -> IntoValues { 312 | IntoValues { 313 | inner: self.into_iter(), 314 | } 315 | } 316 | } 317 | 318 | /// An iterator over the values of `EnumMap`. 319 | /// 320 | /// This `struct` is created by the `values` method of `EnumMap`. 321 | /// See its documentation for more. 322 | pub struct Values<'a, V: 'a>(slice::Iter<'a, V>); 323 | 324 | impl<'a, V> Clone for Values<'a, V> { 325 | fn clone(&self) -> Self { 326 | Values(self.0.clone()) 327 | } 328 | } 329 | 330 | impl<'a, V: 'a> Iterator for Values<'a, V> { 331 | type Item = &'a V; 332 | #[inline] 333 | fn next(&mut self) -> Option<&'a V> { 334 | self.0.next() 335 | } 336 | 337 | #[inline] 338 | fn size_hint(&self) -> (usize, Option) { 339 | self.0.size_hint() 340 | } 341 | } 342 | 343 | impl<'a, V: 'a> DoubleEndedIterator for Values<'a, V> { 344 | #[inline] 345 | fn next_back(&mut self) -> Option<&'a V> { 346 | self.0.next_back() 347 | } 348 | } 349 | 350 | impl<'a, V: 'a> ExactSizeIterator for Values<'a, V> {} 351 | 352 | impl<'a, V: 'a> FusedIterator for Values<'a, V> {} 353 | 354 | /// A mutable iterator over the values of `EnumMap`. 355 | /// 356 | /// This `struct` is created by the `values_mut` method of `EnumMap`. 357 | /// See its documentation for more. 358 | pub struct ValuesMut<'a, V: 'a>(slice::IterMut<'a, V>); 359 | 360 | impl<'a, V: 'a> Iterator for ValuesMut<'a, V> { 361 | type Item = &'a mut V; 362 | #[inline] 363 | fn next(&mut self) -> Option<&'a mut V> { 364 | self.0.next() 365 | } 366 | 367 | #[inline] 368 | fn size_hint(&self) -> (usize, Option) { 369 | self.0.size_hint() 370 | } 371 | } 372 | 373 | impl<'a, V: 'a> DoubleEndedIterator for ValuesMut<'a, V> { 374 | #[inline] 375 | fn next_back(&mut self) -> Option<&'a mut V> { 376 | self.0.next_back() 377 | } 378 | } 379 | 380 | impl<'a, V: 'a> ExactSizeIterator for ValuesMut<'a, V> {} 381 | 382 | impl<'a, V: 'a> FusedIterator for ValuesMut<'a, V> {} 383 | 384 | /// An owning iterator over the values of an `EnumMap`. 385 | /// 386 | /// This `struct` is created by the `into_values` method of `EnumMap`. 387 | /// See its documentation for more. 388 | pub struct IntoValues, V> { 389 | inner: IntoIter, 390 | } 391 | 392 | impl Iterator for IntoValues 393 | where 394 | K: EnumArray, 395 | { 396 | type Item = V; 397 | 398 | fn next(&mut self) -> Option { 399 | Some(self.inner.next()?.1) 400 | } 401 | 402 | fn size_hint(&self) -> (usize, Option) { 403 | self.inner.size_hint() 404 | } 405 | } 406 | 407 | impl, V> DoubleEndedIterator for IntoValues { 408 | fn next_back(&mut self) -> Option { 409 | Some(self.inner.next_back()?.1) 410 | } 411 | } 412 | 413 | impl ExactSizeIterator for IntoValues where K: EnumArray {} 414 | 415 | impl FusedIterator for IntoValues where K: EnumArray {} 416 | -------------------------------------------------------------------------------- /enum-map/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2017 - 2023 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2019 Riey 3 | // SPDX-FileCopyrightText: 2021 Alex Sayers 4 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 5 | // SPDX-FileCopyrightText: 2022 Cass Fridkin 6 | // SPDX-FileCopyrightText: 2022 Mateusz Kowalczyk 7 | // 8 | // SPDX-License-Identifier: MIT OR Apache-2.0 9 | 10 | //! An enum mapping type. 11 | //! 12 | //! It is implemented using an array type, so using it is as fast as using Rust 13 | //! arrays. 14 | //! 15 | //! # Examples 16 | //! 17 | //! ``` 18 | //! use enum_map::{enum_map, Enum, EnumMap}; 19 | //! 20 | //! #[derive(Debug, Enum)] 21 | //! enum Example { 22 | //! A(bool), 23 | //! B, 24 | //! C, 25 | //! } 26 | //! 27 | //! let mut map = enum_map! { 28 | //! Example::A(false) => 0, 29 | //! Example::A(true) => 1, 30 | //! Example::B => 2, 31 | //! Example::C => 3, 32 | //! }; 33 | //! map[Example::C] = 4; 34 | //! 35 | //! assert_eq!(map[Example::A(true)], 1); 36 | //! 37 | //! for (key, &value) in &map { 38 | //! println!("{:?} has {} as value.", key, value); 39 | //! } 40 | //! ``` 41 | 42 | #![no_std] 43 | #![deny(missing_docs)] 44 | #![warn(clippy::pedantic)] 45 | 46 | #[cfg(feature = "arbitrary")] 47 | mod arbitrary; 48 | mod enum_map_impls; 49 | mod internal; 50 | mod iter; 51 | #[cfg(feature = "serde")] 52 | mod serde; 53 | 54 | #[doc(hidden)] 55 | pub use core::mem::{self, ManuallyDrop, MaybeUninit}; 56 | #[doc(hidden)] 57 | pub use core::primitive::usize; 58 | use core::slice; 59 | #[doc(hidden)] 60 | // unreachable needs to be exported for compatibility with older versions of enum-map-derive 61 | pub use core::{panic, ptr, unreachable}; 62 | pub use enum_map_derive::Enum; 63 | #[doc(hidden)] 64 | pub use internal::out_of_bounds; 65 | use internal::Array; 66 | pub use internal::{Enum, EnumArray}; 67 | pub use iter::{IntoIter, IntoValues, Iter, IterMut, Values, ValuesMut}; 68 | 69 | // SAFETY: initialized needs to represent number of initialized elements 70 | #[doc(hidden)] 71 | pub struct Guard<'a, K, V> 72 | where 73 | K: EnumArray, 74 | { 75 | array_mut: &'a mut MaybeUninit, 76 | initialized: usize, 77 | } 78 | 79 | impl Drop for Guard<'_, K, V> 80 | where 81 | K: EnumArray, 82 | { 83 | fn drop(&mut self) { 84 | // This is safe as arr[..len] is initialized due to 85 | // Guard's type invariant. 86 | unsafe { 87 | ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.initialized).drop_in_place(); 88 | } 89 | } 90 | } 91 | 92 | impl<'a, K, V> Guard<'a, K, V> 93 | where 94 | K: EnumArray, 95 | { 96 | #[doc(hidden)] 97 | pub fn as_mut_ptr(&mut self) -> *mut V { 98 | self.array_mut.as_mut_ptr().cast::() 99 | } 100 | 101 | #[doc(hidden)] 102 | #[must_use] 103 | pub fn new(array_mut: &'a mut MaybeUninit) -> Self { 104 | Self { 105 | array_mut, 106 | initialized: 0, 107 | } 108 | } 109 | 110 | #[doc(hidden)] 111 | #[must_use] 112 | #[allow(clippy::unused_self)] 113 | pub fn storage_length(&self) -> usize { 114 | // SAFETY: We need to use LENGTH from K::Array, as K::LENGTH is 115 | // untrustworthy. 116 | K::Array::LENGTH 117 | } 118 | 119 | #[doc(hidden)] 120 | #[must_use] 121 | pub fn get_key(&self) -> K { 122 | K::from_usize(self.initialized) 123 | } 124 | 125 | #[doc(hidden)] 126 | // Unsafe as it can write out of bounds. 127 | pub unsafe fn push(&mut self, value: V) { 128 | self.as_mut_ptr().add(self.initialized).write(value); 129 | self.initialized += 1; 130 | } 131 | } 132 | 133 | #[doc(hidden)] 134 | pub struct TypeEqualizer<'a, K, V> 135 | where 136 | K: EnumArray, 137 | { 138 | pub enum_map: [EnumMap; 0], 139 | pub guard: Guard<'a, K, V>, 140 | } 141 | 142 | /// Enum map constructor. 143 | /// 144 | /// This macro allows to create a new enum map in a type safe way. It takes 145 | /// a list of `,` separated pairs separated by `=>`. Left side is `|` 146 | /// separated list of enum keys, or `_` to match all unmatched enum keys, 147 | /// while right side is a value. 148 | /// 149 | /// The iteration order when using this macro is not guaranteed to be 150 | /// consistent. Future releases of this crate may change it, and this is not 151 | /// considered to be a breaking change. 152 | /// 153 | /// # Examples 154 | /// 155 | /// ``` 156 | /// use enum_map::{enum_map, Enum}; 157 | /// 158 | /// #[derive(Enum)] 159 | /// enum Example { 160 | /// A, 161 | /// B, 162 | /// C, 163 | /// D, 164 | /// } 165 | /// 166 | /// let enum_map = enum_map! { 167 | /// Example::A | Example::B => 1, 168 | /// Example::C => 2, 169 | /// _ => 3, 170 | /// }; 171 | /// assert_eq!(enum_map[Example::A], 1); 172 | /// assert_eq!(enum_map[Example::B], 1); 173 | /// assert_eq!(enum_map[Example::C], 2); 174 | /// assert_eq!(enum_map[Example::D], 3); 175 | /// ``` 176 | #[macro_export] 177 | macro_rules! enum_map { 178 | {$($t:tt)*} => {{ 179 | let mut uninit = $crate::MaybeUninit::uninit(); 180 | let mut eq = $crate::TypeEqualizer { 181 | enum_map: [], 182 | guard: $crate::Guard::new(&mut uninit), 183 | }; 184 | if false { 185 | // Safe because this code is unreachable 186 | unsafe { (&mut eq.enum_map).as_mut_ptr().read() } 187 | } else { 188 | for _ in 0..(&eq.guard).storage_length() { 189 | struct __PleaseDoNotUseBreakWithoutLabel; 190 | let _please_do_not_use_continue_without_label; 191 | let value; 192 | #[allow(unreachable_code)] 193 | loop { 194 | _please_do_not_use_continue_without_label = (); 195 | value = match (&eq.guard).get_key() { $($t)* }; 196 | break __PleaseDoNotUseBreakWithoutLabel; 197 | }; 198 | 199 | unsafe { (&mut eq.guard).push(value); } 200 | } 201 | $crate::mem::forget(eq); 202 | // Safe because the array was fully initialized. 203 | $crate::EnumMap::from_array(unsafe { uninit.assume_init() }) 204 | } 205 | }}; 206 | } 207 | 208 | /// An enum mapping. 209 | /// 210 | /// This internally uses an array which stores a value for each possible 211 | /// enum value. To work, it requires implementation of internal (private, 212 | /// although public due to macro limitations) trait which allows extracting 213 | /// information about an enum, which can be automatically generated using 214 | /// `#[derive(Enum)]` macro. 215 | /// 216 | /// Additionally, `bool` and `u8` automatically derives from `Enum`. While 217 | /// `u8` is not technically an enum, it's convenient to consider it like one. 218 | /// In particular, [reverse-complement in benchmark game] could be using `u8` 219 | /// as an enum. 220 | /// 221 | /// # Examples 222 | /// 223 | /// ``` 224 | /// use enum_map::{enum_map, Enum, EnumMap}; 225 | /// 226 | /// #[derive(Enum)] 227 | /// enum Example { 228 | /// A, 229 | /// B, 230 | /// C, 231 | /// } 232 | /// 233 | /// let mut map = EnumMap::default(); 234 | /// // new initializes map with default values 235 | /// assert_eq!(map[Example::A], 0); 236 | /// map[Example::A] = 3; 237 | /// assert_eq!(map[Example::A], 3); 238 | /// ``` 239 | /// 240 | /// [reverse-complement in benchmark game]: 241 | /// http://benchmarksgame.alioth.debian.org/u64q/program.php?test=revcomp&lang=rust&id=2 242 | pub struct EnumMap, V> { 243 | array: K::Array, 244 | } 245 | 246 | impl, V: Default> EnumMap { 247 | /// Clear enum map with default values. 248 | /// 249 | /// # Examples 250 | /// 251 | /// ``` 252 | /// use enum_map::{Enum, EnumMap}; 253 | /// 254 | /// #[derive(Enum)] 255 | /// enum Example { 256 | /// A, 257 | /// B, 258 | /// } 259 | /// 260 | /// let mut enum_map = EnumMap::<_, String>::default(); 261 | /// enum_map[Example::B] = "foo".into(); 262 | /// enum_map.clear(); 263 | /// assert_eq!(enum_map[Example::A], ""); 264 | /// assert_eq!(enum_map[Example::B], ""); 265 | /// ``` 266 | #[inline] 267 | pub fn clear(&mut self) { 268 | for v in self.as_mut_slice() { 269 | *v = V::default(); 270 | } 271 | } 272 | } 273 | 274 | #[allow(clippy::len_without_is_empty)] 275 | impl, V> EnumMap { 276 | /// Creates an enum map from array. 277 | #[inline] 278 | pub const fn from_array(array: K::Array) -> EnumMap { 279 | EnumMap { array } 280 | } 281 | 282 | /// Returns an iterator over enum map. 283 | /// 284 | /// The iteration order is deterministic, and when using [macro@Enum] derive 285 | /// it will be the order in which enum variants are declared. 286 | /// 287 | /// # Examples 288 | /// 289 | /// ``` 290 | /// use enum_map::{enum_map, Enum}; 291 | /// 292 | /// #[derive(Enum, PartialEq)] 293 | /// enum E { 294 | /// A, 295 | /// B, 296 | /// C, 297 | /// } 298 | /// 299 | /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; 300 | /// assert!(map.iter().eq([(E::A, &1), (E::B, &2), (E::C, &3)])); 301 | /// ``` 302 | #[inline] 303 | pub fn iter(&self) -> Iter { 304 | self.into_iter() 305 | } 306 | 307 | /// Returns a mutable iterator over enum map. 308 | #[inline] 309 | pub fn iter_mut(&mut self) -> IterMut { 310 | self.into_iter() 311 | } 312 | 313 | /// Returns number of elements in enum map. 314 | #[inline] 315 | #[allow(clippy::unused_self)] 316 | pub const fn len(&self) -> usize { 317 | K::Array::LENGTH 318 | } 319 | 320 | /// Swaps two indexes. 321 | /// 322 | /// # Examples 323 | /// 324 | /// ``` 325 | /// use enum_map::enum_map; 326 | /// 327 | /// let mut map = enum_map! { false => 0, true => 1 }; 328 | /// map.swap(false, true); 329 | /// assert_eq!(map[false], 1); 330 | /// assert_eq!(map[true], 0); 331 | /// ``` 332 | #[inline] 333 | pub fn swap(&mut self, a: K, b: K) { 334 | self.as_mut_slice().swap(a.into_usize(), b.into_usize()); 335 | } 336 | 337 | /// Consumes an enum map and returns the underlying array. 338 | /// 339 | /// The order of elements is deterministic, and when using [macro@Enum] 340 | /// derive it will be the order in which enum variants are declared. 341 | /// 342 | /// # Examples 343 | /// 344 | /// ``` 345 | /// use enum_map::{enum_map, Enum}; 346 | /// 347 | /// #[derive(Enum, PartialEq)] 348 | /// enum E { 349 | /// A, 350 | /// B, 351 | /// C, 352 | /// } 353 | /// 354 | /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; 355 | /// assert_eq!(map.into_array(), [1, 2, 3]); 356 | /// ``` 357 | pub fn into_array(self) -> K::Array { 358 | self.array 359 | } 360 | 361 | /// Returns a reference to the underlying array. 362 | /// 363 | /// The order of elements is deterministic, and when using [macro@Enum] 364 | /// derive it will be the order in which enum variants are declared. 365 | /// 366 | /// # Examples 367 | /// 368 | /// ``` 369 | /// use enum_map::{enum_map, Enum}; 370 | /// 371 | /// #[derive(Enum, PartialEq)] 372 | /// enum E { 373 | /// A, 374 | /// B, 375 | /// C, 376 | /// } 377 | /// 378 | /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; 379 | /// assert_eq!(map.as_array(), &[1, 2, 3]); 380 | /// ``` 381 | pub const fn as_array(&self) -> &K::Array { 382 | &self.array 383 | } 384 | 385 | /// Returns a mutable reference to the underlying array. 386 | /// 387 | /// The order of elements is deterministic, and when using [macro@Enum] 388 | /// derive it will be the order in which enum variants are declared. 389 | /// 390 | /// # Examples 391 | /// 392 | /// ``` 393 | /// use enum_map::{enum_map, Enum}; 394 | /// 395 | /// #[derive(Enum, PartialEq)] 396 | /// enum E { 397 | /// A, 398 | /// B, 399 | /// C, 400 | /// } 401 | /// 402 | /// let mut map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; 403 | /// map.as_mut_array()[1] = 42; 404 | /// assert_eq!(map.as_array(), &[1, 42, 3]); 405 | /// ``` 406 | pub fn as_mut_array(&mut self) -> &mut K::Array { 407 | &mut self.array 408 | } 409 | 410 | /// Converts an enum map to a slice representing values. 411 | /// 412 | /// The order of elements is deterministic, and when using [macro@Enum] 413 | /// derive it will be the order in which enum variants are declared. 414 | /// 415 | /// # Examples 416 | /// 417 | /// ``` 418 | /// use enum_map::{enum_map, Enum}; 419 | /// 420 | /// #[derive(Enum, PartialEq)] 421 | /// enum E { 422 | /// A, 423 | /// B, 424 | /// C, 425 | /// } 426 | /// 427 | /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; 428 | /// assert_eq!(map.as_slice(), &[1, 2, 3]); 429 | /// ``` 430 | #[inline] 431 | pub fn as_slice(&self) -> &[V] { 432 | unsafe { slice::from_raw_parts(ptr::addr_of!(self.array).cast(), K::Array::LENGTH) } 433 | } 434 | 435 | /// Converts a mutable enum map to a mutable slice representing values. 436 | #[inline] 437 | pub fn as_mut_slice(&mut self) -> &mut [V] { 438 | unsafe { slice::from_raw_parts_mut(ptr::addr_of_mut!(self.array).cast(), K::Array::LENGTH) } 439 | } 440 | 441 | /// Returns an enum map with function `f` applied to each element in order. 442 | /// 443 | /// # Examples 444 | /// 445 | /// ``` 446 | /// use enum_map::enum_map; 447 | /// 448 | /// let a = enum_map! { false => 0, true => 1 }; 449 | /// let b = a.map(|_, x| f64::from(x) + 0.5); 450 | /// assert_eq!(b, enum_map! { false => 0.5, true => 1.5 }); 451 | /// ``` 452 | pub fn map(self, mut f: F) -> EnumMap 453 | where 454 | F: FnMut(K, V) -> T, 455 | K: EnumArray, 456 | { 457 | struct DropOnPanic 458 | where 459 | K: EnumArray, 460 | { 461 | position: usize, 462 | map: ManuallyDrop>, 463 | } 464 | impl Drop for DropOnPanic 465 | where 466 | K: EnumArray, 467 | { 468 | fn drop(&mut self) { 469 | unsafe { 470 | ptr::drop_in_place(&mut self.map.as_mut_slice()[self.position..]); 471 | } 472 | } 473 | } 474 | let mut drop_protect = DropOnPanic { 475 | position: 0, 476 | map: ManuallyDrop::new(self), 477 | }; 478 | enum_map! { 479 | k => { 480 | let value = unsafe { ptr::read(&drop_protect.map.as_slice()[drop_protect.position]) }; 481 | drop_protect.position += 1; 482 | f(k, value) 483 | } 484 | } 485 | } 486 | } 487 | -------------------------------------------------------------------------------- /enum-map/src/serde.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2017 - 2023 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 3 | // 4 | // SPDX-License-Identifier: MIT OR Apache-2.0 5 | 6 | use crate::{enum_map, EnumArray, EnumMap}; 7 | use core::fmt; 8 | use core::marker::PhantomData; 9 | use serde::de::{self, Deserialize, Deserializer, Error, MapAccess, SeqAccess}; 10 | use serde::ser::{Serialize, SerializeTuple, Serializer}; 11 | 12 | /// Requires crate feature `"serde"` 13 | impl + Serialize, V: Serialize> Serialize for EnumMap { 14 | fn serialize(&self, serializer: S) -> Result { 15 | if serializer.is_human_readable() { 16 | serializer.collect_map(self) 17 | } else { 18 | let mut tup = serializer.serialize_tuple(self.len())?; 19 | for value in self.values() { 20 | tup.serialize_element(value)?; 21 | } 22 | tup.end() 23 | } 24 | } 25 | } 26 | 27 | /// Requires crate feature `"serde"` 28 | impl<'de, K, V> Deserialize<'de> for EnumMap 29 | where 30 | K: EnumArray + EnumArray> + Deserialize<'de>, 31 | V: Deserialize<'de>, 32 | { 33 | fn deserialize>(deserializer: D) -> Result { 34 | if deserializer.is_human_readable() { 35 | deserializer.deserialize_map(HumanReadableVisitor(PhantomData)) 36 | } else { 37 | deserializer.deserialize_tuple(K::LENGTH, CompactVisitor(PhantomData)) 38 | } 39 | } 40 | } 41 | 42 | struct HumanReadableVisitor(PhantomData<(K, V)>); 43 | 44 | impl<'de, K, V> de::Visitor<'de> for HumanReadableVisitor 45 | where 46 | K: EnumArray + EnumArray> + Deserialize<'de>, 47 | V: Deserialize<'de>, 48 | { 49 | type Value = EnumMap; 50 | 51 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 52 | write!(formatter, "a map") 53 | } 54 | 55 | fn visit_map>(self, mut access: M) -> Result { 56 | let mut entries = EnumMap::default(); 57 | while let Some((key, value)) = access.next_entry()? { 58 | entries[key] = Some(value); 59 | } 60 | for value in entries.values() { 61 | value 62 | .as_ref() 63 | .ok_or_else(|| M::Error::custom("key not specified"))?; 64 | } 65 | Ok(enum_map! { key => entries[key].take().unwrap() }) 66 | } 67 | } 68 | 69 | struct CompactVisitor(PhantomData<(K, V)>); 70 | 71 | impl<'de, K, V> de::Visitor<'de> for CompactVisitor 72 | where 73 | K: EnumArray + EnumArray> + Deserialize<'de>, 74 | V: Deserialize<'de>, 75 | { 76 | type Value = EnumMap; 77 | 78 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 79 | write!(formatter, "a sequence") 80 | } 81 | 82 | fn visit_seq>(self, mut access: M) -> Result { 83 | let mut entries = EnumMap::default(); 84 | let len = entries.len(); 85 | { 86 | let mut iter = entries.values_mut(); 87 | while let Some(place) = iter.next() { 88 | *place = Some(access.next_element()?.ok_or_else(|| { 89 | M::Error::invalid_length( 90 | len - iter.len() - 1, 91 | &"a sequence with as many elements as there are variants", 92 | ) 93 | })?); 94 | } 95 | } 96 | Ok(enum_map! { key => entries[key].take().unwrap() }) 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /enum-map/tests/serde.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "serde")] 2 | 3 | // SPDX-FileCopyrightText: 2017 - 2022 Konrad Borowski 4 | // SPDX-FileCopyrightText: 2022 Cass Fridkin 5 | // 6 | // SPDX-License-Identifier: MIT OR Apache-2.0 7 | 8 | use enum_map::{enum_map, Enum, EnumMap}; 9 | use serde::{Deserialize, Serialize}; 10 | use serde_test::{assert_de_tokens_error, assert_tokens, Compact, Configure, Token}; 11 | 12 | #[derive(Debug, Enum, Deserialize, Serialize)] 13 | enum Example { 14 | A, 15 | B, 16 | } 17 | 18 | #[test] 19 | fn serialization() { 20 | let map = enum_map! { Example::A => 5, Example::B => 10 }; 21 | assert_tokens( 22 | &map.readable(), 23 | &[ 24 | Token::Map { len: Some(2) }, 25 | Token::UnitVariant { 26 | name: "Example", 27 | variant: "A", 28 | }, 29 | Token::I32(5), 30 | Token::UnitVariant { 31 | name: "Example", 32 | variant: "B", 33 | }, 34 | Token::I32(10), 35 | Token::MapEnd, 36 | ], 37 | ); 38 | } 39 | 40 | #[test] 41 | fn compact_serialization() { 42 | let map = enum_map! { Example::A => 5, Example::B => 10 }; 43 | assert_tokens( 44 | &map.compact(), 45 | &[ 46 | Token::Tuple { len: 2 }, 47 | Token::I32(5), 48 | Token::I32(10), 49 | Token::TupleEnd, 50 | ], 51 | ); 52 | } 53 | 54 | #[test] 55 | fn invalid_compact_deserialization() { 56 | assert_de_tokens_error::>>( 57 | &[Token::I32(4)], 58 | "invalid type: integer `4`, expected a sequence", 59 | ); 60 | } 61 | 62 | #[test] 63 | fn too_short_compact_deserialization() { 64 | assert_de_tokens_error::>>( 65 | &[Token::Seq { len: None }, Token::Bool(true), Token::SeqEnd], 66 | "invalid length 1, expected a sequence with as many elements as there are variants", 67 | ); 68 | } 69 | 70 | const JSON: &str = r#"{"A":5,"B":10}"#; 71 | 72 | #[test] 73 | fn json_serialization() { 74 | let map = enum_map! { Example::A => 5, Example::B => 10 }; 75 | assert_eq!(serde_json::to_string(&map).unwrap(), String::from(JSON)); 76 | } 77 | 78 | #[test] 79 | fn json_deserialization() { 80 | let example: EnumMap = serde_json::from_str(JSON).unwrap(); 81 | assert_eq!(example, enum_map! { Example::A => 5, Example::B => 10 }); 82 | } 83 | 84 | #[test] 85 | fn json_invalid_deserialization() { 86 | let example: Result, _> = serde_json::from_str(r"{}"); 87 | assert!(example.is_err()); 88 | } 89 | 90 | #[test] 91 | fn json_invalid_type() { 92 | let example: Result, _> = serde_json::from_str("4"); 93 | assert!(example.is_err()); 94 | } 95 | 96 | #[test] 97 | fn json_invalid_key() { 98 | let example: Result, _> = 99 | serde_json::from_str(r#"{"a": 5, "b": 10, "c": 6}"#); 100 | assert!(example.is_err()); 101 | } 102 | 103 | #[test] 104 | fn bincode_serialization() { 105 | let example = enum_map! { false => 3u8, true => 4u8 }; 106 | let serialized = bincode::serialize(&example).unwrap(); 107 | assert_eq!(example, bincode::deserialize(&serialized).unwrap()); 108 | } 109 | 110 | #[test] 111 | fn bincode_too_short_deserialization() { 112 | assert!( 113 | bincode::deserialize::>(&bincode::serialize(&()).unwrap()).is_err() 114 | ); 115 | } 116 | -------------------------------------------------------------------------------- /enum-map/tests/test.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2018 - 2022 Konrad Borowski 2 | // SPDX-FileCopyrightText: 2019 Riey 3 | // SPDX-FileCopyrightText: 2020 Amanieu d'Antras 4 | // SPDX-FileCopyrightText: 2021 Bruno Corrêa Zimmermann 5 | // SPDX-FileCopyrightText: 2021 micycle 6 | // SPDX-FileCopyrightText: 2022 Cass Fridkin 7 | // 8 | // SPDX-License-Identifier: MIT OR Apache-2.0 9 | 10 | #[macro_use] 11 | extern crate enum_map; 12 | 13 | use enum_map::{Enum, EnumArray, EnumMap, IntoIter}; 14 | 15 | use std::cell::{Cell, RefCell}; 16 | use std::collections::HashSet; 17 | use std::convert::Infallible; 18 | use std::marker::PhantomData; 19 | use std::num::ParseIntError; 20 | use std::panic::{catch_unwind, UnwindSafe}; 21 | 22 | trait From: Sized { 23 | fn from(_: T) -> Self { 24 | unreachable!(); 25 | } 26 | } 27 | 28 | impl From for U {} 29 | 30 | #[derive(Copy, Clone, Debug, Enum, PartialEq)] 31 | enum Example { 32 | A, 33 | B, 34 | C, 35 | } 36 | 37 | #[test] 38 | fn test_bool() { 39 | let mut map = enum_map! { false => 24, true => 42 }; 40 | assert_eq!(map[false], 24); 41 | assert_eq!(map[true], 42); 42 | map[false] += 1; 43 | assert_eq!(map[false], 25); 44 | for (key, item) in &mut map { 45 | if !key { 46 | *item += 1; 47 | } 48 | } 49 | assert_eq!(map[false], 26); 50 | assert_eq!(map[true], 42); 51 | } 52 | 53 | #[test] 54 | fn test_clone() { 55 | let map = enum_map! { false => 3, true => 5 }; 56 | assert_eq!(map.clone(), map); 57 | } 58 | 59 | #[test] 60 | fn test_debug() { 61 | let map = enum_map! { false => 3, true => 5 }; 62 | assert_eq!(format!("{:?}", map), "{false: 3, true: 5}"); 63 | } 64 | 65 | #[test] 66 | fn test_hash() { 67 | let map = enum_map! { false => 3, true => 5 }; 68 | let mut set = HashSet::new(); 69 | set.insert(map); 70 | assert!(set.contains(&map)); 71 | } 72 | 73 | #[test] 74 | fn test_clear() { 75 | let mut map = enum_map! { false => 1, true => 2 }; 76 | map.clear(); 77 | assert_eq!(map[true], 0); 78 | assert_eq!(map[false], 0); 79 | } 80 | 81 | #[test] 82 | fn struct_of_enum() { 83 | #[derive(Copy, Clone, Debug, Enum, PartialEq)] 84 | struct Product { 85 | example: Example, 86 | is_done: bool, 87 | } 88 | 89 | let mut map = enum_map! { 90 | Product { example: Example::A, is_done: false } => "foo", 91 | Product { example: Example::B, is_done: false } => "bar", 92 | Product { example: Example::C, is_done: false } => "baz", 93 | Product { example: Example::A, is_done: true } => "done foo", 94 | Product { example: Example::B, is_done: true } => "bar done", 95 | Product { example: Example::C, is_done: true } => "doooozne", 96 | }; 97 | 98 | assert_eq!( 99 | map[Product { 100 | example: Example::B, 101 | is_done: false 102 | }], 103 | "bar" 104 | ); 105 | assert_eq!( 106 | map[Product { 107 | example: Example::C, 108 | is_done: false 109 | }], 110 | "baz" 111 | ); 112 | assert_eq!( 113 | map[Product { 114 | example: Example::B, 115 | is_done: true 116 | }], 117 | "bar done" 118 | ); 119 | 120 | map[Product { 121 | example: Example::B, 122 | is_done: true, 123 | }] = "not really done"; 124 | assert_eq!( 125 | map[Product { 126 | example: Example::B, 127 | is_done: false 128 | }], 129 | "bar" 130 | ); 131 | assert_eq!( 132 | map[Product { 133 | example: Example::C, 134 | is_done: false 135 | }], 136 | "baz" 137 | ); 138 | assert_eq!( 139 | map[Product { 140 | example: Example::B, 141 | is_done: true 142 | }], 143 | "not really done" 144 | ); 145 | } 146 | 147 | #[test] 148 | fn tuple_struct_of_enum() { 149 | #[derive(Copy, Clone, Debug, Enum, PartialEq)] 150 | struct Product(Example, bool); 151 | 152 | let mut map = enum_map! { 153 | Product(Example::A, false) => "foo", 154 | Product(Example::B, false) => "bar", 155 | Product(Example::C, false) => "baz", 156 | Product(Example::A, true) => "done foo", 157 | Product(Example::B, true) => "bar done", 158 | Product(Example::C, true) => "doooozne", 159 | }; 160 | 161 | assert_eq!(map[Product(Example::B, false)], "bar"); 162 | assert_eq!(map[Product(Example::C, false)], "baz"); 163 | assert_eq!(map[Product(Example::B, true)], "bar done"); 164 | 165 | map[Product(Example::B, true)] = "not really done"; 166 | assert_eq!(map[Product(Example::B, false)], "bar"); 167 | assert_eq!(map[Product(Example::C, false)], "baz"); 168 | assert_eq!(map[Product(Example::B, true)], "not really done"); 169 | } 170 | 171 | #[test] 172 | fn discriminants() { 173 | #[derive(Debug, Enum, PartialEq)] 174 | enum Discriminants { 175 | A = 2000, 176 | B = 3000, 177 | C = 1000, 178 | } 179 | let mut map = EnumMap::default(); 180 | map[Discriminants::A] = 3; 181 | map[Discriminants::B] = 2; 182 | map[Discriminants::C] = 1; 183 | let mut pairs = map.iter(); 184 | assert_eq!(pairs.next(), Some((Discriminants::A, &3))); 185 | assert_eq!(pairs.next(), Some((Discriminants::B, &2))); 186 | assert_eq!(pairs.next(), Some((Discriminants::C, &1))); 187 | assert_eq!(pairs.next(), None); 188 | } 189 | 190 | #[test] 191 | fn extend() { 192 | let mut map = enum_map! { _ => 0 }; 193 | map.extend(vec![(Example::A, 3)]); 194 | map.extend(vec![(&Example::B, &4)]); 195 | assert_eq!( 196 | map, 197 | enum_map! { Example::A => 3, Example::B => 4, Example::C => 0 } 198 | ); 199 | } 200 | 201 | #[test] 202 | fn collect() { 203 | let iter = vec![(Example::A, 5), (Example::B, 7)] 204 | .into_iter() 205 | .map(|(k, v)| (k, v + 1)); 206 | assert_eq!( 207 | iter.collect::>(), 208 | enum_map! { Example::A => 6, Example::B => 8, Example::C => 0 } 209 | ); 210 | } 211 | 212 | #[test] 213 | fn huge_enum() { 214 | #[derive(Enum)] 215 | enum Example { 216 | A, 217 | B, 218 | C, 219 | D, 220 | E, 221 | F, 222 | G, 223 | H, 224 | I, 225 | J, 226 | K, 227 | L, 228 | M, 229 | N, 230 | O, 231 | P, 232 | Q, 233 | R, 234 | S, 235 | T, 236 | U, 237 | V, 238 | W, 239 | X, 240 | Y, 241 | Z, 242 | Aa, 243 | Bb, 244 | Cc, 245 | Dd, 246 | Ee, 247 | Ff, 248 | Gg, 249 | Hh, 250 | Ii, 251 | Jj, 252 | Kk, 253 | Ll, 254 | Mm, 255 | Nn, 256 | Oo, 257 | Pp, 258 | Qq, 259 | Rr, 260 | Ss, 261 | Tt, 262 | Uu, 263 | Vv, 264 | Ww, 265 | Xx, 266 | Yy, 267 | Zz, 268 | } 269 | 270 | let map = enum_map! { _ => 2 }; 271 | assert_eq!(map[Example::Xx], 2); 272 | } 273 | 274 | #[test] 275 | fn iterator_len() { 276 | assert_eq!( 277 | enum_map! { Example::A | Example::B | Example::C => 0 } 278 | .iter() 279 | .len(), 280 | 3 281 | ); 282 | } 283 | 284 | #[test] 285 | fn iter_mut_len() { 286 | assert_eq!( 287 | enum_map! { Example::A | Example::B | Example::C => 0 } 288 | .iter_mut() 289 | .len(), 290 | 3 291 | ); 292 | } 293 | 294 | #[test] 295 | fn into_iter_len() { 296 | assert_eq!(enum_map! { Example::A | _ => 0 }.into_iter().len(), 3); 297 | } 298 | 299 | #[test] 300 | fn iterator_next_back() { 301 | assert_eq!( 302 | enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } 303 | .iter() 304 | .next_back(), 305 | Some((Example::C, &3)) 306 | ); 307 | } 308 | 309 | #[test] 310 | fn iter_mut_next_back() { 311 | assert_eq!( 312 | enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } 313 | .iter_mut() 314 | .next_back(), 315 | Some((Example::C, &mut 3)) 316 | ); 317 | } 318 | 319 | #[test] 320 | fn into_iter() { 321 | let mut iter = enum_map! { true => 5, false => 7 }.into_iter(); 322 | assert_eq!(iter.next(), Some((false, 7))); 323 | assert_eq!(iter.next(), Some((true, 5))); 324 | assert_eq!(iter.next(), None); 325 | assert_eq!(iter.next(), None); 326 | } 327 | 328 | #[test] 329 | fn into_iter_u8() { 330 | assert_eq!( 331 | enum_map! { i => i }.into_iter().collect::>(), 332 | (0..256).map(|x| (x as u8, x as u8)).collect::>() 333 | ); 334 | } 335 | 336 | struct DropReporter<'a> { 337 | into: &'a RefCell>, 338 | value: usize, 339 | } 340 | 341 | impl<'a> Drop for DropReporter<'a> { 342 | fn drop(&mut self) { 343 | self.into.borrow_mut().push(self.value); 344 | } 345 | } 346 | 347 | #[test] 348 | fn into_iter_drop() { 349 | let dropped = RefCell::new(Vec::default()); 350 | let mut a: IntoIter = enum_map! { 351 | k => DropReporter { 352 | into: &dropped, 353 | value: k as usize, 354 | }, 355 | } 356 | .into_iter(); 357 | assert_eq!(a.next().unwrap().0, Example::A); 358 | assert_eq!(*dropped.borrow(), &[0]); 359 | drop(a); 360 | assert_eq!(*dropped.borrow(), &[0, 1, 2]); 361 | } 362 | 363 | #[test] 364 | fn into_iter_double_ended_iterator() { 365 | let mut iter = enum_map! { 0 => 5, 255 => 7, _ => 0 }.into_iter(); 366 | assert_eq!(iter.next(), Some((0, 5))); 367 | assert_eq!(iter.next_back(), Some((255, 7))); 368 | assert_eq!(iter.next(), Some((1, 0))); 369 | assert_eq!(iter.next_back(), Some((254, 0))); 370 | assert!(iter.rev().eq((2..254).rev().map(|i| (i, 0)))); 371 | } 372 | 373 | #[test] 374 | fn values_rev_collect() { 375 | assert_eq!( 376 | vec![3, 2, 1], 377 | enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } 378 | .values() 379 | .rev() 380 | .cloned() 381 | .collect::>() 382 | ); 383 | } 384 | 385 | #[test] 386 | fn values_len() { 387 | assert_eq!(enum_map! { false => 0, true => 1 }.values().len(), 2); 388 | } 389 | 390 | #[test] 391 | fn into_values_rev_collect() { 392 | assert_eq!( 393 | vec![3, 2, 1], 394 | enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } 395 | .into_values() 396 | .rev() 397 | .collect::>() 398 | ); 399 | } 400 | 401 | #[test] 402 | fn into_values_len() { 403 | assert_eq!(enum_map! { false => 0, true => 1 }.into_values().len(), 2); 404 | } 405 | 406 | #[test] 407 | fn values_mut_next_back() { 408 | let mut map = enum_map! { false => 0, true => 1 }; 409 | assert_eq!(map.values_mut().next_back(), Some(&mut 1)); 410 | } 411 | #[test] 412 | fn test_u8() { 413 | let mut map = enum_map! { b'a' => 4, _ => 0 }; 414 | map[b'c'] = 3; 415 | assert_eq!(map[b'a'], 4); 416 | assert_eq!(map[b'b'], 0); 417 | assert_eq!(map[b'c'], 3); 418 | assert_eq!(map.iter().next(), Some((0, &0))); 419 | } 420 | 421 | #[derive(Enum)] 422 | enum Void {} 423 | 424 | #[test] 425 | fn empty_map() { 426 | let void: EnumMap = enum_map! {}; 427 | assert_eq!(void.len(), 0); 428 | } 429 | 430 | #[test] 431 | #[should_panic] 432 | fn empty_value() { 433 | let _void: EnumMap = enum_map! { _ => unreachable!() }; 434 | } 435 | 436 | #[test] 437 | fn empty_infallible_map() { 438 | let void: EnumMap = enum_map! {}; 439 | assert_eq!(void.len(), 0); 440 | } 441 | 442 | #[derive(Clone, Copy)] 443 | enum X { 444 | A(PhantomData<*const ()>), 445 | } 446 | 447 | impl Enum for X { 448 | const LENGTH: usize = 1; 449 | 450 | fn from_usize(arg: usize) -> X { 451 | assert_eq!(arg, 0); 452 | X::A(PhantomData) 453 | } 454 | 455 | fn into_usize(self) -> usize { 456 | 0 457 | } 458 | } 459 | 460 | impl EnumArray for X { 461 | type Array = [V; Self::LENGTH]; 462 | } 463 | 464 | fn assert_sync_send(_: T) {} 465 | 466 | #[test] 467 | fn assert_enum_map_does_not_copy_sync_send_dependency_of_keys() { 468 | let mut map = enum_map! { X::A(PhantomData) => true }; 469 | assert_sync_send(map); 470 | assert_sync_send(&map); 471 | assert_sync_send(&mut map); 472 | assert_sync_send(map.iter()); 473 | assert_sync_send(map.iter_mut()); 474 | assert_sync_send(map.into_iter()); 475 | assert!(map[X::A(PhantomData)]); 476 | } 477 | 478 | #[test] 479 | fn test_sum() { 480 | assert_eq!( 481 | enum_map! { i => u8::into(i) } 482 | .iter() 483 | .map(|(_, v)| v) 484 | .sum::(), 485 | 32_640 486 | ); 487 | } 488 | 489 | #[test] 490 | fn test_sum_mut() { 491 | assert_eq!( 492 | enum_map! { i => u8::into(i) } 493 | .iter_mut() 494 | .map(|(_, &mut v)| -> u32 { v }) 495 | .sum::(), 496 | 32_640 497 | ); 498 | } 499 | 500 | #[test] 501 | fn test_iter_clone() { 502 | struct S(u8); 503 | let map = enum_map! { 504 | Example::A => S(3), 505 | Example::B => S(4), 506 | Example::C => S(1), 507 | }; 508 | let iter = map.iter(); 509 | assert_eq!(iter.clone().map(|(_, S(v))| v).sum::(), 8); 510 | assert_eq!(iter.map(|(_, S(v))| v).sum::(), 8); 511 | let values = map.values(); 512 | assert_eq!(values.clone().map(|S(v)| v).sum::(), 8); 513 | assert_eq!(values.map(|S(v)| v).sum::(), 8); 514 | } 515 | 516 | #[test] 517 | fn question_mark() -> Result<(), ParseIntError> { 518 | let map = enum_map! { false => "2".parse()?, true => "5".parse()? }; 519 | assert_eq!(map, enum_map! { false => 2, true => 5 }); 520 | Ok(()) 521 | } 522 | 523 | #[test] 524 | fn question_mark_failure() { 525 | struct IncOnDrop<'a>(&'a Cell); 526 | 527 | impl Drop for IncOnDrop<'_> { 528 | fn drop(&mut self) { 529 | self.0.set(self.0.get() + 1); 530 | } 531 | } 532 | 533 | fn failible() -> Result, &'static str> { 534 | Err("ERROR!") 535 | } 536 | 537 | fn try_block(inc: &Cell) -> Result<(), &'static str> { 538 | enum_map! { 539 | 32 => failible()?, 540 | _ => { 541 | IncOnDrop(inc) 542 | } 543 | }; 544 | Ok(()) 545 | } 546 | let value = Cell::new(0); 547 | assert_eq!(try_block(&value), Err("ERROR!")); 548 | assert_eq!(value.get(), 32); 549 | } 550 | 551 | #[test] 552 | #[should_panic = "Intentional panic"] 553 | fn map_panic() { 554 | let map: EnumMap = enum_map! { i => i.to_string() }; 555 | map.map(|k, v| { 556 | if k == 2 { 557 | panic!("Intentional panic"); 558 | } 559 | v + " modified" 560 | }); 561 | } 562 | 563 | macro_rules! make_enum_map_macro_safety_test { 564 | ($a:tt $b:tt) => { 565 | // This is misuse of an API, however we need to test that to ensure safety 566 | // as we use unsafe code. 567 | enum E { 568 | A, 569 | B, 570 | C, 571 | } 572 | 573 | impl Enum for E { 574 | const LENGTH: usize = $a; 575 | 576 | fn from_usize(value: usize) -> E { 577 | match value { 578 | 0 => E::A, 579 | 1 => E::B, 580 | 2 => E::C, 581 | _ => unimplemented!(), 582 | } 583 | } 584 | 585 | fn into_usize(self) -> usize { 586 | self as usize 587 | } 588 | } 589 | 590 | impl EnumArray for E { 591 | type Array = [V; $b]; 592 | } 593 | 594 | let map: EnumMap = enum_map! { _ => "Hello, world!".into() }; 595 | map.into_iter(); 596 | }; 597 | } 598 | 599 | #[test] 600 | fn enum_map_macro_safety_under() { 601 | make_enum_map_macro_safety_test!(2 3); 602 | } 603 | 604 | #[test] 605 | fn enum_map_macro_safety_over() { 606 | make_enum_map_macro_safety_test!(3 2); 607 | } 608 | 609 | #[test] 610 | fn drop_panic_into_iter() { 611 | struct DropHandler<'a>(&'a Cell); 612 | impl Drop for DropHandler<'_> { 613 | fn drop(&mut self) { 614 | self.0.set(self.0.get() + 1); 615 | } 616 | } 617 | impl UnwindSafe for DropHandler<'_> {} 618 | struct Storage<'a> { 619 | should_panic: bool, 620 | _drop_handler: DropHandler<'a>, 621 | } 622 | impl Drop for Storage<'_> { 623 | fn drop(&mut self) { 624 | if self.should_panic { 625 | panic!(); 626 | } 627 | } 628 | } 629 | let cell = Cell::new(0); 630 | let map: EnumMap = enum_map! { 631 | v => Storage { should_panic: v == Example::B, _drop_handler: DropHandler(&cell) }, 632 | }; 633 | assert!(catch_unwind(|| { 634 | map.into_iter(); 635 | }) 636 | .is_err()); 637 | assert_eq!(cell.get(), 3); 638 | } 639 | 640 | #[test] 641 | fn test_const_enum_map_from_array() { 642 | const CONST_ENUM_MAP_FROM_ARRAY: EnumMap = EnumMap::from_array([4, 8]); 643 | assert_eq!( 644 | CONST_ENUM_MAP_FROM_ARRAY, 645 | enum_map! { false => 4, true => 8 }, 646 | ); 647 | } 648 | 649 | #[test] 650 | fn usize_override() { 651 | #[allow(non_camel_case_types, dead_code)] 652 | type usize = (); 653 | #[derive(Enum)] 654 | enum X { 655 | A, 656 | B, 657 | } 658 | } 659 | --------------------------------------------------------------------------------