@@ -346,6 +346,45 @@ impl<K: Ord, V> BSTMap<K, V> {
346
346
None
347
347
}
348
348
349
+ /// Returns a key-value pair corresponding to the given key, or `None` if no such key exists in
350
+ /// the binary search tree
351
+ ///
352
+ /// The key may be any borrowed form of the map's key type, but the ordering on the borrowed
353
+ /// form must match the ordering on the key type.
354
+ ///
355
+ /// Time complexity: `O(log n)`
356
+ ///
357
+ /// # Examples
358
+ ///
359
+ /// ```
360
+ /// use bst::BSTMap;
361
+ ///
362
+ /// let mut map = BSTMap::new();
363
+ /// map.insert(1, "a");
364
+ /// assert_eq!(map.get_entry_mut(&1), Some((&1, &mut "a")));
365
+ /// assert_eq!(map.get_entry_mut(&2), None);
366
+ ///
367
+ /// let (key, value) = map.get_entry_mut(&1).unwrap();
368
+ /// assert_eq!(key, &1);
369
+ /// *value = "abc";
370
+ /// assert_eq!(map.get(&1), Some(&"abc"));
371
+ /// ```
372
+ pub fn get_entry_mut < Q > ( & mut self , key : & Q ) -> Option < ( & K , & mut V ) >
373
+ where K : Borrow < Q > ,
374
+ Q : Ord + ?Sized ,
375
+ {
376
+ let mut current = self . root_mut ( ) ;
377
+ while let Some ( mut node) = current {
378
+ match key. cmp ( node. key ( ) . borrow ( ) ) {
379
+ Ordering :: Less => current = node. left ( ) ,
380
+ Ordering :: Greater => current = node. right ( ) ,
381
+ Ordering :: Equal => return Some ( node. into_entry_mut ( ) ) ,
382
+ }
383
+ }
384
+
385
+ None
386
+ }
387
+
349
388
/// Inserts a new value into the binary search tree
350
389
///
351
390
/// Returns the previous value if the key was already present in an
0 commit comments