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

manual_unsigned_abs #13786

Open
owenthewizard opened this issue Dec 6, 2024 · 3 comments
Open

manual_unsigned_abs #13786

owenthewizard opened this issue Dec 6, 2024 · 3 comments
Labels
A-lint Area: New lints

Comments

@owenthewizard
Copy link

owenthewizard commented Dec 6, 2024

What it does

Replace -{signed} as {unsigned} with {signed}.unsigned_abs()

Advantage

Clear and concise meaning & order of operations.
No panics or overflow (potentially).

Drawbacks

No response

Example

let n: isize = -42;
-n as usize

Could be written as:

let n: isize = -42;
n.unsigned_abs()
@owenthewizard owenthewizard added the A-lint Area: New lints label Dec 6, 2024
@owenthewizard owenthewizard changed the title manual_abs_unsigned manual_unsigned_abs Dec 6, 2024
@samueltardieu
Copy link
Contributor

The example works only because n is negative. Should n be positive, the result would not be the same at all.

If you are thinking about n.abs() as usize, this is already handled by the CAST_ABS_TO_UNSIGNED lint.

@owenthewizard
Copy link
Author

The example works only because n is negative. Should n be positive, the result would not be the same at all.

If you are thinking about n.abs() as usize, this is already handled by the CAST_ABS_TO_UNSIGNED lint.

Yeah, I accidentally omitted it from my example but in my code I had this:

let n: isize = -42;
if n.is_negative() {
    -n as usize
}

@samueltardieu
Copy link
Contributor

samueltardieu commented Dec 12, 2024

Others might disagree, but I feel this is very specific (-n as … following is_negative() or < 0 or <= 0). Do you have evidence of this happening in the wild? I couldn't find code with this pattern.

Or maybe we could include it in a more general lint manual_abs which would also detect the same thing without as ….

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