I believe that most libraries and applications should always prefer checked arithmetic (e.g. a.checked_add(b) instead of a + b ) and conversions (a.try_into()? instead of a as u32 ). Unchecked operations have their purpose, but they shouldn't be the default choice. Unfortunately, there are a lot of inconveniences when using checked alternatives. I created cadd to alleviate most of these inconveniences:
- All functions return
Result(no moreOptions that requireok_or_else; easy to integate withanyhowor with custom error types). - Error messages are useful: they show the failed operation and its inputs, and even a backtrace (if enabled).
- Function names are short and predictable: add "c" in front of the unchecked alternative to get the improved version:
cadd,cdiv,cilog, and so on. .into_type::<T>()and.try_into_type::<T>()adapter: you no longer need to rewriteexpr as u32asu32::try_from(expr)?because of type inference issues.
There is more: function-style checked math (cadd(a, b) ), saturating conversions, and conversions to NonZero types. Check out the documentation for more details.
Pair it with some clippy's lints (arithmetic_side_effects , cast_possible_wrap , cast_precision_loss , cast_sign_loss ) and eliminate unexpected overflows, truncations, and panics from your code.