Skip to content

Commit 5139266

Browse files
committed
Auto merge of rust-lang#119599 - marthadev:position, r=<try>
Rewrite Iterator::position default impl Storing the accumulating value outside the fold in an attempt to improve code generation has shown speedups on various handwritten benchmarks, see discussion at rust-lang#119551.
2 parents a59a980 + fd33955 commit 5139266

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

library/core/src/iter/traits/iterator.rs

+13-6
Original file line numberDiff line numberDiff line change
@@ -3094,16 +3094,23 @@ pub trait Iterator {
30943094
P: FnMut(Self::Item) -> bool,
30953095
{
30963096
#[inline]
3097-
fn check<T>(
3098-
mut predicate: impl FnMut(T) -> bool,
3099-
) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3097+
fn check<'a, T>(
3098+
mut predicate: impl FnMut(T) -> bool + 'a,
3099+
acc: &'a mut usize,
3100+
) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
31003101
#[rustc_inherit_overflow_checks]
3101-
move |i, x| {
3102-
if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
3102+
move |_, x| {
3103+
if predicate(x) {
3104+
ControlFlow::Break(*acc)
3105+
} else {
3106+
*acc += 1;
3107+
ControlFlow::Continue(())
3108+
}
31033109
}
31043110
}
31053111

3106-
self.try_fold(0, check(predicate)).break_value()
3112+
let mut acc = 0;
3113+
self.try_fold((), check(predicate, &mut acc)).break_value()
31073114
}
31083115

31093116
/// Searches for an element in an iterator from the right, returning its

0 commit comments

Comments
 (0)