Skip to content

Commit

Permalink
Add FromIterator impl
Browse files Browse the repository at this point in the history
  • Loading branch information
Maneren committed Feb 4, 2024
1 parent 23b4b72 commit 3ccfbad
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/default_hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,21 @@ where
keys: Vec<K>,
}

impl<K, V, S> FromIterator<(K, V)> for DefaultHashMap<K, V, S>
where
K: Eq + Hash,
V: Default,
S: BuildHasher + Default,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let mut map = DefaultHashMap::with_hasher(Default::default());
for (k, v) in iter {
let _ = map.insert(k, v);
}
map
}
}

#[macro_export]
/// A quick way to instantiate a HashMap.
///
Expand Down
10 changes: 10 additions & 0 deletions tests/test_hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,16 @@ fn into_iter_default_hashmap() {
assert_eq!(v, correct_v);
}

#[test]
fn from_iter_hashmap() {
let data = [(1, 1), (2, 2), (3, 3), (4, 4)];
let map: DefaultHashMap<i8, u8> = data.iter().cloned().collect();

let correct_map: DefaultHashMap<i8, u8> = defaulthashmap!((1, 1), (2, 2), (3, 3), (4, 4));

assert_eq!(map, correct_map);
}

#[test]
fn borrow_loop_over_default_hashmap() {
let mut map: DefaultHashMap<i8, u8> = DefaultHashMap::new();
Expand Down

0 comments on commit 3ccfbad

Please sign in to comment.