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

u8::max as usize instead of u8::MAX as usize should warn #13973

Open
theemathas opened this issue Jan 9, 2025 · 2 comments · May be fixed by #13979
Open

u8::max as usize instead of u8::MAX as usize should warn #13973

theemathas opened this issue Jan 9, 2025 · 2 comments · May be fixed by #13979
Labels
A-lint Area: New lints

Comments

@theemathas
Copy link
Contributor

What it does

It should warn on code like u8::max as usize, or similar code with min or with other integer types.

Advantage

u8::MAX is a constant equal to 2^8-1. u8::MAX as usize casts that value to a larger integer size.

u8::max is a function that takes two u8 values and returns the larger one. u8::max as usize takes the address of that function, which is almost certainly not intended.

Drawbacks

No response

Example

u8::max as usize

Could be written as:

u8::MAX as usize
@theemathas theemathas added the A-lint Area: New lints label Jan 9, 2025
@dennisjackson
Copy link

dennisjackson commented Jan 10, 2025

Example code which triggers the assert, but emits no warnings from Cargo or Clippy in pedantic mode:

#[deny(clippy::pedantic)]
pub fn main() {
    let x: usize = 65_535;

    // Should be u16::MAX
    if x < u16::max as usize {
        println!("fits in a u16!");
        assert!(x < 65_535);
    } else {
        println!("Too big!");
    }
}

Although clippy::fn_to_numeric_cast_any will catch this mistake, it's not enabled in pedantic mode and will flag all other uses where function pointers are converted to integers.

Possible solutions:

  • Enable clippy::fn_to_numeric_cast_any by default for the special case of standard library functions where associated constants and functions are lookalikes.
  • Warn when function pointers are cast to usize in a non-equality comparison.

@GuillaumeGomez
Copy link
Member

I don't think we can make fn_to_numeric_cast_any to be emitted in some special cases. Its category cannot be changed at runtime.

I think in this case, the best might be a specialized new lint. Something like primitive_method_to_numeric_cast.

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

Successfully merging a pull request may close this issue.

3 participants