about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2022-10-18 21:18:46 +0200
committerGitHub <noreply@github.com>2022-10-18 21:18:46 +0200
commit18431b66ce68a58d3dde2c7143a6e6bfb08cae60 (patch)
tree325967d83f6589806040ade7a5c755adf65852ff
parentd2644e538ccbf99e6aea79f60de3449e5c90c3d5 (diff)
parent5b9a02a87d8f8b384ea45a0fd2a7bcc57b810986 (diff)
downloadrust-18431b66ce68a58d3dde2c7143a6e6bfb08cae60.tar.gz
rust-18431b66ce68a58d3dde2c7143a6e6bfb08cae60.zip
Rollup merge of #102507 - scottmcm:more-binary-search-docs, r=m-ou-se
More slice::partition_point examples

After seeing the discussion of `binary_search` vs `partition_point` in #101999, I thought some more example code could be helpful.
-rw-r--r--library/core/src/slice/mod.rs32
1 files changed, 32 insertions, 0 deletions
diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs
index 56133f346ae..5f1a05706f2 100644
--- a/library/core/src/slice/mod.rs
+++ b/library/core/src/slice/mod.rs
@@ -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`]:
     ///
@@ -3787,6 +3809,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:
     ///