17

Is there a canonical way to explicitly check for integer overflow in Rust? I Googled around but couldn't find the answer.

Something like:

match add_or_overflow(x, y) {
  None    => println!("overflow!"),
  Some(z) => println!("{} + {} = {}", x, y, z),
}

Or:

let x = OverflowChecked<i32>(_x);
let y = OverflowChecked<i32>(_y);
match x + y {
  OverflowChecked::Overflow => println!("overflow!"),
  OverflowChecked::Value(z) => println!("{} + {} = {}", x, y, z),
}

I could write this manually since Rust guarantees wrapping semantics, but I was just checking that there isn't some standard way to do this.

Luke McCarthy
  • 879
  • 2
  • 9
  • 21
  • 1
    Looks like that answer is obsolete, since it looks like CheckedAdd, etc. have been removed from Rust (the links return 404). – Luke McCarthy Oct 04 '18 at 12:53
  • 1
    The second answer seems to be what I was looking for: https://doc.rust-lang.org/nightly/std/primitive.i64.html#method.overflowing_add – Luke McCarthy Oct 04 '18 at 12:54

2 Answers2

20

The functions are named checked_[operator]. See checked_add for example:

fn main() {
    let x: u8 = 255;
    let y: u8 = 1;
    let z = x.checked_add(y);

    assert_eq!(z, None);
}
Boiethios
  • 38,438
  • 19
  • 134
  • 183
6

The standard library integer types have checked_* methods for common operations, such as checked_add for addition, etc.

Example from the docs:

assert_eq!((u32::max_value() - 2).checked_add(1), Some(u32::max_value() - 1));
assert_eq!((u32::max_value() - 2).checked_add(3), None);

A working example with a similar construct as your example could be:

let x = u32::max_value() - 2;
let y = 3;

match x.checked_add(y) {
    Some(v) => {
        println!("{} + {} = {}", x, y, v);
    }
    None => {
        println!("overflow!");
    }
};