diff --git a/src/default_btree.rs b/src/default_btree.rs index 33e4b5a..d44bf02 100644 --- a/src/default_btree.rs +++ b/src/default_btree.rs @@ -790,6 +790,20 @@ where } } +impl FromIterator<(K, V)> for DefaultBTreeMap +where + K: Ord, + V: Default, +{ + fn from_iter>(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. /// diff --git a/src/default_hashmap.rs b/src/default_hashmap.rs index e5e0116..40a8408 100644 --- a/src/default_hashmap.rs +++ b/src/default_hashmap.rs @@ -651,6 +651,21 @@ where } } +impl FromIterator<(K, V)> for DefaultHashMap +where + K: Eq + Hash, + V: Default, + S: BuildHasher + Default, +{ + fn from_iter>(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. /// diff --git a/tests/test_btree.rs b/tests/test_btree.rs index aca7b74..51b9d1b 100644 --- a/tests/test_btree.rs +++ b/tests/test_btree.rs @@ -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 = data.iter().cloned().collect(); + + let correct_map: DefaultBTreeMap = defaultbtreemap!((1, 1), (2, 2), (3, 3), (4, 4)); + + assert_eq!(map, correct_map); +} diff --git a/tests/test_hashmap.rs b/tests/test_hashmap.rs index c40910b..4379605 100644 --- a/tests/test_hashmap.rs +++ b/tests/test_hashmap.rs @@ -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 = data.iter().cloned().collect(); + + let correct_map: DefaultHashMap = 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 = DefaultHashMap::new();