< All Blog

Wrapping Integers in Rust

November 10, 2022

In Rust, integers can be wrapped to avoid panicking during runtime.

Checking operations

Let's think the following example. The following source code panicks, because 1 + 255 = 256 is out of range in the uint8 range.

let result = 1_u8.checked_add(255_u8).unwrap();
println!("{}", result);
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:2:43

NOTE: uint8 has a range from 0 to 2^8-1 = 255, meaning uint8 cannot represent number 256 for example.

It makes sense because programmers do not expect to have 256 here, as long as they are using uint8 for this value.

Wrapping operations

But sometimes, there is a case that 1_u8 + 255_u8 can be valid. In uint8 range, it sometimes makes sense to regard 1 + 255 = 0 as assuming that the overflowed value are wrapped and start again from the beginning of the range.

In order to achieve this behaviour, Rust offers a way to wrap integers. Use wrapping_add instead and now you'll get 0.

let result = 1_u8.wrapping_add(255_u8);
println!("{}", result); //=> 0

Get control when overflowed

There is another way to handle when integer operations are overflowed. Sometime you'd want to get control how to handled overflow cases.

In this case, you can use overflow_add instead. It returns a turple, (result, overflowed), where result is the wrapping version of the operation results and overflowed is a boolean suggesting if the operation causes overflow or not.

You can use the overflowed boolean value to branch conditions how you'd like to handle overflowed cases.

let (result, overflowed) = 1_u8.overflowing_add(255_u8);
if overflowed {
    println!("Overflowed! Showing wrapped value: {}", result);
} else {
    println!("{}", result);
Overflowed! Showing wrapped value: 0

Recommended Posts

  1. How to Initialize Vector in Rust

    November 12, 2022
    In Rust, there are a couple of ways to initialize Vector. Vec::new() Vec::new() returns an empty vector. You can initialize a new empty vector and then pushing…
  2. Tuple with a Single Value in Rust

    November 11, 2022
    In Rust, tuples can be used to have different types of values as a container. Array does not allow you to have different types of elements instead. When Tuple …