Skip to content

Commit 1e7bf40

Browse files
committed
Add HashMap::get_key_value_mut
This new API exposes a way to modify a value of an HashMap while keeping a reference to the relative key. The other safe way of doing this is using the `RawEntryMut` API, which could easily lead to an inconsistent state of the map if misused.
1 parent 8be230c commit 1e7bf40

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/map.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,44 @@ where
758758
})
759759
}
760760

761+
/// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.
762+
///
763+
/// The supplied key may be any borrowed form of the map's key type, but
764+
/// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
765+
/// the key type.
766+
///
767+
/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
768+
/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
769+
///
770+
/// # Examples
771+
///
772+
/// ```
773+
/// use hashbrown::HashMap;
774+
///
775+
/// let mut map = HashMap::new();
776+
/// map.insert(1, "a");
777+
/// let (k, v) = map.get_key_value_mut(&1).unwrap();
778+
/// assert_eq!(k, &1);
779+
/// assert_eq!(v, &mut "a");
780+
/// *v = "b";
781+
/// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
782+
/// assert_eq!(map.get_key_value_mut(&2), None);
783+
/// ```
784+
#[inline]
785+
pub fn get_key_value_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<(&K, &mut V)>
786+
where
787+
K: Borrow<Q>,
788+
Q: Hash + Eq,
789+
{
790+
let hash = make_hash(&self.hash_builder, k);
791+
self.table
792+
.find(hash, |x| k.eq(x.0.borrow()))
793+
.map(|item| unsafe {
794+
let &mut (ref key, ref mut value) = item.as_mut();
795+
(key, value)
796+
})
797+
}
798+
761799
/// Returns `true` if the map contains a value for the specified key.
762800
///
763801
/// The key may be any borrowed form of the map's key type, but

0 commit comments

Comments
 (0)