Skip to content

Commit ba82400

Browse files
committed
Added get_entry_mut method
1 parent a226f79 commit ba82400

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ fn main() {
6666
- [x] `len` / `is_empty`
6767
- [x] `get` / `get_mut`
6868
- [x] `get_entry` - returns `Option<(&K, &V)>`
69-
- [ ] `get_entry_mut` - returns `Option<(&K, &mut V)>`
70-
- [ ] `entry`
69+
- [x] `get_entry_mut` - returns `Option<(&K, &mut V)>`
70+
- [ ] `entry` - entry API similar to `HashMap`
7171
- [x] `contains_key`
7272
- [x] `insert`
7373
- [x] `remove`

src/map.rs

+39
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,45 @@ impl<K: Ord, V> BSTMap<K, V> {
346346
None
347347
}
348348

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+
349388
/// Inserts a new value into the binary search tree
350389
///
351390
/// Returns the previous value if the key was already present in an

src/map/node.rs

+5
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,11 @@ impl<'a, K, V> NodeMut<'a, K, V> {
176176
&mut self.node.value
177177
}
178178

179+
/// Returns the (key, mutable value) pair of this node, consuming the node in the process
180+
pub(crate) fn into_entry_mut(self) -> (&'a K, &'a mut V) {
181+
(&self.node.key, &mut self.node.value)
182+
}
183+
179184
/// Returns true if this node has a left subtree
180185
pub fn has_left(&self) -> bool {
181186
self.node.left.is_some()

0 commit comments

Comments
 (0)