rust-lang / rust-lang/rust-clippy
Lint suggestion: `manual_highest_one`
Open
@qdot3 is already working on this.
Since Jul 30, 2026.
A-lint
- 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 the index of the highest bit set to one in x, and suggests using x.highest_one() instead.
The 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 the overflow when
xiszero.
Drawbacks
Requires MSRV 1.97.0.
Example
let x: u32 = 5;
// `31 == (u32::BITS - 1)`
let index = 31 - x.leading_zeros();
let index = if x == 0 {
None
} else {
Some(31 - x.leading_zeros())
};
let x = NonZeroU32::new(5).unwrap();
// `31 == (NonZeroU32::BITS - 1)`
let index = 31 - x.leading_zeros();
Could be written as:
let x: u32 = 5;
let index = x.highest_one().unwrap();
let index = x.highest_one();
let x = NonZeroU32::new(5).unwrap();
let index = x.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.
Assessment
This issue has not been assessed yet.