Skip to content

arith-oflo: what is semantics of divide int::MIN.wrapped_div(-1) #964

Open
@pnkfelix

Description

@pnkfelix

I am working through implementing #560

I had thought, from the name "wrapping", that int::MIN.wrapped_div(-1) would be defined as follows:

    /// Returns `floor(a / b) mod 2^N`, where `N` is the width of `T` in bits.
    ///
    /// Note that for signed T:
    ///   `(floor(T::MIN / -1) mod 2^N) == (floor(T::MAX + 1) mod 2^N) == 1`
    pub fn overflowing_div<T>(a: T, b: T) -> T;

but then I saw this comment on the RFC thread:

#560 (comment)

which suggests: "there is no undefined behaviour or values left (if we agree to defining the result of INT_MIN/-1 as INT_MAX)."

My thinking is that if one wants the latter semantic, then maybe we should give it a name other than wrapping_div ... e.g. maybe have both:

    /// Returns `floor(a / b) mod 2^N`, where `N` is the width of `T` in bits.
    ///
    /// Note that for signed T:
    ///   `(floor(T::MIN / -1) mod 2^N) == (floor(T::MAX + 1) mod 2^N) == 1`
    pub fn wrapping_div<T>(a: T, b: T) -> T;

    /// Returns `floor(a / b)` clamped to the range `[-2^N, 2^N-1] mod 2^N`, where `N+1` is the width of `T` in bits.
    ///
    /// Note that for signed T:
    ///   `clamp(floor(T::MIN / -1)) == clamp(floor(T::MAX + 1)) == T::MAX`
    pub fn saturating_div<T>(a: T, b: T) -> T;

keywords: arithmetic overflow division divide wrapping

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions