Description
(Note: this was originally posted as a comment on #62429 - also cc #35310 but not sure how relevant)
In #62429 (comment) @scottmcm said:
Might be worth double-checking there's a test for overflow checks here? I'm never confident in what
rustc_inherit_overflow_checks
does. (And I hear that one can useAdd::add(count, 1)
instead of using the attribute.)
While adding more tests is better, I don't agree with removing the attribute. If anything the attribute should be better documented, but relying on more implicit mechanisms that internally use the attribute obscures the fact that something unusual is happening.
(i.e. that some of the behavior isn't decided by the crate being compiled, but by a downstream using crate)
The reason Add::add
works at all is because the attribute is used in the impl
s` for the integer types, e.g.:
rust/library/core/src/ops/arith.rs
Lines 92 to 107 in 186f7ae
There's nothing magical about it being a trait call, you're just calling another function with #[rustc_inherit_overflow_checks]
on it, instead of using #[rustc_inherit_overflow_checks]
yourself, and relying on generic/#[inline]
instantiation to get the behavior.
The only reason the trait impls have the attribute is because of things generic over those traits, not to call directly.
EDIT: see also documentation issue by @m-ou-se at rust-lang/std-dev-guide#13
Activity
scottmcm commentedon Feb 3, 2021
+1 to having something in the guidelines for what the correct approach is -- I only said this because it was mentioned to me in #45754 (comment)
eddyb commentedon Feb 3, 2021
Wow, that's really old, thanks for tracking it down! I wasn't sure how far back it might go, I was only shown this pattern recently.
eddyb commentedon Feb 3, 2021
Looks like that was potentially a misunderstanding of my comment at #36372 (comment), heh:
I suggested replacing
iter.fold(0, |a, b| a + b)
withiter.fold(0, Add::add)
, not callingAdd::add
directly.In retrospect, for documentation purposes, maybe this would've been better:
#[rustc_inherit_overflow_checks]
instead of Add::add etc. #81732Auto merge of rust-lang#81732 - m-ou-se:inherit-overflow-checks, r=Ma…
eddyb commentedon Feb 22, 2021
Regarding the suboptimal name, I wrote (in #81732 (comment)):
I also had an idea that might be useful for avoiding misuse in most cases:
Flatten
andFlatMap
iterators #99541hkBst commentedon Jan 30, 2025
Is there anything to do here?
bionicles commentedon Feb 19, 2025
one question is, how does this interact with clippy::arithmetic_side_effects ?
could this lead to developers missing instances where arithmetic could panic or produce unexpected results?
https://rust-lang.github.io/rust-clippy/master/index.html?groups=restriction#arithmetic_side_effects