rust-lang / rust-lang/rust-clippy
Suggest to replace `int_as_float.log{|2|10}().floor() as u32` with `int.ilog{|2|10}()`
Open
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
Search for redundant $\lfloor \log_b n \rfloor$ for a integer $n$.
- $\lfloor \log_5 25 \rfloor$ can be written as
25_i32.ilog(5)instead of(25_i32 as f64).log(5.0).floor() as u32. - $\lfloor \log_2 8 \rfloor$ can be written as
8_i32.ilog2()instead of(8_i32 as f64).log2().floor() as u32. - $\lfloor \log_{10} 100 \rfloor$ can be written as
100_i32.ilog10()instead of(100_i32 as f64).log10().floor() as u32.
ilog{|2|10} are const fn, but log{|2|10} and floor are not.
const A: u32 = (8_i32 as f64).log2().floor() as u32; // compilation error
const B: u32 = 8_i32.ilog2(); // ok
Advantage
- Simplify.
- Can be used in the const contexts.
Drawbacks
MSRV is 1.67.0.
Example
let x: i32 = 42;
let a = (x as f64).log(42.0).floor() as u32;
let b = (x as f64).log2().floor() as u32;
let c = (x as f64).log10().floor() as u32;
Could be written as:
let x: i32 = 42;
let a = x.ilog(42);
let b = x.ilog2();
let c = x.ilog10();
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 searching the rust-clippy lint implementations and tests for existing numeric-expression lints and the patterns shown in the issue. Define completion as recognizing the redundant log-and-floor forms, suggesting the corresponding ilog, ilog2, or ilog10 call, and covering the examples and const-context motivation with tests.
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