Skip to content

Commit 61bb183

Browse files
committed
Optimize Iterator::is_sorted_by by using Iterator::all for internal iteration
1 parent fee0d31 commit 61bb183

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

Diff for: library/core/src/iter/traits/iterator.rs

+16-9
Original file line numberDiff line numberDiff line change
@@ -3317,24 +3317,31 @@ pub trait Iterator {
33173317
///
33183318
/// [`is_sorted`]: Iterator::is_sorted
33193319
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3320-
fn is_sorted_by<F>(mut self, mut compare: F) -> bool
3320+
fn is_sorted_by<F>(mut self, compare: F) -> bool
33213321
where
33223322
Self: Sized,
33233323
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
33243324
{
3325+
#[inline]
3326+
fn check<'a, T>(
3327+
last: &'a mut T,
3328+
mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3329+
) -> impl FnMut(T) -> bool + 'a {
3330+
move |curr| {
3331+
if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3332+
return false;
3333+
}
3334+
*last = curr;
3335+
true
3336+
}
3337+
}
3338+
33253339
let mut last = match self.next() {
33263340
Some(e) => e,
33273341
None => return true,
33283342
};
33293343

3330-
while let Some(curr) = self.next() {
3331-
if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3332-
return false;
3333-
}
3334-
last = curr;
3335-
}
3336-
3337-
true
3344+
self.all(check(&mut last, compare))
33383345
}
33393346

33403347
/// Checks if the elements of this iterator are sorted using the given key extraction

0 commit comments

Comments
 (0)