Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add IndexMap::from(array) and IndexSet::from(array) #205

Merged
merged 2 commits into from
Jan 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ fn main() {
Some(_) => autocfg::emit("has_std"),
None => autocfg::new().emit_sysroot_crate("std"),
}
autocfg::new().emit_rustc_version(1, 51);
autocfg::rerun_path("build.rs");
}
30 changes: 30 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1345,6 +1345,25 @@ where
}
}

#[cfg(all(has_std, rustc_1_51))]
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 @@ -1839,4 +1858,15 @@ mod tests {
assert!(values.contains(&'b'));
assert!(values.contains(&'c'));
}

#[test]
#[cfg(all(has_std, rustc_1_51))]
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)
}
}
28 changes: 28 additions & 0 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,25 @@ where
}
}

#[cfg(all(has_std, rustc_1_51))]
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 @@ -1710,4 +1729,13 @@ mod tests {
assert_eq!(&set_c - &set_d, set_a);
assert_eq!(&set_d - &set_c, &set_d - &set_b);
}

#[test]
#[cfg(all(has_std, rustc_1_51))]
fn from_array() {
let set1 = IndexSet::from([1, 2, 3, 4]);
let set2: IndexSet<_> = [1, 2, 3, 4].into();

assert_eq!(set1, set2);
}
}