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 saturating_sub for if i != 0 { i -= 1; } #5399

Closed
Luro02 opened this issue Apr 1, 2020 · 3 comments · Fixed by #5427
Closed

Suggest saturating_sub for if i != 0 { i -= 1; } #5399

Luro02 opened this issue Apr 1, 2020 · 3 comments · Fixed by #5427
Labels
A-lint Area: New lints L-style Lint: Belongs in the style lint group L-suggestion Lint: Improving, adding or fixing lint suggestions

Comments

@Luro02
Copy link

Luro02 commented Apr 1, 2020

#![warn(clippy::all)]

fn main() {
    let end = 10;
    let start = 5;
    
    let mut i = end - start;
    
    if i != 0 {
        i -= 1;
    }
    
    println!("i: {}", i);
}

could be optimized to

#![warn(clippy::all)]

fn main() {
    let end = 10;
    let start = 5;
    
    let mut i = (end - start).saturating_sub(1);

    println!("i: {}", i);
}
@flip1995
Copy link
Member

flip1995 commented Apr 1, 2020

The example is only correct for unsigned types. But this could also be implemented for signed types.

@flip1995 flip1995 added L-style Lint: Belongs in the style lint group L-suggestion Lint: Improving, adding or fixing lint suggestions A-lint Area: New lints labels Apr 1, 2020
@pmk21
Copy link
Contributor

pmk21 commented Apr 4, 2020

Never written a lint before. Could I take a shot at this?

@flip1995
Copy link
Member

flip1995 commented Apr 4, 2020

Yeah, sure! Here's a document on how to get started writing new lints: https://github.com/rust-lang/rust-clippy/blob/master/doc/adding_lints.md. I you have any questions, just ask here or open a WIP PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints L-style Lint: Belongs in the style lint group L-suggestion Lint: Improving, adding or fixing lint suggestions
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants