Auto merge of #62473 - timvermeulen:is_sorted_by_key, r=scottmcm

Only call the closure parameter of Iterator::is_sorted_by_key once per item

See https://github.com/rust-lang/rust/issues/53485#issuecomment-472314004.

This changes `Iterator::is_sorted_by_key` to only call the given closure once for each item, which allows us to pass the items to the closure by value instead of by reference.

**Important**: `is_sorted_by_key` for slices and slice iterators is now no longer implemented in terms of the custom `slice::Iter::is_sorted_by` implementation. It's a trade-off: we could forward `slice::Iter::is_sorted_by_key` to it directly for potential SIMD benefits, but that would mean that the closure is potentially called twice for (almost) every element of the slice.
This commit is contained in:
bors 2019-07-08 12:03:06 +00:00
commit 78ca1bda35
2 changed files with 5 additions and 5 deletions

View file

@ -2572,13 +2572,13 @@ pub trait Iterator {
/// ```
#[inline]
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
fn is_sorted_by_key<F, K>(self, mut f: F) -> bool
fn is_sorted_by_key<F, K>(self, f: F) -> bool
where
Self: Sized,
F: FnMut(&Self::Item) -> K,
F: FnMut(Self::Item) -> K,
K: PartialOrd
{
self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
self.map(f).is_sorted()
}
}

View file

@ -2459,12 +2459,12 @@ impl<T> [T] {
/// ```
#[inline]
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
pub fn is_sorted_by_key<F, K>(&self, mut f: F) -> bool
pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
where
F: FnMut(&T) -> K,
K: PartialOrd
{
self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
self.iter().is_sorted_by_key(f)
}
}