Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sorairolake opened this issue Nov 17, 2024 · 0 comments
Labels
A-lint Area: New lints

Comments

@sorairolake
Copy link

sorairolake commented Nov 17, 2024

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();
@sorairolake sorairolake added the A-lint Area: New lints label Nov 17, 2024
@sorairolake sorairolake changed the title Suggest to replace (x as {float}).log{|2|10}().floor() as {uint} with x.ilog{|2|10}() Suggest to replace x.log{|2|10}().floor() with x.ilog{|2|10}() Nov 18, 2024
@sorairolake sorairolake changed the title Suggest to replace x.log{|2|10}().floor() with x.ilog{|2|10}() Suggest to replace int_as_float.log{|2|10}().floor() as u32 with int.ilog{|2|10}() Nov 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

1 participant