Skip to content

Commit

Permalink
Implement IndexMut for HashMap
Browse files Browse the repository at this point in the history
  • Loading branch information
ToMe25 committed May 30, 2024
1 parent f540cb7 commit 74167dc
Showing 1 changed file with 45 additions and 1 deletion.
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

0 comments on commit 74167dc

Please sign in to comment.