Skip to content

Commit

Permalink
Auto merge of rust-lang#3028 - ttsugriy:range-map-find-offset, r=Ralf…
Browse files Browse the repository at this point in the history
…Jung

Replace hand-written binary search with Vec::binary_search_by.

It's similar to rust-lang/miri#3021 and should improve maintainability.
  • Loading branch information
bors committed Aug 16, 2023
2 parents e08baec + 0711c01 commit edc6fc1
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions src/tools/miri/src/range_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,21 @@ impl<T> RangeMap<T> {

/// Finds the index containing the given offset.
fn find_offset(&self, offset: u64) -> usize {
// We do a binary search.
let mut left = 0usize; // inclusive
let mut right = self.v.len(); // exclusive
loop {
debug_assert!(left < right, "find_offset: offset {offset} is out-of-bounds");
let candidate = left.checked_add(right).unwrap() / 2;
let elem = &self.v[candidate];
if offset < elem.range.start {
// We are too far right (offset is further left).
debug_assert!(candidate < right); // we are making progress
right = candidate;
} 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;
} else {
// This is it!
return candidate;
}
}
self.v
.binary_search_by(|elem| -> std::cmp::Ordering {
if offset < elem.range.start {
// We are too far right (offset is further left).
// (`Greater` means that `elem` is greater than the desired target.)
std::cmp::Ordering::Greater
} else if offset >= elem.range.end {
// We are too far left (offset is further right).
std::cmp::Ordering::Less
} else {
// This is it!
std::cmp::Ordering::Equal
}
})
.unwrap()
}

/// Provides read-only iteration over everything in the given range. This does
Expand Down

0 comments on commit edc6fc1

Please sign in to comment.