Skip to content

Commit 12d9fd6

Browse files
committed
Add the find_mut_equiv method to std::hashmap.
1 parent b3cee62 commit 12d9fd6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/libstd/hashmap.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,16 @@ impl<K: Hash + Eq, V> HashMap<K, V> {
449449
}
450450
}
451451

452+
/// Return a mutable reference to the value corresponding to the key
453+
/// in the map, using equivalence
454+
pub fn find_mut_equiv<'a, Q:Hash + Equiv<K>>(&'a mut self, k: &Q)
455+
-> Option<&'a mut V> {
456+
match self.bucket_for_key_equiv(k) {
457+
FoundEntry(idx) => Some(self.mut_value_for_bucket(idx)),
458+
TableFull | FoundHole(_) => None,
459+
}
460+
}
461+
452462
/// Visit all keys
453463
pub fn each_key(&self, blk: |k: &K| -> bool) -> bool {
454464
self.iter().advance(|(k, _)| blk(k))
@@ -1003,6 +1013,24 @@ mod test_map {
10031013
assert_eq!(m.find_equiv(&("qux")), None);
10041014
}
10051015

1016+
#[test]
1017+
fn test_find_mut_equiv() {
1018+
let mut m = HashMap::new();
1019+
1020+
let (foo, bar, baz) = (1,2,3);
1021+
m.insert(~"foo", foo);
1022+
m.insert(~"bar", bar);
1023+
m.insert(~"baz", baz);
1024+
1025+
let new = 4;
1026+
match m.find_mut_equiv(&("bar")) {
1027+
Some(value) => value = new,
1028+
None => fail!()
1029+
}
1030+
1031+
assert_eq!(m.find_equiv(&("bar")), Some(&new));
1032+
}
1033+
10061034
#[test]
10071035
fn test_from_iter() {
10081036
let xs = ~[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];

0 commit comments

Comments
 (0)