rust-lang / rust-lang/rust-clippy

Lint suggestion: `manual_isolate_highest_one`

Open
#16,984 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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 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 of u32 for NonZero<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

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.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.