#arithmetic #overflow #integer

checked

Implements a wrapper over the primitive Rust types that better indicates overflow during arithmetic

7 releases (4 breaking)

Uses old Rust 2015

0.5.0 Feb 17, 2018
0.4.0 Aug 12, 2017
0.3.1 Aug 5, 2017
0.2.0 Aug 5, 2017
0.1.1 Aug 5, 2017

#1721 in Data structures

Download history 302/week @ 2023-12-08 231/week @ 2023-12-15 167/week @ 2023-12-22 89/week @ 2023-12-29 151/week @ 2024-01-05 176/week @ 2024-01-12 170/week @ 2024-01-19 123/week @ 2024-01-26 107/week @ 2024-02-02 219/week @ 2024-02-09 260/week @ 2024-02-16 192/week @ 2024-02-23 221/week @ 2024-03-01 217/week @ 2024-03-08 138/week @ 2024-03-15 225/week @ 2024-03-22

850 downloads per month
Used in 14 crates (via tower-web)

MIT license

29KB
588 lines

Checked

Implements a wrapper over the primitive Rust types that better indicates overflow during arithmetic.

The struct Checked derefs into an option that either contains the number, or None if an overflow occurred. This means that all of Option's methods can be used.

Note that Add<T> is implemented for Checked<T> for all the primitive integer types T (u8, i16, etc.) so really, only the left-most integer needs to be a Checked object. Once the arithmetic hits a Checked<T> on the right OR left, all the remaining results are Checked too. Just make sure there's a Checked somewhere before the first potential overflow.

This struct is based on std::num::Wrapping, except using checked arithmetic instead of wrapped arithmetic. There was an RFC that mentioned this approach, but as far as I know, it was never implemented anywhere.

Example

extern crate checked
use checked::Checked;

fn main() {
    let x = Checked::from(1_000_000_000_u32) * 3 + 2_000_000_000;
    match *x {
        Some(y) => println!("Didn't overflow: x is {}.", y),
        None => println!("The arithmetic overflowed."),
    }
}

Documentation

Documentation may be found here.

Contributing

I may try to add more features in time: make an Issue or Pull request to get the ball rolling.

Dependencies

~155KB