Why is strict_div implemented in terms of overflowing_div for signed integers?

I was unable to find a satisfying answer to this question, so I thought I'd ask here. strict_div is currently implemented as follows for signed integers:

pub const fn strict_div(self, rhs: Self) -> Self {
    let (a, b) = self.overflowing_div(rhs);
    if b { imp::overflow_panic::div() } else { a }
}

However, div already panics on overflow even in release mode, meaning that strict_div should be exactly equivalent to div. This made me wonder why signed integers don't use the same implementation strategy as unsigned integers:

pub const fn strict_div(self, rhs: Self) -> Self {
    self / rhs
}

Can anyone offer any insights?

1 Like

Your question doesn't seem to be answered here:

And I can't think of a good reason.

That's a good question. I made a PR changing it to use the regular division operation:

The guarantee that iN::MIN / -1 unconditionally panics was documented in #82683. The discussion there clarifies that that was always the intended behaviour.

The Rust Reference gives a sensible picture: Dividing the signed minimum value by -1 is considered overflow, but for legacy reasons / and % panic on it even with -C overflow-checks disabled.

I wasn't aware of that exception before this thread, so I wouldn't be surprised if the implementor of strict_div wasn't either.

1 Like