Skip to content

Commit

Permalink
Add FromIterator impl (#23)
Browse files Browse the repository at this point in the history
Co-authored-by: Mitchell Berendhuysen <[email protected]>
  • Loading branch information
Maneren and MitchellBerend authored Feb 6, 2024
1 parent c4e8780 commit b5f1c38
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/default_btree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,20 @@ where
}
}

impl<K, V> FromIterator<(K, V)> for DefaultBTreeMap<K, V>
where
K: Ord,
V: Default,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let mut map = DefaultBTreeMap::default();
for (k, v) in iter {
let _ = map.insert(k, v);
}
map
}
}

#[macro_export]
/// A quick way to instantiate a BTreeMap.
///
Expand Down
15 changes: 15 additions & 0 deletions src/default_hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,21 @@ where
}
}

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_btree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -700,3 +700,13 @@ fn macro_test_slight_change_btree() {
assert_eq!(map, _map);
assert_eq!(map1, _map1);
}

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

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

assert_eq!(map, correct_map);
}
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 b5f1c38

Please sign in to comment.