enum-map-2.4.2/.cargo_vcs_info.json0000644000000001460000000000100125610ustar { "git": { "sha1": "f44be54f1880c457c47ba8641fa244c01e33437d" }, "path_in_vcs": "enum-map" }enum-map-2.4.2/CHANGELOG.md000064400000000000000000000103111046102023000131550ustar 00000000000000# Version 2.4.2 ## Other changes - Added license files to crate tarball. - Added changelog to crate tarball. # Version 2.4.1 ## Other changes - Improved performance of code generated for `from_usize` when deriving `Enum`. # Version 2.4.0 ## New features - Implemented `Enum` for `()` (unit type) and `core::cmp::Ordering` (implemented by [@phimuemue](https://github.com/phimuemue)). - Implemented `EnumMap::into_array`. # Version 2.3.0 ## New features - `EnumMap::len` is now usable in const contexts. ## Other changes - `Enum` derive now can deal with re-definitions of `usize` and `unimplemented`. # Version 2.2.0 ## New features - `EnumMap::from_array` is now usable in const contexts. # Version 2.1.0 ## New features - Implemented `DoubleEndedIterator` for `IntoIter`. - Implemented `EnumMap::into_values`. ## Other changes - Changed behavior of `IntoIter` so that it drops rest of the elements when one destructor panics. # Version 2.0.3 ## Other changes - Optimized performance of `enum_map!` macro. # Version 2.0.2 ## Other changes - Fixed safety problem when using `enum_map!` macro with enums that incorrectly implemented `Enum` trait. # Version 2.0.1 ## Other changes - Adjusted crate metadata to avoid lib.rs warnings. # Version 2.0.0 ## New features - Implemented `FromIterator` for `EnumMap` (implemented by @bit_network on GitLab). - Implemented `EnumMap::map`. - Derives support product types in addition to sum types (implemented by @bzim on GitLab). - It's now possible to access enum length by accessing `LENGTH` in `Enum` trait. ## Breaking changes - `Enum` trait was split into two traits, `Enum` and `EnumArray`. # Version 1.1.1 ## Other changes - Worked around a bug in Clippy that caused false positives when using `use_self` lint for code that derived `Enum` trait. # Version 1.1.0 ## New features - Implemented `Arbitrary` for maps where the value type also implements `Arbitrary`. (You have to enable the "arbitrary" feature.) # Version 1.0.0 ## New features - It's now possible to use `return` and `?` within `macro_rules!` macro. - `Enum` trait is much simpler having two methods only. ## Other changes - Removed previously deprecated features. - Renamed `to_usize` to `into_usize` matching the naming convention used in Rust programming language. # Version 0.6.5 ## Other changes - Deprecated `EnumMap::is_empty` and `EnumMap::new`. `EnumMap::new` usages can be replaced with `EnumMap::default`. # Version 0.6.4 ## Other changes - Deprecated `EnumMap::as_ptr` and `EnumMap::as_mut_ptr`. # Version 0.6.3 ## New features - `Iter` and `Values` now implements `Clone` (added by @amanieu). # Version 0.6.2. ## New features - Added `EnumMap#clear` method (added by @Riey, thanks :)). # Version 0.6.0 ## Incompatible changes - Now requires Rust 1.36. # Version 0.5.0 - Fixed the issue where an aliasing `From` trait implementation caused compilation errors with `enum_map!` macro. ## Incompatible changes - Now requires Rust 1.31. # Version 0.4.1 ## New features - Default `serde` features are disabled. This allows enabling serde feature when compiling without `std`. # Version 0.4.0 Change of `#[derive(EnumMap)]` to `#[derive(Enum)]` was supposed to appear in 0.3.0, but it was forgotten about. This release fixes just that. ## Incompatible changes - Changed `#[derive(EnumMap)]` to `#[derive(Enum)]` to match trait name. # Version 0.3.1 - Updated README use `#[derive(EnumMap)]` instead of `#[derive(Enum)]`. # Version 0.3.0 ## New features - Implemented compact serde serialization for binary formats like bincode. - Iterator traits with exception now implement `FusedIterator`. ## Incompatible changes - Increased required Rust version to 1.26.0. - Renamed `Internal` trait to `Enum`. - Added new associated constant `POSSIBLE_VALUES` to `Enum` trait, representing the number of possible values the type can have. Manual implementations are required to provide it. - Removed `Enum` implementation for `Option`. - Implemented compact serialization, for formats like `bincode`. This makes it impossible to deserialize non-compact representation used by enum-map 0.2.0. - `values` method returns `Values` as opposed to `slice::Iter`. enum-map-2.4.2/Cargo.toml0000644000000027170000000000100105650ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.61" name = "enum-map" version = "2.4.2" authors = ["Konrad Borowski "] description = "A map with C-like enum keys represented internally as an array" documentation = "https://docs.rs/enum-map" readme = "README.md" keywords = [ "data-structure", "no_std", "enum", ] categories = [ "data-structures", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/xfix/enum-map" resolver = "1" [package.metadata.docs.rs] features = [ "arbitrary", "serde", ] [dependencies.arbitrary] version = "1.0.0" optional = true [dependencies.enum-map-derive] version = "0.11.0" [dependencies.serde] version = "1.0.16" optional = true default-features = false [dev-dependencies.bincode] version = "1.0.0" [dev-dependencies.serde] version = "1.0.103" features = ["derive"] [dev-dependencies.serde_json] version = "1.0.2" [dev-dependencies.serde_test] version = "1.0.19" [badges.maintenance] status = "actively-developed" enum-map-2.4.2/Cargo.toml.orig000064400000000000000000000016231046102023000142410ustar 00000000000000[package] name = "enum-map" version = "2.4.2" authors = ["Konrad Borowski "] edition = "2021" rust-version = "1.61" repository = "https://github.com/xfix/enum-map" license = "MIT OR Apache-2.0" description = "A map with C-like enum keys represented internally as an array" keywords = ["data-structure", "no_std", "enum"] categories = ["data-structures", "no-std"] documentation = "https://docs.rs/enum-map" readme = "README.md" [badges] maintenance = { status = "actively-developed" } [dependencies] arbitrary = { version = "1.0.0", optional = true } enum-map-derive = { version = "0.11.0", path = "../enum-map-derive" } serde = { version = "1.0.16", optional = true, default-features = false } [dev-dependencies] bincode = "1.0.0" serde = { version = "1.0.103", features = ["derive"] } serde_test = "1.0.19" serde_json = "1.0.2" [package.metadata.docs.rs] features = ["arbitrary", "serde"] enum-map-2.4.2/LICENSE-APACHE000064400000000000000000000251371046102023000133040ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. enum-map-2.4.2/LICENSE-MIT000064400000000000000000000020431046102023000130030ustar 00000000000000Copyright (c) 2017 Konrad Borowski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. enum-map-2.4.2/README.md000064400000000000000000000013441046102023000126310ustar 00000000000000# enum-map A library providing enum map providing type safe enum array. It is implemented using regular Rust arrays, so using them is as fast as using regular Rust arrays. This library doesn't provide Minimum Supported Rust Version (MSRV). If you find having MSRV valuable, please use enum-map 0.6 instead. ## Examples ```rust #[macro_use] extern crate enum_map; use enum_map::EnumMap; #[derive(Debug, Enum)] enum Example { A, B, C, } fn main() { let mut map = enum_map! { Example::A => 1, Example::B => 2, Example::C => 3, }; map[Example::C] = 4; assert_eq!(map[Example::A], 1); for (key, &value) in &map { println!("{:?} has {} as value.", key, value); } } ``` enum-map-2.4.2/src/arbitrary.rs000064400000000000000000000012711046102023000145050ustar 00000000000000use crate::{enum_map, EnumArray, EnumMap}; use arbitrary::{Arbitrary, Result, Unstructured}; /// Requires crate feature `"arbitrary"` impl<'a, K: EnumArray, V: Arbitrary<'a>> Arbitrary<'a> for EnumMap { fn arbitrary(u: &mut Unstructured<'a>) -> Result> { Ok(enum_map! { _ => Arbitrary::arbitrary(u)?, }) } fn size_hint(depth: usize) -> (usize, Option) { if K::LENGTH == 0 { (0, Some(0)) } else { let (lo, hi) = V::size_hint(depth); ( lo.saturating_mul(K::LENGTH), hi.and_then(|hi| hi.checked_mul(K::LENGTH)), ) } } } enum-map-2.4.2/src/enum_map_impls.rs000064400000000000000000000045431046102023000155200ustar 00000000000000use crate::{enum_map, EnumArray, EnumMap}; use core::fmt::{self, Debug, Formatter}; use core::hash::{Hash, Hasher}; use core::iter::{Extend, FromIterator}; use core::ops::{Index, IndexMut}; impl + Debug, V: Debug> Debug for EnumMap { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_map().entries(self).finish() } } impl, V> Extend<(K, V)> for EnumMap { fn extend>(&mut self, iter: I) { for (key, value) in iter { self[key] = value; } } } impl<'a, K, V> Extend<(&'a K, &'a V)> for EnumMap where K: EnumArray + Copy, V: Copy, { fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); } } impl FromIterator<(K, V)> for EnumMap where Self: Default, K: EnumArray, { fn from_iter>(iter: I) -> Self { let mut map = EnumMap::default(); map.extend(iter); map } } impl, V> Index for EnumMap { type Output = V; #[inline] fn index(&self, key: K) -> &V { &self.as_slice()[key.into_usize()] } } impl, V> IndexMut for EnumMap { #[inline] fn index_mut(&mut self, key: K) -> &mut V { &mut self.as_mut_slice()[key.into_usize()] } } // Implementations provided by derive attribute are too specific, and put requirements on K. // This is caused by rust-lang/rust#26925. impl, V> Clone for EnumMap where K::Array: Clone, { #[inline] fn clone(&self) -> Self { EnumMap { array: self.array.clone(), } } } impl, V> Copy for EnumMap where K::Array: Copy {} impl, V: PartialEq> PartialEq for EnumMap { #[inline] fn eq(&self, other: &Self) -> bool { self.as_slice() == other.as_slice() } } impl, V: Eq> Eq for EnumMap {} impl, V: Hash> Hash for EnumMap { #[inline] fn hash(&self, state: &mut H) { self.as_slice().hash(state); } } impl, V: Default> Default for EnumMap { #[inline] fn default() -> Self { enum_map! { _ => V::default() } } } enum-map-2.4.2/src/internal.rs000064400000000000000000000064161046102023000143300ustar 00000000000000use core::cmp::Ordering; use core::convert::Infallible; /// Enum mapping type. /// /// This trait is implemented by `#[derive(Enum)]`. /// /// This trait is also implemented by `bool` and `u8`. While `u8` is /// strictly speaking not an actual enum, there are good reasons to consider /// it like one, as array of `u8` keys is a relatively common pattern. pub trait Enum: Sized { /// Length of the enum. const LENGTH: usize; /// Takes an usize, and returns an element matching `into_usize` function. fn from_usize(value: usize) -> Self; /// Returns an unique identifier for a value within range of `0..Array::LENGTH`. fn into_usize(self) -> usize; } /// Trait associating enum with an array. /// /// This exists due to limitations of Rust compiler that prevent arrays from using /// associated constants in structures. The array length must match `LENGTH` of an /// `Enum`. pub trait EnumArray: Enum { /// Representation of an enum map for type `V`. type Array: Array; } /// Array for enum-map storage. /// /// This trait is inteded for primitive array types (with fixed length). /// /// # Safety /// /// The array length needs to match actual storage. pub unsafe trait Array { // This is necessary duplication because the length in Enum trait can be // provided by user and may not be trustworthy for unsafe code. const LENGTH: usize; } unsafe impl Array for [V; N] { const LENGTH: usize = N; } impl Enum for bool { const LENGTH: usize = 2; #[inline] fn from_usize(value: usize) -> Self { match value { 0 => false, 1 => true, _ => unreachable!(), } } #[inline] fn into_usize(self) -> usize { usize::from(self) } } impl EnumArray for bool { type Array = [T; Self::LENGTH]; } impl Enum for () { const LENGTH: usize = 1; #[inline] fn from_usize(value: usize) -> Self { match value { 0 => (), _ => unreachable!(), } } #[inline] fn into_usize(self) -> usize { 0 } } impl EnumArray for () { type Array = [T; Self::LENGTH]; } impl Enum for u8 { const LENGTH: usize = 256; #[inline] fn from_usize(value: usize) -> Self { value.try_into().unwrap() } #[inline] fn into_usize(self) -> usize { usize::from(self) } } impl EnumArray for u8 { type Array = [T; Self::LENGTH]; } impl Enum for Infallible { const LENGTH: usize = 0; #[inline] fn from_usize(_: usize) -> Self { unreachable!(); } #[inline] fn into_usize(self) -> usize { match self {} } } impl EnumArray for Infallible { type Array = [T; Self::LENGTH]; } impl Enum for Ordering { const LENGTH: usize = 3; #[inline] fn from_usize(value: usize) -> Self { match value { 0 => Ordering::Less, 1 => Ordering::Equal, 2 => Ordering::Greater, _ => unreachable!(), } } #[inline] fn into_usize(self) -> usize { match self { Ordering::Less => 0, Ordering::Equal => 1, Ordering::Greater => 2, } } } impl EnumArray for Ordering { type Array = [T; Self::LENGTH]; } enum-map-2.4.2/src/iter.rs000064400000000000000000000236351046102023000134610ustar 00000000000000#![allow(clippy::module_name_repetitions)] use crate::{EnumArray, EnumMap}; use core::iter::{Enumerate, FusedIterator}; use core::marker::PhantomData; use core::mem::ManuallyDrop; use core::ops::Range; use core::ptr; use core::slice; /// Immutable enum map iterator /// /// This struct is created by `iter` method or `into_iter` on a reference /// to `EnumMap`. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// C, /// } /// /// let mut map = enum_map! { Example::A => 3, _ => 0 }; /// assert_eq!(map[Example::A], 3); /// for (key, &value) in &map { /// assert_eq!(value, match key { /// Example::A => 3, /// _ => 0, /// }); /// } /// ``` #[derive(Debug)] pub struct Iter<'a, K, V: 'a> { _phantom: PhantomData K>, iterator: Enumerate>, } impl<'a, K: EnumArray, V> Clone for Iter<'a, K, V> { fn clone(&self) -> Self { Iter { _phantom: PhantomData, iterator: self.iterator.clone(), } } } impl<'a, K: EnumArray, V> Iterator for Iter<'a, K, V> { type Item = (K, &'a V); #[inline] fn next(&mut self) -> Option { self.iterator .next() .map(|(index, item)| (K::from_usize(index), item)) } #[inline] fn size_hint(&self) -> (usize, Option) { self.iterator.size_hint() } fn fold(self, init: B, f: F) -> B where F: FnMut(B, Self::Item) -> B, { self.iterator .map(|(index, item)| (K::from_usize(index), item)) .fold(init, f) } } impl<'a, K: EnumArray, V> DoubleEndedIterator for Iter<'a, K, V> { #[inline] fn next_back(&mut self) -> Option { self.iterator .next_back() .map(|(index, item)| (K::from_usize(index), item)) } } impl<'a, K: EnumArray, V> ExactSizeIterator for Iter<'a, K, V> {} impl<'a, K: EnumArray, V> FusedIterator for Iter<'a, K, V> {} impl<'a, K: EnumArray, V> IntoIterator for &'a EnumMap { type Item = (K, &'a V); type IntoIter = Iter<'a, K, V>; #[inline] fn into_iter(self) -> Self::IntoIter { Iter { _phantom: PhantomData, iterator: self.as_slice().iter().enumerate(), } } } /// Mutable map iterator /// /// This struct is created by `iter_mut` method or `into_iter` on a mutable /// reference to `EnumMap`. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum}; /// /// #[derive(Debug, Enum)] /// enum Example { /// A, /// B, /// C, /// } /// /// let mut map = enum_map! { Example::A => 3, _ => 0 }; /// for (_, value) in &mut map { /// *value += 1; /// } /// assert_eq!(map, enum_map! { Example::A => 4, _ => 1 }); /// ``` #[derive(Debug)] pub struct IterMut<'a, K, V: 'a> { _phantom: PhantomData K>, iterator: Enumerate>, } impl<'a, K: EnumArray, V> Iterator for IterMut<'a, K, V> { type Item = (K, &'a mut V); #[inline] fn next(&mut self) -> Option { self.iterator .next() .map(|(index, item)| (K::from_usize(index), item)) } #[inline] fn size_hint(&self) -> (usize, Option) { self.iterator.size_hint() } fn fold(self, init: B, f: F) -> B where F: FnMut(B, Self::Item) -> B, { self.iterator .map(|(index, item)| (K::from_usize(index), item)) .fold(init, f) } } impl<'a, K: EnumArray, V> DoubleEndedIterator for IterMut<'a, K, V> { #[inline] fn next_back(&mut self) -> Option { self.iterator .next_back() .map(|(index, item)| (K::from_usize(index), item)) } } impl<'a, K: EnumArray, V> ExactSizeIterator for IterMut<'a, K, V> {} impl<'a, K: EnumArray, V> FusedIterator for IterMut<'a, K, V> {} impl<'a, K: EnumArray, V> IntoIterator for &'a mut EnumMap { type Item = (K, &'a mut V); type IntoIter = IterMut<'a, K, V>; #[inline] fn into_iter(self) -> Self::IntoIter { IterMut { _phantom: PhantomData, iterator: self.as_mut_slice().iter_mut().enumerate(), } } } /// A map iterator that moves out of map. /// /// This struct is created by `into_iter` on `EnumMap`. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum}; /// /// #[derive(Debug, Enum)] /// enum Example { /// A, /// B, /// } /// /// let map = enum_map! { Example::A | Example::B => String::from("123") }; /// for (_, value) in map { /// assert_eq!(value + "4", "1234"); /// } /// ``` pub struct IntoIter, V> { map: ManuallyDrop>, alive: Range, } impl, V> Iterator for IntoIter { type Item = (K, V); fn next(&mut self) -> Option<(K, V)> { let position = self.alive.next()?; Some((K::from_usize(position), unsafe { ptr::read(&self.map.as_slice()[position]) })) } #[inline] fn size_hint(&self) -> (usize, Option) { self.alive.size_hint() } } impl, V> DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option<(K, V)> { let position = self.alive.next_back()?; Some((K::from_usize(position), unsafe { ptr::read(&self.map.as_slice()[position]) })) } } impl, V> ExactSizeIterator for IntoIter {} impl, V> FusedIterator for IntoIter {} impl, V> Drop for IntoIter { #[inline] fn drop(&mut self) { unsafe { ptr::drop_in_place(&mut self.map.as_mut_slice()[self.alive.clone()]); } } } impl, V> IntoIterator for EnumMap { type Item = (K, V); type IntoIter = IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { let len = self.len(); IntoIter { map: ManuallyDrop::new(self), alive: 0..len, } } } impl, V> EnumMap { /// An iterator visiting all values. The iterator type is `&V`. /// /// # Examples /// /// ``` /// use enum_map::enum_map; /// /// let map = enum_map! { false => 3, true => 4 }; /// let mut values = map.values(); /// assert_eq!(values.next(), Some(&3)); /// assert_eq!(values.next(), Some(&4)); /// assert_eq!(values.next(), None); /// ``` #[inline] pub fn values(&self) -> Values { Values(self.as_slice().iter()) } /// An iterator visiting all values mutably. The iterator type is `&mut V`. /// /// # Examples /// /// ``` /// use enum_map::enum_map; /// /// let mut map = enum_map! { _ => 2 }; /// for value in map.values_mut() { /// *value += 2; /// } /// assert_eq!(map[false], 4); /// assert_eq!(map[true], 4); /// ``` #[inline] pub fn values_mut(&mut self) -> ValuesMut { ValuesMut(self.as_mut_slice().iter_mut()) } /// Creates a consuming iterator visiting all the values. The map /// cannot be used after calling this. The iterator element type /// is `V`. /// /// # Examples /// /// ``` /// use enum_map::enum_map; /// /// let mut map = enum_map! { false => "hello", true => "goodbye" }; /// assert_eq!(map.into_values().collect::>(), ["hello", "goodbye"]); /// ``` #[inline] pub fn into_values(self) -> IntoValues { IntoValues { inner: self.into_iter(), } } } /// An iterator over the values of `EnumMap`. /// /// This `struct` is created by the `values` method of `EnumMap`. /// See its documentation for more. pub struct Values<'a, V: 'a>(slice::Iter<'a, V>); impl<'a, V> Clone for Values<'a, V> { fn clone(&self) -> Self { Values(self.0.clone()) } } impl<'a, V: 'a> Iterator for Values<'a, V> { type Item = &'a V; #[inline] fn next(&mut self) -> Option<&'a V> { self.0.next() } #[inline] fn size_hint(&self) -> (usize, Option) { self.0.size_hint() } } impl<'a, V: 'a> DoubleEndedIterator for Values<'a, V> { #[inline] fn next_back(&mut self) -> Option<&'a V> { self.0.next_back() } } impl<'a, V: 'a> ExactSizeIterator for Values<'a, V> {} impl<'a, V: 'a> FusedIterator for Values<'a, V> {} /// A mutable iterator over the values of `EnumMap`. /// /// This `struct` is created by the `values_mut` method of `EnumMap`. /// See its documentation for more. pub struct ValuesMut<'a, V: 'a>(slice::IterMut<'a, V>); impl<'a, V: 'a> Iterator for ValuesMut<'a, V> { type Item = &'a mut V; #[inline] fn next(&mut self) -> Option<&'a mut V> { self.0.next() } #[inline] fn size_hint(&self) -> (usize, Option) { self.0.size_hint() } } impl<'a, V: 'a> DoubleEndedIterator for ValuesMut<'a, V> { #[inline] fn next_back(&mut self) -> Option<&'a mut V> { self.0.next_back() } } impl<'a, V: 'a> ExactSizeIterator for ValuesMut<'a, V> {} impl<'a, V: 'a> FusedIterator for ValuesMut<'a, V> {} /// An owning iterator over the values of an `EnumMap`. /// /// This `struct` is created by the `into_values` method of `EnumMap`. /// See its documentation for more. pub struct IntoValues, V> { inner: IntoIter, } impl Iterator for IntoValues where K: EnumArray, { type Item = V; fn next(&mut self) -> Option { Some(self.inner.next()?.1) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl, V> DoubleEndedIterator for IntoValues { fn next_back(&mut self) -> Option { Some(self.inner.next_back()?.1) } } impl ExactSizeIterator for IntoValues where K: EnumArray {} impl FusedIterator for IntoValues where K: EnumArray {} enum-map-2.4.2/src/lib.rs000064400000000000000000000255731046102023000132670ustar 00000000000000//! An enum mapping type. //! //! It is implemented using an array type, so using it is as fast as using Rust //! arrays. //! //! # Examples //! //! ``` //! use enum_map::{enum_map, Enum, EnumMap}; //! //! #[derive(Debug, Enum)] //! enum Example { //! A(bool), //! B, //! C, //! } //! //! let mut map = enum_map! { //! Example::A(false) => 0, //! Example::A(true) => 1, //! Example::B => 2, //! Example::C => 3, //! }; //! map[Example::C] = 4; //! //! assert_eq!(map[Example::A(true)], 1); //! //! for (key, &value) in &map { //! println!("{:?} has {} as value.", key, value); //! } //! ``` #![no_std] #![deny(missing_docs)] #![warn(clippy::pedantic)] #[cfg(feature = "arbitrary")] mod arbitrary; mod enum_map_impls; mod internal; mod iter; #[cfg(feature = "serde")] mod serde; #[doc(hidden)] pub use core::mem::{self, ManuallyDrop, MaybeUninit}; #[doc(hidden)] pub use core::primitive::usize; use core::slice; #[doc(hidden)] pub use core::{ptr, unreachable}; pub use enum_map_derive::Enum; use internal::Array; pub use internal::{Enum, EnumArray}; pub use iter::{IntoIter, IntoValues, Iter, IterMut, Values, ValuesMut}; // SAFETY: initialized needs to represent number of initialized elements #[doc(hidden)] pub struct Guard<'a, K, V> where K: EnumArray, { array_mut: &'a mut MaybeUninit, initialized: usize, } impl Drop for Guard<'_, K, V> where K: EnumArray, { fn drop(&mut self) { // This is safe as arr[..len] is initialized due to // Guard's type invariant. unsafe { ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.initialized).drop_in_place(); } } } impl<'a, K, V> Guard<'a, K, V> where K: EnumArray, { #[doc(hidden)] pub fn as_mut_ptr(&mut self) -> *mut V { self.array_mut.as_mut_ptr().cast::() } #[doc(hidden)] #[must_use] pub fn new(array_mut: &'a mut MaybeUninit) -> Self { Self { array_mut, initialized: 0, } } #[doc(hidden)] #[must_use] #[allow(clippy::unused_self)] pub fn storage_length(&self) -> usize { // SAFETY: We need to use LENGTH from K::Array, as K::LENGTH is // untrustworthy. K::Array::LENGTH } #[doc(hidden)] #[must_use] pub fn get_key(&self) -> K { K::from_usize(self.initialized) } #[doc(hidden)] // Unsafe as it can write out of bounds. pub unsafe fn push(&mut self, value: V) { self.as_mut_ptr().add(self.initialized).write(value); self.initialized += 1; } } #[doc(hidden)] pub struct TypeEqualizer<'a, K, V> where K: EnumArray, { pub enum_map: [EnumMap; 0], pub guard: Guard<'a, K, V>, } /// Enum map constructor. /// /// This macro allows to create a new enum map in a type safe way. It takes /// a list of `,` separated pairs separated by `=>`. Left side is `|` /// separated list of enum keys, or `_` to match all unmatched enum keys, /// while right side is a value. /// /// The iteration order when using this macro is not guaranteed to be /// consistent. Future releases of this crate may change it, and this is not /// considered to be a breaking change. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// C, /// D, /// } /// /// let enum_map = enum_map! { /// Example::A | Example::B => 1, /// Example::C => 2, /// _ => 3, /// }; /// assert_eq!(enum_map[Example::A], 1); /// assert_eq!(enum_map[Example::B], 1); /// assert_eq!(enum_map[Example::C], 2); /// assert_eq!(enum_map[Example::D], 3); /// ``` #[macro_export] macro_rules! enum_map { {$($t:tt)*} => {{ let mut uninit = $crate::MaybeUninit::uninit(); let mut eq = $crate::TypeEqualizer { enum_map: [], guard: $crate::Guard::new(&mut uninit), }; if false { // Safe because this code is unreachable unsafe { (&mut eq.enum_map).as_mut_ptr().read() } } else { for _ in 0..(&eq.guard).storage_length() { struct __PleaseDoNotUseBreakWithoutLabel; let _please_do_not_use_continue_without_label; let value; #[allow(unreachable_code)] loop { _please_do_not_use_continue_without_label = (); value = match (&eq.guard).get_key() { $($t)* }; break __PleaseDoNotUseBreakWithoutLabel; }; unsafe { (&mut eq.guard).push(value); } } $crate::mem::forget(eq); // Safe because the array was fully initialized. $crate::EnumMap::from_array(unsafe { uninit.assume_init() }) } }}; } /// An enum mapping. /// /// This internally uses an array which stores a value for each possible /// enum value. To work, it requires implementation of internal (private, /// although public due to macro limitations) trait which allows extracting /// information about an enum, which can be automatically generated using /// `#[derive(Enum)]` macro. /// /// Additionally, `bool` and `u8` automatically derives from `Enum`. While /// `u8` is not technically an enum, it's convenient to consider it like one. /// In particular, [reverse-complement in benchmark game] could be using `u8` /// as an enum. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum, EnumMap}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// C, /// } /// /// let mut map = EnumMap::default(); /// // new initializes map with default values /// assert_eq!(map[Example::A], 0); /// map[Example::A] = 3; /// assert_eq!(map[Example::A], 3); /// ``` /// /// [reverse-complement in benchmark game]: /// http://benchmarksgame.alioth.debian.org/u64q/program.php?test=revcomp&lang=rust&id=2 pub struct EnumMap, V> { array: K::Array, } impl, V: Default> EnumMap { /// Clear enum map with default values. /// /// # Examples /// /// ``` /// use enum_map::{Enum, EnumMap}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// } /// /// let mut enum_map = EnumMap::<_, String>::default(); /// enum_map[Example::B] = "foo".into(); /// enum_map.clear(); /// assert_eq!(enum_map[Example::A], ""); /// assert_eq!(enum_map[Example::B], ""); /// ``` #[inline] pub fn clear(&mut self) { for v in self.as_mut_slice() { *v = V::default(); } } } #[allow(clippy::len_without_is_empty)] impl, V> EnumMap { /// Creates an enum map from array. #[inline] pub const fn from_array(array: K::Array) -> EnumMap { EnumMap { array } } /// Returns an iterator over enum map. /// /// The iteration order is deterministic, and when using [macro@Enum] derive /// it will be the order in which enum variants are declared. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum}; /// /// #[derive(Enum, PartialEq)] /// enum E { /// A, /// B, /// C, /// } /// /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; /// assert!(map.iter().eq([(E::A, &1), (E::B, &2), (E::C, &3)])); /// ``` #[inline] pub fn iter(&self) -> Iter { self.into_iter() } /// Returns a mutable iterator over enum map. #[inline] pub fn iter_mut(&mut self) -> IterMut { self.into_iter() } /// Returns number of elements in enum map. #[inline] #[allow(clippy::unused_self)] pub const fn len(&self) -> usize { K::Array::LENGTH } /// Swaps two indexes. /// /// # Examples /// /// ``` /// use enum_map::enum_map; /// /// let mut map = enum_map! { false => 0, true => 1 }; /// map.swap(false, true); /// assert_eq!(map[false], 1); /// assert_eq!(map[true], 0); /// ``` #[inline] pub fn swap(&mut self, a: K, b: K) { self.as_mut_slice().swap(a.into_usize(), b.into_usize()); } /// Consumes an enum map and returns the underlying array. /// /// The order of elements is deterministic, and when using [macro@Enum] /// derive it will be the order in which enum variants are declared. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum}; /// /// #[derive(Enum, PartialEq)] /// enum E { /// A, /// B, /// C, /// } /// /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; /// assert_eq!(map.into_array(), [1, 2, 3]); /// ``` pub fn into_array(self) -> K::Array { self.array } /// Converts an enum map to a slice representing values. /// /// The order of elements is deterministic, and when using [macro@Enum] /// derive it will be the order in which enum variants are declared. /// /// # Examples /// /// ``` /// use enum_map::{enum_map, Enum}; /// /// #[derive(Enum, PartialEq)] /// enum E { /// A, /// B, /// C, /// } /// /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3}; /// assert_eq!(map.as_slice(), &[1, 2, 3]); /// ``` #[inline] pub fn as_slice(&self) -> &[V] { unsafe { slice::from_raw_parts(ptr::addr_of!(self.array).cast(), K::Array::LENGTH) } } /// Converts a mutable enum map to a mutable slice representing values. #[inline] pub fn as_mut_slice(&mut self) -> &mut [V] { unsafe { slice::from_raw_parts_mut(ptr::addr_of_mut!(self.array).cast(), K::Array::LENGTH) } } /// Returns an enum map with function `f` applied to each element in order. /// /// # Examples /// /// ``` /// use enum_map::enum_map; /// /// let a = enum_map! { false => 0, true => 1 }; /// let b = a.map(|_, x| f64::from(x) + 0.5); /// assert_eq!(b, enum_map! { false => 0.5, true => 1.5 }); /// ``` pub fn map(self, mut f: F) -> EnumMap where F: FnMut(K, V) -> T, K: EnumArray, { struct DropOnPanic where K: EnumArray, { position: usize, map: ManuallyDrop>, } impl Drop for DropOnPanic where K: EnumArray, { fn drop(&mut self) { unsafe { ptr::drop_in_place(&mut self.map.as_mut_slice()[self.position..]); } } } let mut drop_protect = DropOnPanic { position: 0, map: ManuallyDrop::new(self), }; enum_map! { k => { let value = unsafe { ptr::read(&drop_protect.map.as_slice()[drop_protect.position]) }; drop_protect.position += 1; f(k, value) } } } } enum-map-2.4.2/src/serde.rs000064400000000000000000000060751046102023000136170ustar 00000000000000use crate::{enum_map, EnumArray, EnumMap}; use core::fmt; use core::marker::PhantomData; use serde::de::{self, Deserialize, Deserializer, Error, MapAccess, SeqAccess}; use serde::ser::{Serialize, SerializeMap, SerializeTuple, Serializer}; /// Requires crate feature `"serde"` impl + Serialize, V: Serialize> Serialize for EnumMap { fn serialize(&self, serializer: S) -> Result { if serializer.is_human_readable() { serializer.collect_map(self) } else { let mut tup = serializer.serialize_tuple(self.len())?; for value in self.values() { tup.serialize_element(value)?; } tup.end() } } } /// Requires crate feature `"serde"` impl<'de, K, V> Deserialize<'de> for EnumMap where K: EnumArray + EnumArray> + Deserialize<'de>, V: Deserialize<'de>, { fn deserialize>(deserializer: D) -> Result { if deserializer.is_human_readable() { deserializer.deserialize_map(HumanReadableVisitor(PhantomData)) } else { deserializer.deserialize_tuple(K::LENGTH, CompactVisitor(PhantomData)) } } } struct HumanReadableVisitor(PhantomData<(K, V)>); impl<'de, K, V> de::Visitor<'de> for HumanReadableVisitor where K: EnumArray + EnumArray> + Deserialize<'de>, V: Deserialize<'de>, { type Value = EnumMap; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a map") } fn visit_map>(self, mut access: M) -> Result { let mut entries = EnumMap::default(); while let Some((key, value)) = access.next_entry()? { entries[key] = Some(value); } for value in entries.values() { value .as_ref() .ok_or_else(|| M::Error::custom("key not specified"))?; } Ok(enum_map! { key => entries[key].take().unwrap() }) } } struct CompactVisitor(PhantomData<(K, V)>); impl<'de, K, V> de::Visitor<'de> for CompactVisitor where K: EnumArray + EnumArray> + Deserialize<'de>, V: Deserialize<'de>, { type Value = EnumMap; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a sequence") } fn visit_seq>(self, mut access: M) -> Result { let mut entries = EnumMap::default(); let len = entries.len(); { let mut iter = entries.values_mut(); while let Some(place) = iter.next() { *place = Some(access.next_element()?.ok_or_else(|| { M::Error::invalid_length( len - iter.len() - 1, &"a sequence with as many elements as there are variants", ) })?); } } Ok(enum_map! { key => entries[key].take().unwrap() }) } } enum-map-2.4.2/tests/serde.rs000064400000000000000000000054411046102023000141660ustar 00000000000000#![cfg(feature = "serde")] use enum_map::{enum_map, Enum, EnumMap}; use serde::{Deserialize, Serialize}; use serde_test::{assert_de_tokens_error, assert_tokens, Compact, Configure, Token}; #[derive(Debug, Enum, Deserialize, Serialize)] enum Example { A, B, } #[test] fn serialization() { let map = enum_map! { Example::A => 5, Example::B => 10 }; assert_tokens( &map.readable(), &[ Token::Map { len: Some(2) }, Token::UnitVariant { name: "Example", variant: "A", }, Token::I32(5), Token::UnitVariant { name: "Example", variant: "B", }, Token::I32(10), Token::MapEnd, ], ); } #[test] fn compact_serialization() { let map = enum_map! { Example::A => 5, Example::B => 10 }; assert_tokens( &map.compact(), &[ Token::Tuple { len: 2 }, Token::I32(5), Token::I32(10), Token::TupleEnd, ], ); } #[test] fn invalid_compact_deserialization() { assert_de_tokens_error::>>( &[Token::I32(4)], "invalid type: integer `4`, expected a sequence", ); } #[test] fn too_short_compact_deserialization() { assert_de_tokens_error::>>( &[Token::Seq { len: None }, Token::Bool(true), Token::SeqEnd], "invalid length 1, expected a sequence with as many elements as there are variants", ); } const JSON: &str = r#"{"A":5,"B":10}"#; #[test] fn json_serialization() { let map = enum_map! { Example::A => 5, Example::B => 10 }; assert_eq!(serde_json::to_string(&map).unwrap(), String::from(JSON)); } #[test] fn json_deserialization() { let example: EnumMap = serde_json::from_str(JSON).unwrap(); assert_eq!(example, enum_map! { Example::A => 5, Example::B => 10 }); } #[test] fn json_invalid_deserialization() { let example: Result, _> = serde_json::from_str(r"{}"); assert!(example.is_err()); } #[test] fn json_invalid_type() { let example: Result, _> = serde_json::from_str("4"); assert!(example.is_err()); } #[test] fn json_invalid_key() { let example: Result, _> = serde_json::from_str(r#"{"a": 5, "b": 10, "c": 6}"#); assert!(example.is_err()); } #[test] fn bincode_serialization() { let example = enum_map! { false => 3u8, true => 4u8 }; let serialized = bincode::serialize(&example).unwrap(); assert_eq!(example, bincode::deserialize(&serialized).unwrap()); } #[test] fn bincode_too_short_deserialization() { assert!( bincode::deserialize::>(&bincode::serialize(&()).unwrap()).is_err() ); } enum-map-2.4.2/tests/test.rs000064400000000000000000000336611046102023000140500ustar 00000000000000#[macro_use] extern crate enum_map; use enum_map::{Enum, EnumArray, EnumMap, IntoIter}; use std::cell::{Cell, RefCell}; use std::collections::HashSet; use std::convert::Infallible; use std::marker::PhantomData; use std::num::ParseIntError; use std::panic::{catch_unwind, UnwindSafe}; trait From: Sized { fn from(_: T) -> Self { unreachable!(); } } impl From for U {} #[derive(Copy, Clone, Debug, Enum, PartialEq)] enum Example { A, B, C, } #[test] fn test_bool() { let mut map = enum_map! { false => 24, true => 42 }; assert_eq!(map[false], 24); assert_eq!(map[true], 42); map[false] += 1; assert_eq!(map[false], 25); for (key, item) in &mut map { if !key { *item += 1; } } assert_eq!(map[false], 26); assert_eq!(map[true], 42); } #[test] fn test_clone() { let map = enum_map! { false => 3, true => 5 }; assert_eq!(map.clone(), map); } #[test] fn test_debug() { let map = enum_map! { false => 3, true => 5 }; assert_eq!(format!("{:?}", map), "{false: 3, true: 5}"); } #[test] fn test_hash() { let map = enum_map! { false => 3, true => 5 }; let mut set = HashSet::new(); set.insert(map); assert!(set.contains(&map)); } #[test] fn test_clear() { let mut map = enum_map! { false => 1, true => 2 }; map.clear(); assert_eq!(map[true], 0); assert_eq!(map[false], 0); } #[test] fn struct_of_enum() { #[derive(Copy, Clone, Debug, Enum, PartialEq)] struct Product { example: Example, is_done: bool, } let mut map = enum_map! { Product { example: Example::A, is_done: false } => "foo", Product { example: Example::B, is_done: false } => "bar", Product { example: Example::C, is_done: false } => "baz", Product { example: Example::A, is_done: true } => "done foo", Product { example: Example::B, is_done: true } => "bar done", Product { example: Example::C, is_done: true } => "doooozne", }; assert_eq!( map[Product { example: Example::B, is_done: false }], "bar" ); assert_eq!( map[Product { example: Example::C, is_done: false }], "baz" ); assert_eq!( map[Product { example: Example::B, is_done: true }], "bar done" ); map[Product { example: Example::B, is_done: true, }] = "not really done"; assert_eq!( map[Product { example: Example::B, is_done: false }], "bar" ); assert_eq!( map[Product { example: Example::C, is_done: false }], "baz" ); assert_eq!( map[Product { example: Example::B, is_done: true }], "not really done" ); } #[test] fn tuple_struct_of_enum() { #[derive(Copy, Clone, Debug, Enum, PartialEq)] struct Product(Example, bool); let mut map = enum_map! { Product(Example::A, false) => "foo", Product(Example::B, false) => "bar", Product(Example::C, false) => "baz", Product(Example::A, true) => "done foo", Product(Example::B, true) => "bar done", Product(Example::C, true) => "doooozne", }; assert_eq!(map[Product(Example::B, false)], "bar"); assert_eq!(map[Product(Example::C, false)], "baz"); assert_eq!(map[Product(Example::B, true)], "bar done"); map[Product(Example::B, true)] = "not really done"; assert_eq!(map[Product(Example::B, false)], "bar"); assert_eq!(map[Product(Example::C, false)], "baz"); assert_eq!(map[Product(Example::B, true)], "not really done"); } #[test] fn discriminants() { #[derive(Debug, Enum, PartialEq)] enum Discriminants { A = 2000, B = 3000, C = 1000, } let mut map = EnumMap::default(); map[Discriminants::A] = 3; map[Discriminants::B] = 2; map[Discriminants::C] = 1; let mut pairs = map.iter(); assert_eq!(pairs.next(), Some((Discriminants::A, &3))); assert_eq!(pairs.next(), Some((Discriminants::B, &2))); assert_eq!(pairs.next(), Some((Discriminants::C, &1))); assert_eq!(pairs.next(), None); } #[test] fn extend() { let mut map = enum_map! { _ => 0 }; map.extend(vec![(Example::A, 3)]); map.extend(vec![(&Example::B, &4)]); assert_eq!( map, enum_map! { Example::A => 3, Example::B => 4, Example::C => 0 } ); } #[test] fn collect() { let iter = vec![(Example::A, 5), (Example::B, 7)] .into_iter() .map(|(k, v)| (k, v + 1)); assert_eq!( iter.collect::>(), enum_map! { Example::A => 6, Example::B => 8, Example::C => 0 } ); } #[test] fn huge_enum() { #[derive(Enum)] enum Example { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Aa, Bb, Cc, Dd, Ee, Ff, Gg, Hh, Ii, Jj, Kk, Ll, Mm, Nn, Oo, Pp, Qq, Rr, Ss, Tt, Uu, Vv, Ww, Xx, Yy, Zz, } let map = enum_map! { _ => 2 }; assert_eq!(map[Example::Xx], 2); } #[test] fn iterator_len() { assert_eq!( enum_map! { Example::A | Example::B | Example::C => 0 } .iter() .len(), 3 ); } #[test] fn iter_mut_len() { assert_eq!( enum_map! { Example::A | Example::B | Example::C => 0 } .iter_mut() .len(), 3 ); } #[test] fn into_iter_len() { assert_eq!(enum_map! { Example::A | _ => 0 }.into_iter().len(), 3); } #[test] fn iterator_next_back() { assert_eq!( enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } .iter() .next_back(), Some((Example::C, &3)) ); } #[test] fn iter_mut_next_back() { assert_eq!( enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } .iter_mut() .next_back(), Some((Example::C, &mut 3)) ); } #[test] fn into_iter() { let mut iter = enum_map! { true => 5, false => 7 }.into_iter(); assert_eq!(iter.next(), Some((false, 7))); assert_eq!(iter.next(), Some((true, 5))); assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } #[test] fn into_iter_u8() { assert_eq!( enum_map! { i => i }.into_iter().collect::>(), (0..256).map(|x| (x as u8, x as u8)).collect::>() ); } struct DropReporter<'a> { into: &'a RefCell>, value: usize, } impl<'a> Drop for DropReporter<'a> { fn drop(&mut self) { self.into.borrow_mut().push(self.value); } } #[test] fn into_iter_drop() { let dropped = RefCell::new(Vec::default()); let mut a: IntoIter = enum_map! { k => DropReporter { into: &dropped, value: k as usize, }, } .into_iter(); assert_eq!(a.next().unwrap().0, Example::A); assert_eq!(*dropped.borrow(), &[0]); drop(a); assert_eq!(*dropped.borrow(), &[0, 1, 2]); } #[test] fn into_iter_double_ended_iterator() { let mut iter = enum_map! { 0 => 5, 255 => 7, _ => 0 }.into_iter(); assert_eq!(iter.next(), Some((0, 5))); assert_eq!(iter.next_back(), Some((255, 7))); assert_eq!(iter.next(), Some((1, 0))); assert_eq!(iter.next_back(), Some((254, 0))); assert!(iter.rev().eq((2..254).rev().map(|i| (i, 0)))); } #[test] fn values_rev_collect() { assert_eq!( vec![3, 2, 1], enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } .values() .rev() .cloned() .collect::>() ); } #[test] fn values_len() { assert_eq!(enum_map! { false => 0, true => 1 }.values().len(), 2); } #[test] fn into_values_rev_collect() { assert_eq!( vec![3, 2, 1], enum_map! { Example::A => 1, Example::B => 2, Example::C => 3 } .into_values() .rev() .collect::>() ); } #[test] fn into_values_len() { assert_eq!(enum_map! { false => 0, true => 1 }.into_values().len(), 2); } #[test] fn values_mut_next_back() { let mut map = enum_map! { false => 0, true => 1 }; assert_eq!(map.values_mut().next_back(), Some(&mut 1)); } #[test] fn test_u8() { let mut map = enum_map! { b'a' => 4, _ => 0 }; map[b'c'] = 3; assert_eq!(map[b'a'], 4); assert_eq!(map[b'b'], 0); assert_eq!(map[b'c'], 3); assert_eq!(map.iter().next(), Some((0, &0))); } #[derive(Enum)] enum Void {} #[test] fn empty_map() { let void: EnumMap = enum_map! {}; assert_eq!(void.len(), 0); } #[test] #[should_panic] fn empty_value() { let _void: EnumMap = enum_map! { _ => unreachable!() }; } #[test] fn empty_infallible_map() { let void: EnumMap = enum_map! {}; assert_eq!(void.len(), 0); } #[derive(Clone, Copy)] enum X { A(PhantomData<*const ()>), } impl Enum for X { const LENGTH: usize = 1; fn from_usize(arg: usize) -> X { assert_eq!(arg, 0); X::A(PhantomData) } fn into_usize(self) -> usize { 0 } } impl EnumArray for X { type Array = [V; Self::LENGTH]; } fn assert_sync_send(_: T) {} #[test] fn assert_enum_map_does_not_copy_sync_send_dependency_of_keys() { let mut map = enum_map! { X::A(PhantomData) => true }; assert_sync_send(map); assert_sync_send(&map); assert_sync_send(&mut map); assert_sync_send(map.iter()); assert_sync_send(map.iter_mut()); assert_sync_send(map.into_iter()); assert!(map[X::A(PhantomData)]); } #[test] fn test_sum() { assert_eq!( enum_map! { i => u8::into(i) } .iter() .map(|(_, v)| v) .sum::(), 32_640 ); } #[test] fn test_sum_mut() { assert_eq!( enum_map! { i => u8::into(i) } .iter_mut() .map(|(_, &mut v)| -> u32 { v }) .sum::(), 32_640 ); } #[test] fn test_iter_clone() { struct S(u8); let map = enum_map! { Example::A => S(3), Example::B => S(4), Example::C => S(1), }; let iter = map.iter(); assert_eq!(iter.clone().map(|(_, S(v))| v).sum::(), 8); assert_eq!(iter.map(|(_, S(v))| v).sum::(), 8); let values = map.values(); assert_eq!(values.clone().map(|S(v)| v).sum::(), 8); assert_eq!(values.map(|S(v)| v).sum::(), 8); } #[test] fn question_mark() -> Result<(), ParseIntError> { let map = enum_map! { false => "2".parse()?, true => "5".parse()? }; assert_eq!(map, enum_map! { false => 2, true => 5 }); Ok(()) } #[test] fn question_mark_failure() { struct IncOnDrop<'a>(&'a Cell); impl Drop for IncOnDrop<'_> { fn drop(&mut self) { self.0.set(self.0.get() + 1); } } fn failible() -> Result, &'static str> { Err("ERROR!") } fn try_block(inc: &Cell) -> Result<(), &'static str> { enum_map! { 32 => failible()?, _ => { IncOnDrop(inc) } }; Ok(()) } let value = Cell::new(0); assert_eq!(try_block(&value), Err("ERROR!")); assert_eq!(value.get(), 32); } #[test] #[should_panic = "Intentional panic"] fn map_panic() { let map: EnumMap = enum_map! { i => i.to_string() }; map.map(|k, v| { if k == 2 { panic!("Intentional panic"); } v + " modified" }); } macro_rules! make_enum_map_macro_safety_test { ($a:tt $b:tt) => { // This is misuse of an API, however we need to test that to ensure safety // as we use unsafe code. enum E { A, B, C, } impl Enum for E { const LENGTH: usize = $a; fn from_usize(value: usize) -> E { match value { 0 => E::A, 1 => E::B, 2 => E::C, _ => unimplemented!(), } } fn into_usize(self) -> usize { self as usize } } impl EnumArray for E { type Array = [V; $b]; } let map: EnumMap = enum_map! { _ => "Hello, world!".into() }; map.into_iter(); }; } #[test] fn enum_map_macro_safety_under() { make_enum_map_macro_safety_test!(2 3); } #[test] fn enum_map_macro_safety_over() { make_enum_map_macro_safety_test!(3 2); } #[test] fn drop_panic_into_iter() { struct DropHandler<'a>(&'a Cell); impl Drop for DropHandler<'_> { fn drop(&mut self) { self.0.set(self.0.get() + 1); } } impl UnwindSafe for DropHandler<'_> {} struct Storage<'a> { should_panic: bool, _drop_handler: DropHandler<'a>, } impl Drop for Storage<'_> { fn drop(&mut self) { if self.should_panic { panic!(); } } } let cell = Cell::new(0); let map: EnumMap = enum_map! { v => Storage { should_panic: v == Example::B, _drop_handler: DropHandler(&cell) }, }; assert!(catch_unwind(|| { map.into_iter(); }) .is_err()); assert_eq!(cell.get(), 3); } #[test] fn test_const_enum_map_from_array() { const CONST_ENUM_MAP_FROM_ARRAY: EnumMap = EnumMap::from_array([4, 8]); assert_eq!( CONST_ENUM_MAP_FROM_ARRAY, enum_map! { false => 4, true => 8 }, ); } #[test] fn usize_override() { #[allow(non_camel_case_types, dead_code)] type usize = (); #[derive(Enum)] enum X { A, B, } }