Skip to content

Commit f6fe24a

Browse files
committed
Add HashMap::try_insert and hash_map::OccupiedError.
1 parent 09cbcdc commit f6fe24a

File tree

1 file changed

+46
-0
lines changed
  • library/std/src/collections/hash

1 file changed

+46
-0
lines changed

library/std/src/collections/hash/map.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,40 @@ where
842842
self.base.insert(k, v)
843843
}
844844

845+
/// Tries to insert a key-value pair into the map, and returns
846+
/// a mutable reference to the value in the entry.
847+
///
848+
/// If the map already had this key present, nothing is updated, and
849+
/// an error containing the occupied entry and the value is returned.
850+
///
851+
/// # Examples
852+
///
853+
/// Basic usage:
854+
///
855+
/// ```
856+
/// #![feature(map_try_insert)]
857+
///
858+
/// use std::collections::HashMap;
859+
///
860+
/// let mut map = HashMap::new();
861+
/// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
862+
///
863+
/// let err = map.try_insert(37, "b").unwrap_err();
864+
/// assert_eq!(err.entry.key(), &37);
865+
/// assert_eq!(err.entry.get(), &"a");
866+
/// assert_eq!(err.value, "b");
867+
/// ```
868+
#[unstable(feature = "map_try_insert", issue = "none")]
869+
pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>>
870+
where
871+
K: Ord,
872+
{
873+
match self.entry(key) {
874+
Occupied(entry) => Err(OccupiedError { entry, value }),
875+
Vacant(entry) => Ok(entry.insert(value)),
876+
}
877+
}
878+
845879
/// Removes a key from the map, returning the value at the key if the key
846880
/// was previously in the map.
847881
///
@@ -1851,6 +1885,18 @@ impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
18511885
}
18521886
}
18531887

1888+
/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
1889+
///
1890+
/// Contains the occupied entry, and the value that was not inserted.
1891+
#[unstable(feature = "map_try_insert", issue = "none")]
1892+
#[derive(Debug)]
1893+
pub struct OccupiedError<'a, K: 'a, V: 'a> {
1894+
/// The entry in the map that was already occupied.
1895+
pub entry: OccupiedEntry<'a, K, V>,
1896+
/// The value which was not inserted, because the entry was already occupied.
1897+
pub value: V,
1898+
}
1899+
18541900
#[stable(feature = "rust1", since = "1.0.0")]
18551901
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
18561902
type Item = (&'a K, &'a V);

0 commit comments

Comments
 (0)