Rollup merge of #82198 - SkiFire13:optimize-iter-is-sorted, r=sfackler
Use internal iteration in Iterator::is_sorted_by
This commit is contained in:
commit
f46bd72e5f
1 changed files with 16 additions and 9 deletions
|
@ -3327,24 +3327,31 @@ pub trait Iterator {
|
||||||
///
|
///
|
||||||
/// [`is_sorted`]: Iterator::is_sorted
|
/// [`is_sorted`]: Iterator::is_sorted
|
||||||
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
|
#[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
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
|
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() {
|
let mut last = match self.next() {
|
||||||
Some(e) => e,
|
Some(e) => e,
|
||||||
None => return true,
|
None => return true,
|
||||||
};
|
};
|
||||||
|
|
||||||
while let Some(curr) = self.next() {
|
self.all(check(&mut last, compare))
|
||||||
if let Some(Ordering::Greater) | None = compare(&last, &curr) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
last = curr;
|
|
||||||
}
|
|
||||||
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks if the elements of this iterator are sorted using the given key extraction
|
/// Checks if the elements of this iterator are sorted using the given key extraction
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue