Skip to content

Commit

Permalink
Rollup merge of #82198 - SkiFire13:optimize-iter-is-sorted, r=sfackler
Browse files Browse the repository at this point in the history
Use internal iteration in Iterator::is_sorted_by
  • Loading branch information
Dylan-DPC committed Feb 17, 2021
2 parents 116f2e5 + 61bb183 commit 7bd07a5
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 7bd07a5

Please sign in to comment.