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

More slice::partition_point examples #102507

Merged
merged 1 commit into from
Oct 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2359,6 +2359,28 @@ impl<T> [T] {
/// assert!(match r { Ok(1..=4) => true, _ => false, });
/// ```
///
/// If you want to find that whole *range* of matching items, rather than
/// an arbitrary matching one, that can be done using [`partition_point`]:
/// ```
/// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
///
/// let low = s.partition_point(|x| x < &1);
/// assert_eq!(low, 1);
/// let high = s.partition_point(|x| x <= &1);
/// assert_eq!(high, 5);
/// let r = s.binary_search(&1);
/// assert!((low..high).contains(&r.unwrap()));
///
/// assert!(s[..low].iter().all(|&x| x < 1));
/// assert!(s[low..high].iter().all(|&x| x == 1));
/// assert!(s[high..].iter().all(|&x| x > 1));
///
/// // For something not found, the "range" of equal items is empty
/// assert_eq!(s.partition_point(|x| x < &11), 9);
/// assert_eq!(s.partition_point(|x| x <= &11), 9);
/// assert_eq!(s.binary_search(&11), Err(9));
/// ```
///
/// If you want to insert an item to a sorted vector, while maintaining
/// sort order, consider using [`partition_point`]:
///
Expand Down Expand Up @@ -3778,6 +3800,16 @@ impl<T> [T] {
/// assert!(v[i..].iter().all(|&x| !(x < 5)));
/// ```
///
/// If all elements of the slice match the predicate, including if the slice
/// is empty, then the length of the slice will be returned:
///
/// ```
/// let a = [2, 4, 8];
/// assert_eq!(a.partition_point(|x| x < &100), a.len());
/// let a: [i32; 0] = [];
/// assert_eq!(a.partition_point(|x| x < &100), 0);
/// ```
///
/// If you want to insert an item to a sorted vector, while maintaining
/// sort order:
///
Expand Down