Skip to content

Commit 416fd43

Browse files
Simplify ensure_root_is_owned callers
This makes ensure_root_is_owned return a reference to the (now guaranteed to exist) root, allowing callers to operate on it without going through another unwrap. Unfortunately this is only rarely useful as it's frequently the case that both the length and the root need to be accessed and field-level borrows in methods don't yet exist.
1 parent 702758d commit 416fd43

File tree

1 file changed

+13
-15
lines changed
  • src/liballoc/collections/btree

1 file changed

+13
-15
lines changed

src/liballoc/collections/btree/map.rs

+13-15
Original file line numberDiff line numberDiff line change
@@ -170,13 +170,13 @@ impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
170170
}
171171
Internal(internal) => {
172172
let mut out_tree = clone_subtree(internal.first_edge().descend());
173-
174-
// Cannot call ensure_root_is_owned() because lacking K: Ord
175-
if out_tree.root.is_none() {
176-
out_tree.root = Some(node::Root::new_leaf());
177-
}
173+
out_tree.ensure_root_is_owned();
178174

179175
{
176+
// Ideally we'd use the return of ensure_root_is_owned
177+
// instead of re-unwrapping here but unfortunately that
178+
// borrows all of out_tree and we need access to the
179+
// length below.
180180
let mut out_node = out_tree.root.as_mut().unwrap().push_level();
181181
let mut in_edge = internal.first_edge();
182182
while let Ok(kv) = in_edge.right_kv() {
@@ -1207,9 +1207,9 @@ impl<K: Ord, V> BTreeMap<K, V> {
12071207
let total_num = self.len();
12081208

12091209
let mut right = Self::new();
1210-
right.root = Some(node::Root::new_leaf());
1210+
let right_root = right.ensure_root_is_owned();
12111211
for _ in 0..(self.root.as_ref().unwrap().as_ref().height()) {
1212-
right.root.as_mut().unwrap().push_level();
1212+
right_root.push_level();
12131213
}
12141214

12151215
{
@@ -1348,14 +1348,6 @@ impl<K: Ord, V> BTreeMap<K, V> {
13481348

13491349
self.fix_top();
13501350
}
1351-
1352-
/// If the root node is the empty (non-allocated) root node, allocate our
1353-
/// own node.
1354-
fn ensure_root_is_owned(&mut self) {
1355-
if self.root.is_none() {
1356-
self.root = Some(node::Root::new_leaf());
1357-
}
1358-
}
13591351
}
13601352

13611353
#[stable(feature = "rust1", since = "1.0.0")]
@@ -2151,6 +2143,12 @@ impl<K, V> BTreeMap<K, V> {
21512143
pub fn is_empty(&self) -> bool {
21522144
self.len() == 0
21532145
}
2146+
2147+
/// If the root node is the empty (non-allocated) root node, allocate our
2148+
/// own node.
2149+
fn ensure_root_is_owned(&mut self) -> &mut node::Root<K, V> {
2150+
self.root.get_or_insert_with(|| node::Root::new_leaf())
2151+
}
21542152
}
21552153

21562154
impl<'a, K: Ord, V> Entry<'a, K, V> {

0 commit comments

Comments
 (0)