rust-lang / rust-lang/rust-clippy

Lint suggestion: `manual_highest_one`

Open
#16,985 1 comment 0 reactions 1 assignee View on GitHub

@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 x is zero.
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.