Skip to content

Commit f46bd72

Browse files
Rollup merge of #82198 - SkiFire13:optimize-iter-is-sorted, r=sfackler
Use internal iteration in Iterator::is_sorted_by
2 parents 8e6bc14 + 61bb183 commit f46bd72

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
@@ -3327,24 +3327,31 @@ pub trait Iterator {
33273327
///
33283328
/// [`is_sorted`]: Iterator::is_sorted
33293329
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3330-
fn is_sorted_by<F>(mut self, mut compare: F) -> bool
3330+
fn is_sorted_by<F>(mut self, compare: F) -> bool
33313331
where
33323332
Self: Sized,
33333333
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
33343334
{
3335+
#[inline]
3336+
fn check<'a, T>(
3337+
last: &'a mut T,
3338+
mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3339+
) -> impl FnMut(T) -> bool + 'a {
3340+
move |curr| {
3341+
if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3342+
return false;
3343+
}
3344+
*last = curr;
3345+
true
3346+
}
3347+
}
3348+
33353349
let mut last = match self.next() {
33363350
Some(e) => e,
33373351
None => return true,
33383352
};
33393353

3340-
while let Some(curr) = self.next() {
3341-
if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3342-
return false;
3343-
}
3344-
last = curr;
3345-
}
3346-
3347-
true
3354+
self.all(check(&mut last, compare))
33483355
}
33493356

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

0 commit comments

Comments
 (0)