Skip to content

Commit 8bb46ca

Browse files
authored
Merge pull request #205 from rouge8/from-array
Add `IndexMap::from(array)` and `IndexSet::from(array)`
2 parents 4d6dde3 + 5d2ce52 commit 8bb46ca

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

build.rs

+1
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@ fn main() {
44
Some(_) => autocfg::emit("has_std"),
55
None => autocfg::new().emit_sysroot_crate("std"),
66
}
7+
autocfg::new().emit_rustc_version(1, 51);
78
autocfg::rerun_path("build.rs");
89
}

src/map.rs

+30
Original file line numberDiff line numberDiff line change
@@ -1345,6 +1345,25 @@ where
13451345
}
13461346
}
13471347

1348+
#[cfg(all(has_std, rustc_1_51))]
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,15 @@ mod tests {
18391858
assert!(values.contains(&'b'));
18401859
assert!(values.contains(&'c'));
18411860
}
1861+
1862+
#[test]
1863+
#[cfg(all(has_std, rustc_1_51))]
1864+
fn from_array() {
1865+
let map = IndexMap::from([(1, 2), (3, 4)]);
1866+
let mut expected = IndexMap::new();
1867+
expected.insert(1, 2);
1868+
expected.insert(3, 4);
1869+
1870+
assert_eq!(map, expected)
1871+
}
18421872
}

src/set.rs

+28
Original file line numberDiff line numberDiff line change
@@ -843,6 +843,25 @@ where
843843
}
844844
}
845845

846+
#[cfg(all(has_std, rustc_1_51))]
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,13 @@ 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+
#[cfg(all(has_std, rustc_1_51))]
1735+
fn from_array() {
1736+
let set1 = IndexSet::from([1, 2, 3, 4]);
1737+
let set2: IndexSet<_> = [1, 2, 3, 4].into();
1738+
1739+
assert_eq!(set1, set2);
1740+
}
17131741
}

0 commit comments

Comments
 (0)