Skip to content

Use Vec's binary search instead of hand-written one. #3021

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

Merged
merged 2 commits into from
Aug 9, 2023
Merged
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
23 changes: 6 additions & 17 deletions src/concurrency/range_object_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,30 +42,19 @@ impl<T> RangeObjectMap<T> {
/// in an existing allocation, then returns Err containing the position
/// where such allocation should be inserted
fn find_offset(&self, offset: Size) -> Result<Position, Position> {
// We do a binary search.
let mut left = 0usize; // inclusive
let mut right = self.v.len(); // exclusive
loop {
if left == right {
// No element contains the given offset. But the
// position is where such element should be placed at.
return Err(left);
}
let candidate = left.checked_add(right).unwrap() / 2;
let elem = &self.v[candidate];
self.v.binary_search_by(|elem| -> std::cmp::Ordering {
if offset < elem.range.start {
// We are too far right (offset is further left).
debug_assert!(candidate < right); // we are making progress
right = candidate;
// (`Greater` means that `elem` is greater than the desired target.)
std::cmp::Ordering::Greater
Copy link
Member

@RalfJung RalfJung Aug 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please preserve the comments inside the ifs here, they still seem helpful.

Also have the comment explain that Greater indicates "elem is greater than desired target".

} else if offset >= elem.range.end() {
// We are too far left (offset is further right).
debug_assert!(candidate >= left); // we are making progress
left = candidate + 1;
std::cmp::Ordering::Less
} else {
// This is it!
return Ok(candidate);
std::cmp::Ordering::Equal
}
}
})
}

/// Determines whether a given access on `range` overlaps with
Expand Down