From af2932fa2abb838c5e70bbb59b39e6a4dbe6c59d Mon Sep 17 00:00:00 2001 From: Andy Freeland Date: Thu, 21 Oct 2021 14:06:55 -0700 Subject: [PATCH] Add `IndexMap::from(array)` and `IndexSet::from(array)` This patch adds `IndexMap::from(array)` and `IndexSet::from(array)` to match the API for `HashMap`, `HashSet`, etc. as of https://github.com/rust-lang/rust/pull/84111. --- src/map.rs | 29 +++++++++++++++++++++++++++++ src/set.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/map.rs b/src/map.rs index 3a43a79b..5505476c 100644 --- a/src/map.rs +++ b/src/map.rs @@ -1340,6 +1340,25 @@ where } } +#[cfg(has_std)] +impl From<[(K, V); N]> for IndexMap +where + K: Hash + Eq, +{ + /// # Examples + /// + /// ``` + /// use indexmap::IndexMap; + /// + /// let map1 = IndexMap::from([(1, 2), (3, 4)]); + /// let map2: IndexMap<_, _> = [(1, 2), (3, 4)].into(); + /// assert_eq!(map1, map2); + /// ``` + fn from(arr: [(K, V); N]) -> Self { + std::array::IntoIter::new(arr).collect() + } +} + impl Extend<(K, V)> for IndexMap where K: Hash + Eq, @@ -1834,4 +1853,14 @@ mod tests { assert!(values.contains(&'b')); assert!(values.contains(&'c')); } + + #[test] + fn from_array() { + let map = IndexMap::from([(1, 2), (3, 4)]); + let mut expected = IndexMap::new(); + expected.insert(1, 2); + expected.insert(3, 4); + + assert_eq!(map, expected) + } } diff --git a/src/set.rs b/src/set.rs index 134c9045..960fa24e 100644 --- a/src/set.rs +++ b/src/set.rs @@ -838,6 +838,25 @@ where } } +#[cfg(has_std)] +impl From<[T; N]> for IndexSet +where + T: Eq + Hash, +{ + /// # Examples + /// + /// ``` + /// use indexmap::IndexSet; + /// + /// let set1 = IndexSet::from([1, 2, 3, 4]); + /// let set2: IndexSet<_> = [1, 2, 3, 4].into(); + /// assert_eq!(set1, set2); + /// ``` + fn from(arr: [T; N]) -> Self { + std::array::IntoIter::new(arr).collect() + } +} + impl Extend for IndexSet where T: Hash + Eq, @@ -1705,4 +1724,12 @@ mod tests { assert_eq!(&set_c - &set_d, set_a); assert_eq!(&set_d - &set_c, &set_d - &set_b); } + + #[test] + fn from_array() { + let set1 = IndexSet::from([1, 2, 3, 4]); + let set2: IndexSet<_> = [1, 2, 3, 4].into(); + + assert_eq!(set1, set2); + } }