Skip to content

Commit 4c8ce48

Browse files
committed
Add partition_point
1 parent 2d8bd9b commit 4c8ce48

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/libcore/slice/mod.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2663,6 +2663,44 @@ impl<T> [T] {
26632663
{
26642664
self.iter().is_sorted_by_key(f)
26652665
}
2666+
2667+
/// Returns index of partition point according to the given predicate,
2668+
/// such that all those that return true precede the index and
2669+
/// such that all those that return false succeed the index.
2670+
///
2671+
/// 'self' must be partitioned.
2672+
///
2673+
/// # Examples
2674+
///
2675+
/// ```
2676+
/// #![feature(partition_point)]
2677+
///
2678+
/// let v = [1, 2, 3, 3, 5, 6, 7];
2679+
/// let i = xs.partition_point(|&x| x < 5);
2680+
///
2681+
/// assert_eq!(i, 4);
2682+
/// assert!(xs[..i].iter().all(|&x| x < 5));
2683+
/// assert!(xs[i..].iter().all(|&x| !(x < 5)));
2684+
/// ```
2685+
#[unstable(feature = "partition_point", reason = "new API", issue = "99999")]
2686+
pub fn partition_point<P>(&self, mut pred: P) -> usize
2687+
where
2688+
P: FnMut(&T) -> bool,
2689+
{
2690+
let mut left = 0;
2691+
let mut right = self.len();
2692+
2693+
while left != right {
2694+
let mid = left + (right - left) / 2;
2695+
let value = unsafe { self.get_unchecked(mid) };
2696+
if pred(value) {
2697+
left = mid + 1;
2698+
} else {
2699+
right = mid;
2700+
}
2701+
}
2702+
return left;
2703+
}
26662704
}
26672705

26682706
#[lang = "slice_u8"]

0 commit comments

Comments
 (0)