rust-lang / rust-lang/rfcs

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

Open
#964 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-libs
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

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:

https://github.com/rust-lang/rfcs/pull/560#issuecomment-72188471

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the referenced RFC #560 and the linked RFC comment about INT_MIN/-1 behavior. Determine whether wrapping division should use modular semantics or a clamped result, then document the agreed semantics and naming in the relevant RFC discussion.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.