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 IndexMut for HashMap #527

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
46 changes: 45 additions & 1 deletion src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use core::hash::{BuildHasher, Hash};
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::mem;
use core::ops::Index;
use core::ops::{Index, IndexMut};

/// Default hasher for `HashMap`.
#[cfg(feature = "ahash")]
Expand Down Expand Up @@ -2257,6 +2257,37 @@ where
}
}

impl<K, Q: ?Sized, V, S, A> IndexMut<&Q> for HashMap<K, V, S, A>
where
K: Eq + Hash,
Q: Hash + Equivalent<K>,
S: BuildHasher,
A: Allocator,
{
/// Returns a mutable reference to the value corresponding to the supplied key.
///
/// # Panics
///
/// Panics if the key is not present in the `HashMap`.
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
///
/// let mut map: HashMap<_, _> = [("a", "One".to_owned()), ("b", "Two".to_owned())].into();
///
/// map[&"a"].make_ascii_uppercase();
///
/// assert_eq!(map.get("a"), Some(&"ONE".to_owned()));
/// assert_eq!(map.get("b"), Some(&"Two".to_owned()));
/// ```
#[cfg_attr(feature = "inline-more", inline)]
fn index_mut(&mut self, key: &Q) -> &mut V {
self.get_mut(key).expect("no entry found for key")
}
}

// The default hasher is used to match the std implementation signature
#[cfg(feature = "ahash")]
impl<K, V, A, const N: usize> From<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A>
Expand Down Expand Up @@ -7478,6 +7509,19 @@ mod test_map {
map[&4];
}

#[test]
fn test_index_mut() {
let mut map = HashMap::new();

map.insert(5, 9);
map.insert(3, 17);
map.insert(9, -17);

map[&3] *= 5;

assert_eq!(map.get(&3), Some(&85));
}

#[test]
fn test_entry() {
let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
Expand Down
Loading