diff --git a/src/map.rs b/src/map.rs index 7f06bd558..c69872702 100644 --- a/src/map.rs +++ b/src/map.rs @@ -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")] @@ -2257,6 +2257,37 @@ where } } +impl IndexMut<&Q> for HashMap +where + K: Eq + Hash, + Q: Hash + Equivalent, + 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 From<[(K, V); N]> for HashMap @@ -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)];