3 ms·
> 1. add two signed 64 but it's without overflowing fn f(x: i64, y: i64) -> Option<i64> { x.checked_add(y) } Option<T> being the Rust equivalent for s
by zdimension 3y ago
> 1. add two signed 64 but it's without overflowing
fn f(x: i64, y: i64) -> Option<i64> {
x.checked_add(y)
}
Option<T> being the Rust equivalent for std::optional, but with all the nice ADT features so it's ergonomic to use. You can transform it to a Result<T, E> if you want, or even just panic and exit if it overflows. In any case, the overflow handling is built-in and doesn't use 128 bit ints.
> 2. Multiply two signed 64 bit ints without overflow
x.checked_mul(y)
(https://doc.rust-lang.org/std/primitive.i64.html#method.checked_add https://doc.rust-lang.org/std/primitive.i64.html#method.chec..., https://doc.rust-lang.org/std/primitive.i64.html#method.checked_mul https://doc.rust-lang.org/std/primitive.i64.html#method.chec...)