Skip to content

Commit f0159f6

Browse files
committed
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 4d6dde3 commit f0159f6

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/map.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1345,6 +1345,25 @@ where
13451345
}
13461346
}
13471347

1348+
#[cfg(has_std)]
1349+
impl<K, V, const N: usize> From<[(K, V); N]> for IndexMap<K, V, RandomState>
1350+
where
1351+
K: Hash + Eq,
1352+
{
1353+
/// # Examples
1354+
///
1355+
/// ```
1356+
/// use indexmap::IndexMap;
1357+
///
1358+
/// let map1 = IndexMap::from([(1, 2), (3, 4)]);
1359+
/// let map2: IndexMap<_, _> = [(1, 2), (3, 4)].into();
1360+
/// assert_eq!(map1, map2);
1361+
/// ```
1362+
fn from(arr: [(K, V); N]) -> Self {
1363+
std::array::IntoIter::new(arr).collect()
1364+
}
1365+
}
1366+
13481367
impl<K, V, S> Extend<(K, V)> for IndexMap<K, V, S>
13491368
where
13501369
K: Hash + Eq,
@@ -1839,4 +1858,14 @@ mod tests {
18391858
assert!(values.contains(&'b'));
18401859
assert!(values.contains(&'c'));
18411860
}
1861+
1862+
#[test]
1863+
fn from_array() {
1864+
let map = IndexMap::from([(1, 2), (3, 4)]);
1865+
let mut expected = IndexMap::new();
1866+
expected.insert(1, 2);
1867+
expected.insert(3, 4);
1868+
1869+
assert_eq!(map, expected)
1870+
}
18421871
}

src/set.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -843,6 +843,25 @@ where
843843
}
844844
}
845845

846+
#[cfg(has_std)]
847+
impl<T, const N: usize> From<[T; N]> for IndexSet<T, RandomState>
848+
where
849+
T: Eq + Hash,
850+
{
851+
/// # Examples
852+
///
853+
/// ```
854+
/// use indexmap::IndexSet;
855+
///
856+
/// let set1 = IndexSet::from([1, 2, 3, 4]);
857+
/// let set2: IndexSet<_> = [1, 2, 3, 4].into();
858+
/// assert_eq!(set1, set2);
859+
/// ```
860+
fn from(arr: [T; N]) -> Self {
861+
std::array::IntoIter::new(arr).collect()
862+
}
863+
}
864+
846865
impl<T, S> Extend<T> for IndexSet<T, S>
847866
where
848867
T: Hash + Eq,
@@ -1710,4 +1729,12 @@ mod tests {
17101729
assert_eq!(&set_c - &set_d, set_a);
17111730
assert_eq!(&set_d - &set_c, &set_d - &set_b);
17121731
}
1732+
1733+
#[test]
1734+
fn from_array() {
1735+
let set1 = IndexSet::from([1, 2, 3, 4]);
1736+
let set2: IndexSet<_> = [1, 2, 3, 4].into();
1737+
1738+
assert_eq!(set1, set2);
1739+
}
17131740
}

0 commit comments

Comments
 (0)