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

Add find_equiv_mut to HashMap #15721

Closed
wants to merge 1 commit 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
33 changes: 28 additions & 5 deletions src/libstd/collections/hashmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use mem::replace;
use num;
use option::{Some, None, Option};
use result::{Ok, Err};
use tuple::Tuple2;

mod table {
use clone::Clone;
Expand Down Expand Up @@ -1349,12 +1350,17 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
/// Return the value corresponding to the key in the map, using
/// equivalence.
pub fn find_equiv<'a, Q: Hash<S> + Equiv<K>>(&'a self, k: &Q) -> Option<&'a V> {
self.search_equiv(k).map(|idx| {
self.table.read(&idx).val1()
})
}

/// Return the (mutable) value corresponding to the key in the map, using
/// equivalence.
pub fn find_equiv_mut<'a, Q: Hash<S> + Equiv<K>>(&'a mut self, k: &Q) -> Option<&'a mut V> {
match self.search_equiv(k) {
None => None,
Some(idx) => {
let (_, v_ref) = self.table.read(&idx);
Some(v_ref)
}
None => None,
Some(idx) => Some(self.table.read_mut(&idx).val1())
}
}

Expand Down Expand Up @@ -2115,6 +2121,23 @@ mod test_map {
assert_eq!(m.find_equiv(&("qux")), None);
}

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

let (mut foo, mut bar, mut baz) = (1i, 2, 3);
m.insert("foo".to_string(), foo);
m.insert("bar".to_string(), bar);
m.insert("baz".to_string(), baz);


assert_eq!(m.find_equiv_mut(&"foo"), Some(&mut foo));
assert_eq!(m.find_equiv_mut(&"bar"), Some(&mut bar));
assert_eq!(m.find_equiv_mut(&"baz"), Some(&mut baz));

assert_eq!(m.find_equiv_mut(&"qux"), None);
}

#[test]
fn test_from_iter() {
let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
Expand Down