Skip to content

BTreeMap: bundle the duplication of node references in navigate.rs #81332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions library/alloc/src/collections/btree/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,16 @@ fn full_range<BorrowType, K, V>(
}
}

impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
/// Duplicates a NodeRef, even for a non-immutable borrow type.
/// # Safety
/// Never visit the same KV twice, and never end up with overlapping
/// value references.
unsafe fn fork(self) -> (Self, Self) {
unsafe { (ptr::read(&self), self) }
}
}

impl<'a, K: 'a, V: 'a> NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal> {
/// Creates a pair of leaf edges delimiting a specified range in or underneath a node.
///
Expand Down Expand Up @@ -180,10 +190,8 @@ impl<'a, K: 'a, V: 'a> NodeRef<marker::ValMut<'a>, K, V, marker::LeafOrInternal>
K: Borrow<Q>,
R: RangeBounds<Q>,
{
// We duplicate the root NodeRef here -- we will never visit the same KV
// twice, and never end up with overlapping value references.
let self2 = unsafe { ptr::read(&self) };
range_search(self, self2, range)
let (self1, self2) = unsafe { self.fork() };
range_search(self1, self2, range)
}

/// Splits a unique reference into a pair of leaf edges delimiting the full range of the tree.
Expand All @@ -195,10 +203,8 @@ impl<'a, K: 'a, V: 'a> NodeRef<marker::ValMut<'a>, K, V, marker::LeafOrInternal>
Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>,
Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>,
) {
// We duplicate the root NodeRef here -- we will never visit the same KV
// twice, and never end up with overlapping value references.
let self2 = unsafe { ptr::read(&self) };
full_range(self, self2)
let (self1, self2) = unsafe { self.fork() };
full_range(self1, self2)
}
}

Expand All @@ -212,10 +218,8 @@ impl<K, V> NodeRef<marker::Owned, K, V, marker::LeafOrInternal> {
Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
) {
// We duplicate the root NodeRef here -- we will never access it in a way
// that overlaps references obtained from the root.
let self2 = unsafe { ptr::read(&self) };
full_range(self, self2)
let (self1, self2) = unsafe { self.fork() };
full_range(self1, self2)
}
}

Expand Down