Skip to content

Commit

Permalink
Auto merge of #62473 - timvermeulen:is_sorted_by_key, r=scottmcm
Browse files Browse the repository at this point in the history
Only call the closure parameter of Iterator::is_sorted_by_key once per item

See #53485 (comment).

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.
  • Loading branch information
bors committed Jul 8, 2019
2 parents 10840b8 + 98b54fb commit 78ca1bd
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/libcore/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down

0 comments on commit 78ca1bd

Please sign in to comment.