Skip to content

Commit

Permalink
Auto merge of rust-lang#119599 - marthadev:position, r=the8472
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bors committed Jan 6, 2024
2 parents b6a8c76 + 0e9c3d9 commit fde0e98
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3094,16 +3094,23 @@ pub trait Iterator {
P: FnMut(Self::Item) -> bool,
{
#[inline]
fn check<T>(
mut predicate: impl FnMut(T) -> bool,
) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
fn check<'a, T>(
mut predicate: impl FnMut(T) -> bool + 'a,
acc: &'a mut usize,
) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
#[rustc_inherit_overflow_checks]
move |i, x| {
if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
move |_, x| {
if predicate(x) {
ControlFlow::Break(*acc)
} else {
*acc += 1;
ControlFlow::Continue(())
}
}
}

self.try_fold(0, check(predicate)).break_value()
let mut acc = 0;
self.try_fold((), check(predicate, &mut acc)).break_value()
}

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

0 comments on commit fde0e98

Please sign in to comment.