From 93839c3fb4e3a3c3341595ac8dc2c7f4e39326d2 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Sat, 10 Aug 2019 16:31:38 +0000 Subject: [PATCH 1/2] Add an example to show how to insert item to a sorted vec --- src/libcore/slice/mod.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index d5a34ea2bd5a1..29afc43599620 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -1364,6 +1364,20 @@ impl [T] { /// let r = s.binary_search(&1); /// assert!(match r { Ok(1..=4) => true, _ => false, }); /// ``` + /// + /// If you want to insert an item to a sorted vector, while maintaining + /// sort order: + /// + /// ``` + /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let num = 42; + /// let idx = match s.binary_search(&num) { + /// Ok(idx) => idx, + /// Err(idx) => idx, + /// }; + /// s.insert(idx, num); + /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn binary_search(&self, x: &T) -> Result where T: Ord From 30ba4bd8e2da15ce8e2fe3c8fbc339ee67cb3241 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Sat, 10 Aug 2019 17:16:58 +0000 Subject: [PATCH 2/2] Use Result::unwrap_or_else instead of matching --- src/libcore/slice/mod.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 29afc43599620..ce5af13d4ca90 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -1371,10 +1371,7 @@ impl [T] { /// ``` /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; /// let num = 42; - /// let idx = match s.binary_search(&num) { - /// Ok(idx) => idx, - /// Err(idx) => idx, - /// }; + /// let idx = s.binary_search(&num).unwrap_or_else(|x| x); /// s.insert(idx, num); /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); /// ```