From f41df033945ae768f224fa478083dd83ce7991ba Mon Sep 17 00:00:00 2001 From: Maneren <49210777+Maneren@users.noreply.github.com> Date: Sat, 3 Feb 2024 20:23:06 +0100 Subject: [PATCH] Add FromIterator impl --- src/default_hashmap.rs | 44 ++++++++++++++++++++++++++++++++++++++++++ tests/test_hashmap.rs | 10 ++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/default_hashmap.rs b/src/default_hashmap.rs index e5e0116..6a7cba0 100644 --- a/src/default_hashmap.rs +++ b/src/default_hashmap.rs @@ -651,6 +651,50 @@ where } } +impl Iterator for DefaultHashMapIter +where + K: Eq + Hash, + V: Default, + S: BuildHasher, +{ + type Item = (K, V); + + fn next(&mut self) -> Option { + match self.keys.pop() { + Some(key) => { + let val = self._defaulthashmap.remove(&key); + Option::Some((key, val)) + } + None => Option::None, + } + } +} + +pub struct DefaultHashMapIter +where + K: Eq + Hash, + V: Default, + S: BuildHasher, +{ + _defaulthashmap: DefaultHashMap, + keys: Vec, +} + +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_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();