Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for integer overflow in Rust [duplicate]

Tags:

rust

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.

like image 659
Luke McCarthy Avatar asked Oct 04 '18 12:10

Luke McCarthy


People also ask

How do you check overflow in Rust?

In debug mode, Rust adds built-in checks for overflow/underflow and panics when an overflow/underflow occurs at runtime. However, in release (or optimization) mode, Rust silently ignores this behavior by default and computes two's complement wrapping (e.g., 255+1 becomes 0 for an u8 integer).

How do you check if an integer is overflow?

Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.

How do you deal with overflow in Rust?

To remove the overflow error, change the value of variable2 from 0 to any negative number within the range −1 to −32767.

How do you know when an overflow occurred?

The rules for detecting overflow in a two's complement sum are simple: If the sum of two positive numbers yields a negative result, the sum has overflowed. If the sum of two negative numbers yields a positive result, the sum has overflowed. Otherwise, the sum has not overflowed.


1 Answers

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);
}
like image 109
Boiethios Avatar answered Jan 03 '23 05:01

Boiethios