From c7db20c1df81c1dfd711a2f467699d98db6014ac Mon Sep 17 00:00:00 2001 From: Gwilym Kuiper Date: Mon, 21 Mar 2022 20:42:07 +0000 Subject: [PATCH] Implement insert correctly --- agb/src/hash_map.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/agb/src/hash_map.rs b/agb/src/hash_map.rs index 0e6baed8..8084a7cc 100644 --- a/agb/src/hash_map.rs +++ b/agb/src/hash_map.rs @@ -102,7 +102,23 @@ impl HashMap where K: Eq + Hash, { - pub fn insert(&mut self, key: K, value: V) -> &mut V { + pub fn insert(&mut self, key: K, value: V) -> Option { + let hash = self.hash(&key); + + if let Some(location) = self.nodes.get_location(&key, hash) { + Some(self.nodes.replace_at_location(location, key, value)) + } else { + if self.nodes.capacity() * 85 / 100 <= self.len() { + self.resize(self.nodes.capacity() * 2); + } + + self.nodes.insert_new(key, value, hash); + + None + } + } + + fn insert_and_get(&mut self, key: K, value: V) -> &'_ mut V { let hash = self.hash(&key); let location = if let Some(location) = self.nodes.get_location(&key, hash) { @@ -254,7 +270,7 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { where K: Hash + Eq, { - self.map.insert(self.key, value) + self.map.insert_and_get(self.key, value) } }