Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement pop_equiv() for HashMap #11691

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions src/libstd/hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
}
}

fn pop_internal(&mut self, hash: uint, k: &K) -> Option<V> {
fn pop_internal(&mut self, searchresult: SearchResult) -> Option<V> {
// Removing from an open-addressed hashtable
// is, well, painful. The problem is that
// the entry may lie on the probe path for other
Expand All @@ -267,7 +267,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
//
// I found this explanation elucidating:
// http://www.maths.lse.ac.uk/Courses/MA407/del-hash.pdf
let mut idx = match self.bucket_for_key_with_hash(hash, k) {
let mut idx = match searchresult {
TableFull | FoundHole(_) => return None,
FoundEntry(idx) => idx
};
Expand Down Expand Up @@ -349,8 +349,17 @@ impl<K:Hash + Eq,V> MutableMap<K, V> for HashMap<K, V> {
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
fn pop(&mut self, k: &K) -> Option<V> {
let hash = k.hash_keyed(self.k0, self.k1) as uint;
self.pop_internal(hash, k)
let s = self.bucket_for_key(k);
self.pop_internal(s)
}
}

impl<K: Hash + Eq, V> HashMap<K, V> {
/// Removes a key from the map using equivalence, returning the value
/// at the key if the key was previously in the map.
pub fn pop_equiv<Q:Hash + Equiv<K>>(&mut self, k: &Q) -> Option<V> {
let s = self.bucket_for_key_equiv(k);
self.pop_internal(s)
}
}

Expand Down Expand Up @@ -968,6 +977,16 @@ mod test_map {
assert_eq!(m.pop(&1), None);
}

#[test]
fn test_pop_equiv() {
let mut m = HashMap::new();
m.insert(~"key1", 1);
m.insert(~"key2", 2);
assert_eq!(m.pop_equiv(&("key1")), Some(1));
assert_eq!(m.pop_equiv(&("key1")), None);
assert_eq!(m.pop_equiv(&(~"key2")), Some(2));
}

#[test]
fn test_swap() {
let mut m = HashMap::new();
Expand Down