Skip to content

Commit

Permalink
Rollup merge of #105641 - Amanieu:btree_cursor, r=m-ou-se
Browse files Browse the repository at this point in the history
Implement cursors for BTreeMap

See the ACP for an overview of the API: rust-lang/libs-team#141

The implementation is split into 2 commits:
- The first changes the internal insertion functions to return a handle to the newly inserted element. The lifetimes involved are a bit hairy since we need a mutable handle to both the `BTreeMap` itself (which holds the root) and the nodes allocated in memory. I have tested that this passes the standard library testsuite under miri.
- The second commit implements the cursor API itself. This is more straightforward to follow but still involves some unsafe code to deal with simultaneous mutable borrows of the tree root and the node that is currently being iterated.
  • Loading branch information
matthiaskrgr authored Feb 8, 2023
2 parents a00e24d + 36831b3 commit 562581c
Show file tree
Hide file tree
Showing 6 changed files with 957 additions and 41 deletions.
22 changes: 22 additions & 0 deletions library/alloc/src/collections/btree/borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,28 @@ impl<'a, T> DormantMutRef<'a, T> {
// SAFETY: our own safety conditions imply this reference is again unique.
unsafe { &mut *self.ptr.as_ptr() }
}

/// Borrows a new mutable reference from the unique borrow initially captured.
///
/// # Safety
///
/// The reborrow must have ended, i.e., the reference returned by `new` and
/// all pointers and references derived from it, must not be used anymore.
pub unsafe fn reborrow(&mut self) -> &'a mut T {
// SAFETY: our own safety conditions imply this reference is again unique.
unsafe { &mut *self.ptr.as_ptr() }
}

/// Borrows a new shared reference from the unique borrow initially captured.
///
/// # Safety
///
/// The reborrow must have ended, i.e., the reference returned by `new` and
/// all pointers and references derived from it, must not be used anymore.
pub unsafe fn reborrow_shared(&self) -> &'a T {
// SAFETY: our own safety conditions imply this reference is again unique.
unsafe { &*self.ptr.as_ptr() }
}
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit 562581c

Please sign in to comment.