Quotient and Remainder


Is there a way in Rust to get the quotient and remainder in one call, i.e. returns a tuple of both values?


There’s nothing built-in for this, AFAIK. You can write your own and (in my observation) the compiler will optimize it such that only a single instruction is emitted, at least on x86. For example:

pub fn div_rem<T: std::ops::Div<Output=T> + std::ops::Rem<Output=T> + Copy>(x: T, y: T) -> (T, T) {
    let quot = x / y;
    let rem = x % y;
    (quot, rem)

pub fn div_rem_usize(x: usize, y: usize) -> (usize, usize) {

produces the following x86 asm for div_rem_usize:

        testq   %rsi, %rsi
        je      .LBB0_1
        xorl    %edx, %edx
        movq    %rdi, %rax
        divq    %rsi
        pushq   %rbp
        movq    %rsp, %rbp
        leaq    .Lpanic_loc.2(%rip), %rdi
        callq   core::panicking::panic@PLT


I think I need to brush up on my x86 assembler :slight_smile:
(I’ve lived my entire programming life inside virtual machines, it’s only now with Rust it feels safe to escape the box!)


The num-integer crate has div_rem as a standalone function and as a method of its Integer trait.