Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

branchless .filter(_).count() #39107

Merged
merged 4 commits into from
Feb 5, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/libcore/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1099,6 +1099,16 @@ impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}

#[inline]
fn count(self) -> usize {
let (mut c, mut predicate, mut iter) = (0, self.predicate, self.iter);
for x in iter.by_ref() {
// branchless count
c += (&mut predicate)(&x) as usize;
}
c
Copy link
Member

@bluss bluss Jan 17, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe one doesn't want to argue style for trivial things, but I find the code cramped when simple should work well:

fn count(mut self) -> usize {
    // Attempt to produce branchless count if possible
    let mut count = 0;
    for elt in self.iter {
        count += (self.predicate)(&elt) as usize;
    }
    count
}

The surrounding methods use .by_ref() which seems archaic (just &mut self.iter would be fine if mutable reference only was required)

Copy link
Contributor Author

@llogiq llogiq Jan 17, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, will change shortly (perhaps also change the other methods en passant).

}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down