Integer operation with boundary when overflow in Rust

Viewed 1558

The problem I recently meet requires to do integer operation with boundary based on the bits of integer type.

For example, using i32 integer to do add operation, here's a piece of pseudo code to present the idea:

sum = a + b
max(min(sum, 2147483647), -2147483648)

// if the sum is larger than 2147483647, then return 2147483647.
// if the sum is smaller than -2147483648, then return -2147483648.

To achieve this, I naively wrote following ugly code:

fn i32_add_handling_by_casting(a: i32, b: i32) -> i32 {
    let sum: i32;
    if (a as i64 + b as i64) > 2147483647 as i64 {
        sum = 2147483647;
    } else if (a as i64 + b as i64) < -2147483648 as i64 {
        sum = -2147483648;
    } else {
        sum = a + b;
    }
    sum
}

fn main() {
    println!("{:?}", i32_add_handling_by_casting(2147483647, 1));
    println!("{:?}", i32_add_handling_by_casting(-2147483648, -1));
}

The code works well; but my six sense told me that using type casting is problematic. Thus, I tried to use traditional panic (exception) handling to deal with this...but I stuck with below code (the panic result can't detect underflow or overflow):

use std::panic;

fn i32_add_handling_by_panic(a: i32, b: i32) -> i32 {
    let sum: i32;
    let result = panic::catch_unwind(|| {a + b}).ok();
    match result {
        Some(result) => { sum = result },
        None => { sum = ? }                                                              
    }
    sum
}

fn main() {
    println!("{:?}", i32_add_handling_by_panic(2147483647, 1));
    println!("{:?}", i32_add_handling_by_panic(-2147483648, -1));
} 

To sum up, I have 3 questions:

  1. Is my type casting solution valid for strong typing language? (If possible, I need the explanation why it's valid or not valid.)
  2. Is there other better way to deal with this problem?
  3. Could panic handle different exception separately?
1 Answers

In this case, the Rust standard library has a method called saturating_add, which supports your use case:

assert_eq!(10_i32.saturating_add(20), 30);
assert_eq!(i32::MIN.saturating_add(-1), i32::MIN);
assert_eq!(i32::MAX.saturating_add(1), i32::MAX);

Internally, it is implemented as a compiler intrinsic.


In general, such problems are not intended to be solved with panics and unwinding, which are intended for cleanup in exceptional cases only. A hand-written version might involve type casting, but calculating a as i64 + b as i64 only once. Alternatively, here's a version using checked_add, which returns None rather than panics in case of overflow:

fn saturating_add(a: i32, b: i32) -> i32 {
    if let Some(sum) = a.checked_add(b) {
        sum
    } else if a < 0 {
        i32::MIN
    } else {
        i32::MAX
    }
}
Related