Announcing cadd: a library for painless checked arithmetic and conversions

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 more Option s that require ok_or_else ; easy to integate with anyhow or 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 rewrite expr as u32 as u32::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.

7 Likes

Many years ago (1985!) we built a library for multiprecision floating point that used a similar syntax. Potential users HATED it. We ended up producing a custom Fortran compiler that turned floating point a+b into add(a,b). On another project where we didn't control the compiler, I wrote an Awk script (500 lines!) that modified the .s file to replace the add instruction with a specialized call to a function that effectively did add(a,b). Is a possible Rust alternative a macro that takes the source of a function with a+b and produces a function with add(a,b)?

1 Like

Completely unrelated but... FORTRAN.... It's been a while since I read about someone using the first programming language I learned :'D