From b3e2b74a6ca31e86862faafdc30f7664c1e243c8 Mon Sep 17 00:00:00 2001 From: Michael Neumann Date: Tue, 17 Jun 2014 12:07:36 +0200 Subject: [PATCH] Add the find_mut_equiv method to hashmap::HashMap Based on this commit: https://github.com/rcatolino/rust/commit/12d9fd6b0100a2141627e0b21a67ed9976a09c40 --- src/libstd/collections/hashmap.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/libstd/collections/hashmap.rs b/src/libstd/collections/hashmap.rs index f11e68c7a4671..945018334d7e1 100644 --- a/src/libstd/collections/hashmap.rs +++ b/src/libstd/collections/hashmap.rs @@ -1362,6 +1362,18 @@ impl, V, S, H: Hasher> HashMap { } } + /// Return a mutable reference to the value corresponding to the key in the map, using + /// equivalence. + pub fn find_equiv_mut<'a, Q: Hash + Equiv>(&'a mut self, k: &Q) -> Option<&'a mut V> { + match self.search_equiv(k) { + None => None, + Some(idx) => { + let (_, v_ref) = self.table.read_mut(&idx); + Some(v_ref) + } + } + } + /// An iterator visiting all keys in arbitrary order. /// Iterator element type is &'a K. pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { @@ -2139,6 +2151,23 @@ mod test_map { assert_eq!(m.find_equiv(&("qux")), None); } + #[test] + fn test_find_equiv_mut() { + let mut m = HashMap::new(); + + let (foo, bar, baz) = (1,2,3); + m.insert("foo".to_string(), foo); + m.insert("bar".to_string(), bar); + m.insert("baz".to_string(), baz); + + let new = 100; + match m.find_equiv_mut(&("bar")) { + None => fail!(), + Some(x) => *x = new + } + assert_eq!(m.find_equiv(&("bar")), Some(&new)); + } + #[test] fn test_from_iter() { let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];