Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit af2932f

Browse files
committedOct 21, 2021
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 rust-lang/rust#84111.
1 parent 35b36eb commit af2932f

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
 

‎src/map.rs

+29
Original file line numberDiff line numberDiff line change
@@ -1340,6 +1340,25 @@ where
13401340
}
13411341
}
13421342

1343+
#[cfg(has_std)]
1344+
impl<K, V, const N: usize> From<[(K, V); N]> for IndexMap<K, V, RandomState>
1345+
where
1346+
K: Hash + Eq,
1347+
{
1348+
/// # Examples
1349+
///
1350+
/// ```
1351+
/// use indexmap::IndexMap;
1352+
///
1353+
/// let map1 = IndexMap::from([(1, 2), (3, 4)]);
1354+
/// let map2: IndexMap<_, _> = [(1, 2), (3, 4)].into();
1355+
/// assert_eq!(map1, map2);
1356+
/// ```
1357+
fn from(arr: [(K, V); N]) -> Self {
1358+
std::array::IntoIter::new(arr).collect()
1359+
}
1360+
}
1361+
13431362
impl<K, V, S> Extend<(K, V)> for IndexMap<K, V, S>
13441363
where
13451364
K: Hash + Eq,
@@ -1834,4 +1853,14 @@ mod tests {
18341853
assert!(values.contains(&'b'));
18351854
assert!(values.contains(&'c'));
18361855
}
1856+
1857+
#[test]
1858+
fn from_array() {
1859+
let map = IndexMap::from([(1, 2), (3, 4)]);
1860+
let mut expected = IndexMap::new();
1861+
expected.insert(1, 2);
1862+
expected.insert(3, 4);
1863+
1864+
assert_eq!(map, expected)
1865+
}
18371866
}

‎src/set.rs

+27
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,25 @@ where
838838
}
839839
}
840840

841+
#[cfg(has_std)]
842+
impl<T, const N: usize> From<[T; N]> for IndexSet<T, RandomState>
843+
where
844+
T: Eq + Hash,
845+
{
846+
/// # Examples
847+
///
848+
/// ```
849+
/// use indexmap::IndexSet;
850+
///
851+
/// let set1 = IndexSet::from([1, 2, 3, 4]);
852+
/// let set2: IndexSet<_> = [1, 2, 3, 4].into();
853+
/// assert_eq!(set1, set2);
854+
/// ```
855+
fn from(arr: [T; N]) -> Self {
856+
std::array::IntoIter::new(arr).collect()
857+
}
858+
}
859+
841860
impl<T, S> Extend<T> for IndexSet<T, S>
842861
where
843862
T: Hash + Eq,
@@ -1705,4 +1724,12 @@ mod tests {
17051724
assert_eq!(&set_c - &set_d, set_a);
17061725
assert_eq!(&set_d - &set_c, &set_d - &set_b);
17071726
}
1727+
1728+
#[test]
1729+
fn from_array() {
1730+
let set1 = IndexSet::from([1, 2, 3, 4]);
1731+
let set2: IndexSet<_> = [1, 2, 3, 4].into();
1732+
1733+
assert_eq!(set1, set2);
1734+
}
17081735
}

0 commit comments

Comments
 (0)
Please sign in to comment.