Wrapping and Saturating Arithmetic
This example compares wrapping and saturating arithmetic when a result goes beyond an integer type’s bounds. It uses small integer types so we can easily see what happens when addition, subtraction, or multiplication overflows.
expect (250.U8).plus_wrap(10) == 4 expect (250.U8).plus_saturated(10) == 255 expect (0.U8).minus_wrap(1) == 255 expect (0.U8).minus_saturated(1) == 0 expect (100.I8).times_wrap(2) == -56 expect (100.I8).times_saturated(2) == 127
Wrapping continues at the opposite bound: adding ten to 250.U8 wraps around to 4. Saturating arithmetic stops at the nearest bound instead, giving 255 for the same addition.
Ordinary +, -, and * crash on overflow. If you would prefer to handle overflow as an error, the Safe Math example shows the fallible arithmetic methods.
Output
Run this from the directory that has main.roc in it:
$ roc test main.roc All (6) tests passed in 10.8 ms.
Validated with Roc nightly-2026-10-29-a0a9fc2.