rust-lang / rust-lang/rust-clippy
Lint suggestion: `manual_isolate_highest_one`
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
Checks for manual implementations that returns x with only the most significant bit set, and suggests using x.isolate_highest_one() instead.
The isolate_highest_one method will be stabilized in Rust 1.97.0 and will be available for all signed and unsigned primitive integer types and NonZero<T> where T is any signed and unsigned primitive integer type.
Advantage
- Improve readability and clarity compared to manual implementations.
- Eliminate off-by-one errors for $x = 0$.
- Preserve non-zero type information by returning
NonZero<u32>instead ofu32forNonZero<T>.
Drawbacks
Requires MSRV 1.97.0.
Example
let x: u32 = 5;
// `31 == (u32::BITS - 1)`
let msb = x & ((1_u32 << 31).wrapping_shr(x.leading_zeros()));
let msb = if x == 0 {
0
} else {
1 << (31 - x.leading_zeros())
};
let x = NonZeroU32::new(5).unwrap();
// `31 == (NonZeroU32::BITS - 1)`
let msb = NonZeroU32::new(1 << (31 - x.leading_zeros())).unwrap();
Could be written as:
let x: u32 = 5;
let msb = x.isolate_highest_one();
let x = NonZeroU32::new(5).unwrap();
let msb = x.isolate_highest_one();
Comparison with existing lints
No response
Additional Context
No response
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 locating existing Clippy lint implementations for analogous bit-operation suggestions and their tests. Use the issue's examples to cover manual highest-bit isolation for signed and unsigned primitives and NonZero types, gated by MSRV 1.97.0; done means the lint suggests isolate_highest_one without off-by-one behavior for x = 0.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 68/100