[rust-dev] Integer overflow, round -2147483648
banderson at mozilla.com
Wed Jun 18 11:21:06 PDT 2014
On 06/18/2014 10:08 AM, Gábor Lehel wrote:
> # Checked math
> For (2), the standard library offers checked math in the `CheckedAdd`,
> `CheckedMul` etc. traits, as well as integer types of unbounded size:
> `BigInt` and `BigUint`. This is good, but it's not enough. The acid
> test has to be whether for non-performance-critical code, people are
> actually *using* checked math. If they're not, then we've failed.
> `CheckedAdd` and co. are important to have for flexibility, but
> they're far too unwieldy for general use. People aren't going to write
> `.checked_add(2).unwrap()` when they can write `+ 2`. A more adequate
> design might be something like this:
> * Have traits for all the arithmetic operations for both checking on
> overflow and for wrapping around on overflow, e.g. `CheckedAdd` (as
> now), `WrappingAdd`, `CheckedSub`, `WrappingSub`, and so on.
> * Offer convenience methods for the Checked traits which perform
> `unwrap()` automatically.
> * Have separate sets of integer types which check for overflow and
> which wrap around on overflow. Whatever they're called: `CheckedU8`,
> `checked::u8`, `uc8`, ...
> * Both sets of types implement all of the Checked* and Wrapping*
> traits. You can use explicit calls to get either behavior with either
> * The checked types use the Checked traits to implement the operator
> overloads (`Add`, Mul`, etc.), while the wrapping types use the
> Wrapping traits to implement them. In other words, the difference
> between the types is (probably only) in the behavior of the operators.
> * `BigInt` also implements all of the Wrapping and Checked traits:
> because overflow never happens, it can claim to do anything if it
> "does happen". `BigUint` implements all of them except for the
> Wrapping traits which may underflow, such as `WrappingSub`, because it
> has nowhere to wrap around to.
> Another option would be to have just one set of types but two sets of
> operators, like Swift does. I think that would work as well, or even
> better, but we've been avoiding having any operators which aren't
> familiar from C.
The general flavor of this proposal w/r/t checked arithmetic sounds
pretty reasonable to me, and we can probably make progress on this now.
I particularly think that having checked types that use operator
overloading is important for ergonomics.
More information about the Rust-dev