Skip to content

Commit

Permalink
Auto merge of rust-lang#79988 - ssomers:btree_cleanup_5, r=Mark-Simul…
Browse files Browse the repository at this point in the history
…acrum

BTreeMap: capture a recurring use pattern as replace_kv

r? `@Mark-Simulacrum`
  • Loading branch information
bors committed Dec 13, 2020
2 parents f61e5ca + 0ae4c95 commit dd11f45
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
12 changes: 8 additions & 4 deletions library/alloc/src/collections/btree/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,12 @@ impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>
(key, val)
}
}

/// Replace the key and value that the KV handle refers to.
pub fn replace_kv(&mut self, k: K, v: V) -> (K, V) {
let (key, val) = self.kv_mut();
(mem::replace(key, k), mem::replace(val, v))
}
}

impl<'a, K: 'a, V: 'a, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker::KV> {
Expand Down Expand Up @@ -1432,8 +1438,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> {
unsafe {
let (k, v, edge) = self.left_child.pop();

let k = mem::replace(self.parent.kv_mut().0, k);
let v = mem::replace(self.parent.kv_mut().1, v);
let (k, v) = self.parent.replace_kv(k, v);

match self.right_child.reborrow_mut().force() {
ForceResult::Leaf(mut leaf) => leaf.push_front(k, v),
Expand All @@ -1455,8 +1460,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> {
unsafe {
let (k, v, edge) = self.right_child.pop_front();

let k = mem::replace(self.parent.kv_mut().0, k);
let v = mem::replace(self.parent.kv_mut().1, v);
let (k, v) = self.parent.replace_kv(k, v);

match self.left_child.reborrow_mut().force() {
ForceResult::Leaf(mut leaf) => leaf.push(k, v),
Expand Down
6 changes: 2 additions & 4 deletions library/alloc/src/collections/btree/remove.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::map::MIN_LEN;
use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef};
use super::unwrap_unchecked;
use core::mem;

impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV> {
/// Removes a key-value pair from the tree, and returns that pair, as well as
Expand Down Expand Up @@ -84,10 +83,9 @@ impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>,
// The internal node may have been stolen from or merged. Go back right
// to find where the original KV ended up.
let mut internal = unsafe { unwrap_unchecked(left_hole.next_kv().ok()) };
let old_key = mem::replace(internal.kv_mut().0, left_kv.0);
let old_val = mem::replace(internal.kv_mut().1, left_kv.1);
let old_kv = internal.replace_kv(left_kv.0, left_kv.1);
let pos = internal.next_leaf_edge();
((old_key, old_val), pos)
(old_kv, pos)
}
}

Expand Down

0 comments on commit dd11f45

Please sign in to comment.