Replace hand-written binary search with Vec::binary_search_by.
It's similar to https://github.com/rust-lang/miri/pull/3021 and should improve maintainability.
This commit is contained in:
parent
5b9168a32d
commit
0711c01709
1 changed files with 15 additions and 20 deletions
|
@ -36,26 +36,21 @@ impl<T> RangeMap<T> {
|
||||||
|
|
||||||
/// Finds the index containing the given offset.
|
/// Finds the index containing the given offset.
|
||||||
fn find_offset(&self, offset: u64) -> usize {
|
fn find_offset(&self, offset: u64) -> usize {
|
||||||
// We do a binary search.
|
self.v
|
||||||
let mut left = 0usize; // inclusive
|
.binary_search_by(|elem| -> std::cmp::Ordering {
|
||||||
let mut right = self.v.len(); // exclusive
|
if offset < elem.range.start {
|
||||||
loop {
|
// We are too far right (offset is further left).
|
||||||
debug_assert!(left < right, "find_offset: offset {offset} is out-of-bounds");
|
// (`Greater` means that `elem` is greater than the desired target.)
|
||||||
let candidate = left.checked_add(right).unwrap() / 2;
|
std::cmp::Ordering::Greater
|
||||||
let elem = &self.v[candidate];
|
} else if offset >= elem.range.end {
|
||||||
if offset < elem.range.start {
|
// We are too far left (offset is further right).
|
||||||
// We are too far right (offset is further left).
|
std::cmp::Ordering::Less
|
||||||
debug_assert!(candidate < right); // we are making progress
|
} else {
|
||||||
right = candidate;
|
// This is it!
|
||||||
} else if offset >= elem.range.end {
|
std::cmp::Ordering::Equal
|
||||||
// We are too far left (offset is further right).
|
}
|
||||||
debug_assert!(candidate >= left); // we are making progress
|
})
|
||||||
left = candidate + 1;
|
.unwrap()
|
||||||
} else {
|
|
||||||
// This is it!
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Provides read-only iteration over everything in the given range. This does
|
/// Provides read-only iteration over everything in the given range. This does
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue