From 6a1ccf8a86a0753cfbec3ad659b4f3ed58a95867 Mon Sep 17 00:00:00 2001 From: Piotr Czarnecki Date: Thu, 17 Mar 2016 23:11:22 +0100 Subject: fixup Cleaner Recover::replace --- src/libstd/collections/hash/map.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 8fb703e8fb8..e149a5131fe 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1313,6 +1313,7 @@ impl<'a, K, V> InternalEntry> { match self { InternalEntry::Occupied { elem } => { Some(Occupied(OccupiedEntry { + key: Some(key), elem: elem })) } @@ -1347,6 +1348,7 @@ pub enum Entry<'a, K: 'a, V: 'a> { /// A view into a single occupied location in a HashMap. #[stable(feature = "rust1", since = "1.0.0")] pub struct OccupiedEntry<'a, K: 'a, V: 'a> { + key: Option, elem: FullBucket>, } @@ -1552,6 +1554,12 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { pub fn remove(self) -> V { pop_internal(self.elem).1 } + /// Returns a key that was used for search. + /// + /// The key was retained for further use. + fn take_key(&mut self) -> Option { + self.key.take() + } } impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { @@ -1661,20 +1669,16 @@ impl super::Recover for HashMap } fn replace(&mut self, key: K) -> Option { - let hash = self.make_hash(&key); self.reserve(1); - match search_hashed(&mut self.table, hash, |k| *k == key) { - InternalEntry::Occupied { mut elem } => { - Some(mem::replace(elem.read_mut().0, key)) + match self.entry(key) { + Occupied(mut occupied) => { + let key = occupied.take_key().unwrap(); + Some(mem::replace(occupied.elem.read_mut().0, key)) } - other => { - if let Some(Vacant(vacant)) = other.into_entry(key) { - vacant.insert(()); - None - } else { - unreachable!() - } + Vacant(vacant) => { + vacant.insert(()); + None } } } -- cgit 1.4.1-3-g733a5