Skip to content
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

Add partition_point #73577

Merged
merged 10 commits into from
Jun 28, 2020
38 changes: 38 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2663,6 +2663,44 @@ impl<T> [T] {
{
self.iter().is_sorted_by_key(f)
}

/// Returns index of partition point according to the given predicate,
/// such that all those that return true precede the index and
/// such that all those that return false succeed the index.
///
/// 'self' must be partitioned.
Amanieu marked this conversation as resolved.
Show resolved Hide resolved
///
/// # Examples
///
/// ```
/// #![feature(partition_point)]
///
/// let v = [1, 2, 3, 3, 5, 6, 7];
/// let i = v.partition_point(|&x| x < 5);
///
/// assert_eq!(i, 4);
/// assert!(v[..i].iter().all(|&x| x < 5));
/// assert!(v[i..].iter().all(|&x| !(x < 5)));
/// ```
#[unstable(feature = "partition_point", reason = "new API", issue = "99999")]
pub fn partition_point<P>(&self, mut pred: P) -> usize
where
P: FnMut(&T) -> bool,
{
let mut left = 0;
let mut right = self.len();

while left != right {
let mid = left + (right - left) / 2;
let value = unsafe { self.get_unchecked(mid) };
Copy link
Member

Choose a reason for hiding this comment

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

Please add a comment about why this unsafe is fine. You can probably take the text from binary_search. Also see #66219 (let the comment start with // SAFETY:).

if pred(value) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
VillSnow marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[lang = "slice_u8"]
Expand Down