-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
integer_arithmetic
and arithmetic_side_effects
trigger on user-defined types
#11220
Comments
There needs to be some way to tell Clippy that a custom arithmetic implementation is safe. Perhaps something like #![warn(clippy::arithmetic_side_effects)]
use core::ops::Add;
pub struct MyNewtype(pub u64);
pub struct Error;
#[clippy::has_safe_arith]
impl Add for MyNewtype {
type Output = Result<Self, Error>;
fn add(self, other: Self) -> Result<Self, Error> {
self.0
.checked_add(other.0)
.map(Self)
.ok_or(Error)
}
}
pub fn example(a: MyNewtype, b: MyNewtype) -> Result<MyNewtype, Error> {
a + b // OK
} If the team is willing to accept such change, I can create a PR. |
It might be nice if the attribute for "blessing" an arithmetic operation as safe ala That lint is designed to find usages of division and remainder which may be problematic in a cryptographic context, but it's possible for user-defined types to have a "safe" Of course, if you don't want to collude the two either, that's fine, and such types can be annotated twice for the two different lints. |
There is a configuration variable for this, but it would be useful if the implementer could control whether the warning is triggered or not, as suggested in #11220 (comment). https://rust-lang.github.io/rust-clippy/master/index.html#/arithmetic_side_effects
|
Summary
As of Rust 1.71,
integer_arithmetic
started warning for arithmetic operations on user-defined types. On Rust 1.70 and earlier it did not. As far as I can tell, on earlier versions of Rust the lint was restricted to arithmetic operations on core integer types.This same problem applies to
arithemtic_side_effects
which is intended to replaceinteger_arithmetic
.User-defined types may implement
core::ops
traits in ways that always use checked and panic-free arithmetic internally. Thechecked
crate is an example. Such an approach makes it possible to use traditional arithmetic operators (which are easier to read) while still performing checked arithmetic, and perhaps more importantly deliberately don't implement unchecked arithmetic, and thus prevent you from doing the wrong thing (much in the same way this lint is intended to do).Warning for arithmetic operations on such types prevents them being from used as a strategy for mitigating this class of operations in a way that satisfies the lint.
Lint Name
integer_arithmetic
Reproducer
I tried this code:
I saw this happen:
I expected to see this happen:
Success
Version
Additional Labels
No response
The text was updated successfully, but these errors were encountered: