Auto merge of #85406 - VillSnow:integrate_binary_search, r=JohnTitor

Integrate binary search codes of binary_search_by and partition_point

For now partition_point has own binary search code piece.
It is because binary_search_by had called the comparer more times and the author (=me) wanted to avoid it.

However, now binary_search_by uses the comparer minimum times. (#74024)
So it's time to integrate them.

The appearance of the codes are a bit different but both use completely same logic.
This commit is contained in:
bors 2021-06-15 22:56:41 +00:00
commit 684ca335d5

View File

@ -3468,27 +3468,7 @@ impl<T> [T] {
where
P: FnMut(&T) -> bool,
{
let mut left = 0;
let mut right = self.len();
while left != right {
let mid = left + (right - left) / 2;
// SAFETY: When `left < right`, `left <= mid < right`.
// Therefore `left` always increases and `right` always decreases,
// and either of them is selected. In both cases `left <= right` is
// satisfied. Therefore if `left < right` in a step, `left <= right`
// is satisfied in the next step. Therefore as long as `left != right`,
// `0 <= left < right <= len` is satisfied and if this case
// `0 <= mid < len` is satisfied too.
let value = unsafe { self.get_unchecked(mid) };
if pred(value) {
left = mid + 1;
} else {
right = mid;
}
}
left
self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
}
}