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

New lint that suggests the use of mixed type operations like wrapping_sub_unsigned #13715

Open
leonardo-m opened this issue Nov 21, 2024 · 1 comment
Labels
A-lint Area: New lints

Comments

@leonardo-m
Copy link

What it does

Suggests to replace code that contains an as cast, with specialized functions from the std library.

Advantage

Makes the intent more explicit.

Drawbacks

Slightly longer code.

Example

#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![warn(clippy::style)]
fn main() {
    let a = 1_i64;
    let b = 2_u64;
    let c = 2_u32;
    let x = a - (b as i64);
    let y = a.wrapping_sub_unsigned(b);
    let z = a.wrapping_sub_unsigned(u64::from(c));
    println!("{x:?} {y:?} {z:?}");
}

This code gives a clippy::cast_possible_wrap warning on the (b as i64) part, but I think it should suggest to replace code like in the computation of x, with the code that computes y. Similar suggestions could be used for other mixed-type operations.

@leonardo-m leonardo-m added the A-lint Area: New lints label Nov 21, 2024
@ojeda
Copy link
Contributor

ojeda commented Nov 26, 2024

a - (b as i64) is not equivalent, since it may panic.

Should the example say a.wrapping_sub(b as i64) instead?

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

2 participants