Skip to content

Commit 78ca1bd

Browse files
committed
Auto merge of rust-lang#62473 - timvermeulen:is_sorted_by_key, r=scottmcm
Only call the closure parameter of Iterator::is_sorted_by_key once per item See rust-lang#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.
2 parents 10840b8 + 98b54fb commit 78ca1bd

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

src/libcore/iter/traits/iterator.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2572,13 +2572,13 @@ pub trait Iterator {
25722572
/// ```
25732573
#[inline]
25742574
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2575-
fn is_sorted_by_key<F, K>(self, mut f: F) -> bool
2575+
fn is_sorted_by_key<F, K>(self, f: F) -> bool
25762576
where
25772577
Self: Sized,
2578-
F: FnMut(&Self::Item) -> K,
2578+
F: FnMut(Self::Item) -> K,
25792579
K: PartialOrd
25802580
{
2581-
self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2581+
self.map(f).is_sorted()
25822582
}
25832583
}
25842584

src/libcore/slice/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2459,12 +2459,12 @@ impl<T> [T] {
24592459
/// ```
24602460
#[inline]
24612461
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2462-
pub fn is_sorted_by_key<F, K>(&self, mut f: F) -> bool
2462+
pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
24632463
where
24642464
F: FnMut(&T) -> K,
24652465
K: PartialOrd
24662466
{
2467-
self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2467+
self.iter().is_sorted_by_key(f)
24682468
}
24692469
}
24702470

0 commit comments

Comments
 (0)