Skip to content

Add wide division method(s) to (unsigned) integer types #776

Description

@gendx

Proposal

Problem statement

Several helper methods have been added and/or stabilized to help implement addition and multiplication on big integer types (rust-lang/rust#85532). An extension of that is implementing division on big integers, which requires another building block: a wide division function (which can be seen as the reverse of widening_mul):

// Returns (quotient, remainer) of the division of `(high << 64 | low)` by `divisor`.
// This assumes that the quotient fits into a u64 (the remainder always fits as the divisor is a `u64`).
fn wide_div(high: u64, low: u64, divisor: u64) -> (u64, u64);

Contrary to the naive division on u128 (which is typically implemented by the __udivmodti4 compiler built-in, see also rust-lang/rust#44545):

fn divmod_u128(wide: u128, divisor: u128) -> (u128, u128) {
    (wide / divisor, wide % divisor)
}

...this wide_div can be more efficient:

  • the divisor is only 64 bits rather than an arbitrary 128-bit,
  • the quotient is assumed (by the caller) to fit in only 64 bits,
  • importantly, on x86(_64) architectures, the DIV instruction already implements wide_div.

The same wide_div API could be offered on all unsigned integer types up to u64, as well as usize.

Motivating examples or use cases

This API is a useful building block in several contexts:

Solution sketch

For all u8, u16, u32, u64, usize:

impl uN {
    // Returns (quotient, remainer) of the division (high << uN::BITS | low) by divisor.
    fn wide_div(high: uN, low: uN, divisor: uN) -> (uN, uN);
}

Default implementation:

impl u64 {
    fn wide_div(high: u64, low: u64, divisor: u64) -> (u64, u64) {
        // TBD: should invalid inputs cause a panic? arbitrary results? undefined behavior?
        debug_assert!(high < divisor);

        let a = ((high as u128) << 64) | (low as u128);
        let b = divisor as u128;
        ((a / b) as u64, (a % b) as u64)
    }
}

Optimized implementation:

Open questions

  • Have a separate unsafe wide_div_unchecked() variant, when the caller asserts that the quotient will fit in a uN?
  • Also implement on signed integer types (e.g. to mirror the IDIV instruction on Intel)? Would that be useful? Should the low input be unsigned (as with iN::widening_mul)?
  • Naming? Order of the low & high parameters?

Alternatives

This could be implemented manually (as is indeed done in the num_bigint crate). However, this requires:

  1. special-casing CPU architectures (currently x86 and x86_64) to obtain the best performance - which could be a maintenance concern,
  2. unsafe code to emit the ideal div instruction on x86(_64),
  3. dispatch code to other integer types for the case of usize,
  4. carefully written code to avoid the default LLVM calls (__udivti3, __umodti3 or __udivmodti4) which may not be ideal (128-bit integer division with remainder is not combined to a single operation rust#44545), e.g. https://github.com/ridiculousfish/libdivide/blob/v5.3.0/libdivide.h#L554-L634.

Having such methods directly on integer types in the standard library could therefore be helpful and more maintainable for the wider ecosystem, similarly to other bigint helper methods (rust-lang/rust#85532).

Links and related work

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions