about summary refs log tree commit diff
diff options
context:
space:
mode:
authorGuillaume Gomez <guillaume1.gomez@gmail.com>2021-02-17 20:38:04 +0100
committerGitHub <noreply@github.com>2021-02-17 20:38:04 +0100
commitf46bd72e5f4dccc51c3b3db27ffedb5d136e18cc (patch)
tree38ea7ffbd949d77720ef6a035b75e6e9676ce99b
parent8e6bc14f526b4edd2360393f72c8b9467ac62bc6 (diff)
parent61bb1836f8f2e72e9e92187cc763d0873d603b91 (diff)
Rollup merge of #82198 - SkiFire13:optimize-iter-is-sorted, r=sfackler
Use internal iteration in Iterator::is_sorted_by
-rw-r--r--library/core/src/iter/traits/iterator.rs25
1 files changed, 16 insertions, 9 deletions
diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs
index 5faa4b82560..a38b35a5b5c 100644
--- a/library/core/src/iter/traits/iterator.rs
+++ b/library/core/src/iter/traits/iterator.rs
@@ -3327,24 +3327,31 @@ pub trait Iterator {
     ///
     /// [`is_sorted`]: Iterator::is_sorted
     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
-    fn is_sorted_by<F>(mut self, mut compare: F) -> bool
+    fn is_sorted_by<F>(mut self, compare: F) -> bool
     where
         Self: Sized,
         F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
     {
+        #[inline]
+        fn check<'a, T>(
+            last: &'a mut T,
+            mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
+        ) -> impl FnMut(T) -> bool + 'a {
+            move |curr| {
+                if let Some(Ordering::Greater) | None = compare(&last, &curr) {
+                    return false;
+                }
+                *last = curr;
+                true
+            }
+        }
+
         let mut last = match self.next() {
             Some(e) => e,
             None => return true,
         };
 
-        while let Some(curr) = self.next() {
-            if let Some(Ordering::Greater) | None = compare(&last, &curr) {
-                return false;
-            }
-            last = curr;
-        }
-
-        true
+        self.all(check(&mut last, compare))
     }
 
     /// Checks if the elements of this iterator are sorted using the given key extraction