enum-map-0.6.2/Cargo.toml.orig010064400017500000144000000015551357710237100143560ustar0000000000000000[package] name = "enum-map" version = "0.6.2" authors = ["Konrad Borowski "] edition = "2018" repository = "https://gitlab.com/KonradBorowski/enum-map" license = "MIT/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] gitlab = { repository = "KonradBorowski/enum-map" } maintenance = { status = "actively-developed" } [dependencies] array-macro = "1.0.4" enum-map-derive = { version = "0.4.0", path = "../enum-map-derive" } serde = { version = "1.0.16", optional = true, default-features = false } [dev-dependencies] bincode = "1.0.0" serde_derive = "1.0.0" serde_test = "1.0.19" serde_json = "1.0.2" [package.metadata.docs.rs] features = ["serde"] enum-map-0.6.2/Cargo.toml0000644000000027150000000000000106220ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "enum-map" version = "0.6.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/Apache-2.0" repository = "https://gitlab.com/KonradBorowski/enum-map" [package.metadata.docs.rs] features = ["serde"] [dependencies.array-macro] version = "1.0.4" [dependencies.enum-map-derive] version = "0.4.0" [dependencies.serde] version = "1.0.16" optional = true default-features = false [dev-dependencies.bincode] version = "1.0.0" [dev-dependencies.serde_derive] version = "1.0.0" [dev-dependencies.serde_json] version = "1.0.2" [dev-dependencies.serde_test] version = "1.0.19" [badges.gitlab] repository = "KonradBorowski/enum-map" [badges.maintenance] status = "actively-developed" enum-map-0.6.2/README.md010064400017500000144000000013201357710235300127340ustar0000000000000000# 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. If you are using Rust 1.35 or older, you may want to use enum-map 0.5 instead, as enum-map 0.6 requires Rust 1.36. ## 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-0.6.2/src/enum_map_impls.rs010064400017500000144000000040241357710235300156230ustar0000000000000000use crate::{enum_map, Enum, EnumMap}; use core::fmt::{self, Debug, Formatter}; use core::hash::{Hash, Hasher}; use core::iter::Extend; 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: Enum + Copy, V: Copy, { fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); } } impl, V> Index for EnumMap { type Output = V; #[inline] fn index(&self, key: K) -> &V { &self.as_slice()[key.to_usize()] } } impl, V> IndexMut for EnumMap { #[inline] fn index_mut(&mut self, key: K) -> &mut V { &mut self.as_mut_slice()[key.to_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-0.6.2/src/internal.rs010064400017500000144000000046511357710235300144400ustar0000000000000000use array_macro::array; /// Enum mapping type /// /// This trait is internally used by `#[derive(Enum)]`. `Enum` is /// implemented by any enum type where V is a generic type representing a /// value. The purpose of this generic type is to allow providing a value /// type for arrays, as Rust currently does not support higher kinded types. /// /// 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 { /// Representation of an enum map for type `V`, usually an array. type Array; /// Number of possible states the type can have. const POSSIBLE_VALUES: usize; /// Gets a slice from an array type. fn slice(array: &Self::Array) -> &[V]; /// Gets a mutable slice from an array type. fn slice_mut(array: &mut Self::Array) -> &mut [V]; /// Takes an usize, and returns an element matching `to_usize` function. fn from_usize(value: usize) -> Self; /// Returns an unique identifier for a value within range of `0..POSSIBLE_VALUES`. fn to_usize(self) -> usize; /// Creates an array using a function called for each argument. fn from_function V>(f: F) -> Self::Array; } impl Enum for bool { type Array = [T; 2]; const POSSIBLE_VALUES: usize = 2; #[inline] fn slice(array: &[T; 2]) -> &[T] { array } #[inline] fn slice_mut(array: &mut [T; 2]) -> &mut [T] { array } #[inline] fn from_usize(value: usize) -> Self { match value { 0 => false, 1 => true, _ => unreachable!(), } } #[inline] fn to_usize(self) -> usize { self as usize } #[inline] fn from_function T>(mut f: F) -> [T; 2] { [f(false), f(true)] } } impl Enum for u8 { type Array = [T; 256]; const POSSIBLE_VALUES: usize = 256; #[inline] fn slice(array: &[T; 256]) -> &[T] { array } #[inline] fn slice_mut(array: &mut [T; 256]) -> &mut [T] { array } #[inline] fn from_usize(value: usize) -> Self { value as u8 } #[inline] fn to_usize(self) -> usize { self as usize } #[inline] fn from_function T>(mut f: F) -> [T; 256] { array![|i| f(i as u8); 256] } } enum-map-0.6.2/src/iter.rs010064400017500000144000000205441357710235300135660ustar0000000000000000use crate::{Enum, EnumMap}; use core::iter::{Enumerate, FusedIterator}; use core::marker::PhantomData; use core::mem::ManuallyDrop; 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 /// /// ``` /// # extern crate enum_map; /// use enum_map::{enum_map, Enum}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// C, /// } /// /// fn main() { /// 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: Enum, 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: Enum, 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: Enum, V> ExactSizeIterator for Iter<'a, K, V> {} impl<'a, K: Enum, V> FusedIterator for Iter<'a, K, V> {} impl<'a, K: Enum, 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 /// /// ``` /// # extern crate enum_map; /// use enum_map::{enum_map, Enum}; /// /// #[derive(Debug, Enum)] /// enum Example { /// A, /// B, /// C, /// } /// /// fn main() { /// 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: Enum, 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: Enum, 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: Enum, V> ExactSizeIterator for IterMut<'a, K, V> {} impl<'a, K: Enum, V> FusedIterator for IterMut<'a, K, V> {} impl<'a, K: Enum, 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 /// /// ``` /// # extern crate enum_map; /// use enum_map::{enum_map, Enum}; /// /// #[derive(Debug, Enum)] /// enum Example { /// A, /// B, /// } /// /// fn main() { /// 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>, position: usize, } impl, V> Iterator for IntoIter { type Item = (K, V); fn next(&mut self) -> Option<(K, V)> { let slice = self.map.as_slice(); if self.position < slice.len() { let key = K::from_usize(self.position); let result = Some((key, unsafe { ptr::read(&slice[self.position]) })); self.position += 1; result } else { None } } #[inline] fn size_hint(&self) -> (usize, Option) { let slice = self.map.as_slice(); let diff = slice.len() - self.position; (diff, Some(diff)) } } impl, V> ExactSizeIterator for IntoIter {} impl, V> FusedIterator for IntoIter {} impl, V> Drop for IntoIter { #[inline] fn drop(&mut self) { for _item in self {} } } impl, V> IntoIterator for EnumMap { type Item = (K, V); type IntoIter = IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { IntoIter { map: ManuallyDrop::new(self), position: 0, } } } impl, V> EnumMap { /// An iterator visiting all values. The iterator type is `&V`. /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::enum_map; /// /// fn main() { /// 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 /// /// ``` /// # extern crate enum_map; /// use enum_map::enum_map; /// /// fn main() { /// 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()) } } /// 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: '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> {} enum-map-0.6.2/src/lib.rs010064400017500000144000000173261357710235300133750ustar0000000000000000//! 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, //! 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); //! } //! } //! ``` #![no_std] #![deny(missing_docs)] mod enum_map_impls; mod internal; mod iter; mod serde; pub use enum_map_derive::Enum; pub use internal::Enum; pub use iter::{IntoIter, Iter, IterMut, Values, ValuesMut}; /// 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. /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::{enum_map, Enum}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// C, /// D, /// } /// /// fn main() { /// 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)*} => { $crate::__from_fn(|k| match k { $($t)* }) }; } /// 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 /// /// ``` /// # extern crate enum_map; /// use enum_map::{enum_map, Enum, EnumMap}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// C, /// } /// /// fn main() { /// let mut map = EnumMap::new(); /// // 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 { /// Creates an enum map with default values. /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::{Enum, EnumMap}; /// /// #[derive(Enum)] /// enum Example { /// A, /// } /// /// fn main() { /// let enum_map = EnumMap::<_, i32>::new(); /// assert_eq!(enum_map[Example::A], 0); /// } /// ``` #[inline] pub fn new() -> Self { EnumMap::default() } /// Clear enum map with default values. /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::{Enum, EnumMap}; /// /// #[derive(Enum)] /// enum Example { /// A, /// B, /// } /// /// fn main() { /// let mut enum_map = EnumMap::<_, String>::new(); /// 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(); } } } impl, V> EnumMap { /// Returns an iterator over enum map. #[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] pub fn len(&self) -> usize { self.as_slice().len() } /// Returns whether the enum variant set is empty. /// /// This isn't particularly useful, as there is no real reason to use /// enum map for enums without variants. However, it is provided for /// consistency with data structures providing len method (and I will /// admit, to avoid clippy warnings). /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::{Enum, EnumMap}; /// /// #[derive(Enum)] /// enum Void {} /// /// #[derive(Enum)] /// enum SingleVariant { /// Variant, /// } /// /// fn main() { /// assert!(EnumMap::::new().is_empty()); /// assert!(!EnumMap::::new().is_empty()); /// } /// ``` #[inline] pub fn is_empty(&self) -> bool { self.as_slice().is_empty() } /// Swaps two indexes. /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::enum_map; /// /// fn main() { /// 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.to_usize(), b.to_usize()) } /// Converts an enum map to a slice representing values. #[inline] pub fn as_slice(&self) -> &[V] { K::slice(&self.array) } /// Converts a mutable enum map to a mutable slice representing values. #[inline] pub fn as_mut_slice(&mut self) -> &mut [V] { K::slice_mut(&mut self.array) } /// Returns a raw pointer to the enum map's slice. /// /// The caller must ensure that the slice outlives the pointer this /// function returns, or else it will end up pointing to garbage. /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::{enum_map, EnumMap}; /// /// fn main() { /// let map = enum_map! { 5 => 42, _ => 0 }; /// assert_eq!(unsafe { *map.as_ptr().offset(5) }, 42); /// } /// ``` #[inline] pub fn as_ptr(&self) -> *const V { self.as_slice().as_ptr() } /// Returns an unsafe mutable pointer to the enum map's slice. /// /// The caller must ensure that the slice outlives the pointer this /// function returns, or else it will end up pointing to garbage. /// /// # Examples /// /// ``` /// # extern crate enum_map; /// use enum_map::{enum_map, EnumMap}; /// /// fn main() { /// let mut map = enum_map! { _ => 0 }; /// unsafe { /// *map.as_mut_ptr().offset(11) = 23 /// }; /// assert_eq!(map[11], 23); /// } /// ``` #[inline] pub fn as_mut_ptr(&mut self) -> *mut V { self.as_mut_slice().as_mut_ptr() } } impl V, K: Enum, V> From for EnumMap { #[inline] fn from(f: F) -> Self { EnumMap { array: K::from_function(f), } } } #[doc(hidden)] pub fn __from_fn(f: impl FnMut(K) -> V) -> EnumMap where K: Enum, { f.into() } enum-map-0.6.2/src/serde.rs010064400017500000144000000063541357710235300137300ustar0000000000000000#![cfg(feature = "serde")] use crate::{enum_map, Enum, 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() { let mut map = serializer.serialize_map(Some(self.len()))?; for (key, value) in self { map.serialize_entry(&key, value)?; } map.end() } 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: Enum + Enum> + Deserialize<'de>, V: Deserialize<'de>, { fn deserialize>(deserializer: D) -> Result { if deserializer.is_human_readable() { deserializer.deserialize_map(HumanReadableVisitor(PhantomData)) } else { deserializer .deserialize_tuple(>::POSSIBLE_VALUES, CompactVisitor(PhantomData)) } } } struct HumanReadableVisitor(PhantomData<(K, V)>); impl<'de, K, V> de::Visitor<'de> for HumanReadableVisitor where K: Enum + Enum> + 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::new(); 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: Enum + Enum> + 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::new(); 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-0.6.2/tests/serde.rs010064400017500000144000000056251357710235300143030ustar0000000000000000#![cfg(feature = "serde")] extern crate bincode; #[macro_use] extern crate enum_map; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde_test; use enum_map::EnumMap; 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-0.6.2/tests/test.rs010064400017500000144000000157601357710235300141610ustar0000000000000000#[macro_use] extern crate enum_map; use enum_map::{Enum, EnumMap, IntoIter}; use std::cell::RefCell; use std::collections::HashSet; use std::marker::PhantomData; 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 discriminants() { #[derive(Debug, Enum, PartialEq)] enum Discriminants { A = 2000, B = 3000, C = 1000, } let mut map = EnumMap::new(); 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 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!( as core::convert::From<_>>::from(|i: u8| 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::new()); 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 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 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!(void.is_empty()); } #[test] #[should_panic] fn empty_value() { let _void: EnumMap = enum_map! { _ => unreachable!() }; } #[derive(Clone, Copy)] enum X { A(PhantomData<*const ()>), } impl Enum for X { type Array = [V; 1]; const POSSIBLE_VALUES: usize = 1; fn slice(array: &[V; 1]) -> &[V] { array } fn slice_mut(array: &mut [V; 1]) -> &mut [V] { array } fn from_usize(arg: usize) -> X { assert_eq!(arg, 0); X::A(PhantomData) } fn to_usize(self) -> usize { 0 } fn from_function V>(mut f: F) -> [V; 1] { [f(X::A(PhantomData))] } } 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_eq!(map[X::A(PhantomData)], true); } #[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 ); } enum-map-0.6.2/.cargo_vcs_info.json0000644000000001120000000000000126110ustar00{ "git": { "sha1": "b547c51eaee28f4a345da3321fb614d15970b3cd" } }