rust-lang / rust-lang/rust-clippy
Use count_ones()/.count_zeros() instead of loops
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
It suggests to replace a loop with the usage of pop count integer methods.
Lint Name
needless_popcount_loop
Category
perf
Advantage
Shorter, less bug-prone, faster, more explicit.
Drawbacks
Slower Clippy.
Example
I'm not sure if this is doable and reasonable, but I think Clippy could recognize basic popcount loops and suggest to replace them with count_ones()/.count_zeros():
fn foo1a(x: u32) -> usize {
(0 .. 32).filter(|i| x & (1 << i) != 0).count()
}
fn foo2a(x: u32) -> usize {
(0 .. 32).filter(|i| x & (1 << i) == 0).count()
}
Could be written as:
fn foo1b(x: u32) -> usize {
x.count_ones() as _
}
fn foo2b(x: u32) -> usize {
x.count_zeros() as _
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the proposed needless_popcount_loop lint and the Rust examples in the issue, including the count_ones() and count_zeros() replacements. Done means Clippy can recognize the described popcount loops and suggest the corresponding integer methods without changing unrelated code.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 52/100