Skip to content

Commit 6f8703d

Browse files
committed
Auto merge of #145 - dodomorandi:hashmap-get_key_value_mut, r=Amanieu
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. Closes #144
2 parents e0c90c3 + 1e7bf40 commit 6f8703d

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
@@ -756,6 +756,44 @@ where
756756
})
757757
}
758758

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

0 commit comments

Comments
 (0)