@@ -14,7 +14,7 @@ use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
1414use super :: search:: SearchResult :: * ;
1515
1616mod entry;
17- pub use entry:: { Entry , OccupiedEntry , VacantEntry } ;
17+ pub use entry:: { Entry , OccupiedEntry , OccupiedError , VacantEntry } ;
1818use Entry :: * ;
1919
2020/// Minimum number of elements in nodes that are not a root.
@@ -836,6 +836,40 @@ impl<K, V> BTreeMap<K, V> {
836836 }
837837 }
838838
839+ /// Tries to insert a key-value pair into the map, and returns
840+ /// a mutable reference to the value in the entry.
841+ ///
842+ /// If the map already had this key present, nothing is updated, and
843+ /// an error containing the occupied entry and the value is returned.
844+ ///
845+ /// # Examples
846+ ///
847+ /// Basic usage:
848+ ///
849+ /// ```
850+ /// #![feature(map_try_insert)]
851+ ///
852+ /// use std::collections::BTreeMap;
853+ ///
854+ /// let mut map = BTreeMap::new();
855+ /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
856+ ///
857+ /// let err = map.try_insert(37, "b").unwrap_err();
858+ /// assert_eq!(err.entry.key(), &37);
859+ /// assert_eq!(err.entry.get(), &"a");
860+ /// assert_eq!(err.value, "b");
861+ /// ```
862+ #[ unstable( feature = "map_try_insert" , issue = "none" ) ]
863+ pub fn try_insert ( & mut self , key : K , value : V ) -> Result < & mut V , OccupiedError < ' _ , K , V > >
864+ where
865+ K : Ord ,
866+ {
867+ match self . entry ( key) {
868+ Occupied ( entry) => Err ( OccupiedError { entry, value } ) ,
869+ Vacant ( entry) => Ok ( entry. insert ( value) ) ,
870+ }
871+ }
872+
839873 /// Removes a key from the map, returning the value at the key if the key
840874 /// was previously in the map.
841875 ///
0 commit comments