rust-lang / rust-lang/rust-clippy
Recognize trailing_ones code patterns
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
Perhaps Clippy could spot code patterns like foo2() and suggest to replace that loop with trailing_ones() (and similar code for the other functions like trailing_zeros and leading_zeros):
fn foo1(x: usize) -> u32 {
x.trailing_ones()
}
fn foo2(mut x: usize) -> u32 {
let mut count = 0;
while x & 1 == 1 {
x >>= 1;
count += 1;
}
count
}
fn main() {
for i in 0 .. 1_000 {
assert_eq!(foo1(i), foo2(i));
}
}
In Rust code translated from C and C++ code I see many of such small loops (GCC has many functions like __builtin_clz(), but they are less portable so lot of people don't use them or don't remember to use them).
Lint Name
No response
Category
No response
Advantage
No response
Drawbacks
No response
Example
<code>
Could be written as:
<code>
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 with the Rust examples in the issue, especially the foo2 loop, and inspect how rust-clippy implements and tests similar pattern-recognition lints. The work is complete when equivalent loops are recognized and suggestions use trailing_ones(), trailing_zeros(), and leading_zeros() appropriately, with coverage for the shown behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100