How to disable panicking for u64 arithmetic overflow?

I wanted to actually use the functionality which multiplies two u64 and only obtain the lowest 64 bits of the result, like so

    let a: u64 = 1u64 << 2;
    let b: u64 = 1u64 << 63;
    let c: u64 = a*b;

But I got an error saying "thread 'main' panicked at 'attempt to multiply with overflow'" -- how do I disable this?

a.wrapping_mul(b).

3 Likes

Alternatively,

    use std::num::Wrapping;
    let a: Wrapping<u64> = Wrapping(1u64 << 2);
    let b: Wrapping<u64> = Wrapping(1u64 << 63);
    let c: Wrapping<u64> = a*b;

(Without more context it's hard to know whether the method or the newtype is appropriate.)

1 Like

Thanks! What context would be useful here? I am just trying to get the functionality of (a*b mod 2^64).

Both give you that. So it's up to you to look at the surrounding code and decide if this is what you always want for a bunch of stuff in the same area -- and thus use the wrapper type -- or if you normally want the usual rust behaviour (panic in debug; wrap in release) and only occasionally want wrapping -- and thus use the method.

1 Like

I'd just like to highlight this, in case you're unaware.

2 Likes

actually I'm not sure what this means -- could you elaborate?

When you compile Rust in debug mode (the default) it panics when you have overflow; however, when you compile Rust in release mode (by passing the --release flag to cargo build, cargo test, etc.) it switches to using wrapping arithmetic as that is significantly faster. So compiling in release mode would avoid the panic and instead have the behaviour you're after, but it is strongly discouraged to rely on that if you need the overflow, as it is not clear that you intended it, which the other options above do.

1 Like

Thanks! That makes me also wonder the cargo bench command. Does the benchmarking numbers depend on whether I compile using debug or release mode?

They would, but cargo bench defaults to compiling in release mode. If you want to benchmark the debug build you can run cargo bench --debug.

2 Likes