Skip to content

Commit ec3cf8e

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 0af3c46 commit ec3cf8e

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
@@ -1342,6 +1342,25 @@ where
13421342
}
13431343
}
13441344

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

src/set.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,25 @@ where
840840
}
841841
}
842842

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

0 commit comments

Comments
 (0)