Skip to content

Commit

Permalink
Add IndexMap::from(array) and IndexSet::from(array)
Browse files Browse the repository at this point in the history
This patch adds `IndexMap::from(array)` and `IndexSet::from(array)` to
match the API for `HashMap`, `HashSet`, etc. as of
rust-lang/rust#84111.
  • Loading branch information
rouge8 committed Dec 9, 2021
1 parent 0af3c46 commit ec3cf8e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,25 @@ where
}
}

#[cfg(has_std)]
impl<K, V, const N: usize> From<[(K, V); N]> for IndexMap<K, V, RandomState>
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<K, V, S> Extend<(K, V)> for IndexMap<K, V, S>
where
K: Hash + Eq,
Expand Down Expand Up @@ -1836,4 +1855,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)
}
}
27 changes: 27 additions & 0 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,25 @@ where
}
}

#[cfg(has_std)]
impl<T, const N: usize> From<[T; N]> for IndexSet<T, RandomState>
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<T, S> Extend<T> for IndexSet<T, S>
where
T: Hash + Eq,
Expand Down Expand Up @@ -1707,4 +1726,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);
}
}

0 comments on commit ec3cf8e

Please sign in to comment.