Missing traits for checked arithmetic

While working on GitHub - dpc/overflow-proof: Monadic checked arithmetic for Rust I was disappointed that there are no traits abstracting over checked arithmetic in stdlib.

There's a lot of checked_* functions but no glue to allow handling them in a generic way.

From my PoV if there's anything that stdlib is useful for is establishing interoperability interfaces between 3rd party libraries. Would be nice if I could write a overflow handling library that would work for any time that implements a common trait.

The stdlib is intentionally short of a whole bunch of commonly-requested traits for math. There's no trait for the additive identity element either, for example.

The general answer for this is that you want num_traits - Rust, which has CheckedAdd and friends, as well as many others.

3 Likes

Thanks. I'll convert my ad-hoc traits to this then.

Is this official semi-official stance? Is it/should be documented somewhere?

It is the official semi-official stance. The Rust teams don't like to officially recommend crates so far. Including ones that spun out of core (pre-1.0) Rust originally, like num_traits, or are otherwise semi-official, which is why it's not in the official documentation.

2 Likes

There''s also the checked crate which introduces a Checked type similar to core::num::Wrapping: checked::Checked - Rust

It provides a pretty good example of what a self-contained addition of checked arithmetic wrappers might look like if added to the standard library.

There was a pre-RFC about it posted here cc @pdolezal: Where is std::num::Saturating? (Going to pre-RFC!) - #27 by pdolezal

Well, here's the pre-1.0 PR that moved all this stuff out of the standard library and created the num crate:

You'll see that getting to it through rust-lang still works -- try https://github.com/rust-lang/num -- but it's been moved to a separate github organization officially.

So yeah, it's de facto official.

My reading of the tea leaves is that we might get num::Checked in std, like there's num::Wrapping, but that we're unlikely to have CheckedAdd+CheckedSub+... in std.

(That also follows the "add a type instead of a trait" convention we seem to be developing. Like you could then bound on Checked<T>: Add instead of T: CheckedAdd.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.