rust-lang / rust-lang/rust-clippy

Suggest to replace `int_as_float.log{|2|10}().floor() as u32` with `int.ilog{|2|10}()`

Open
#13,699 1 comment 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

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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.