https://stackoverflow.com/questions/3895081/divide-and-get-remainder-at-the-same-time
Is there a way in Rust to get the quotient and remainder in one call, i.e. returns a tuple of both values?
https://stackoverflow.com/questions/3895081/divide-and-get-remainder-at-the-same-time
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) {
div_rem(x,y)
}
produces the following x86 asm for div_rem_usize
:
div_rem_usize:
testq %rsi, %rsi
je .LBB0_1
xorl %edx, %edx
movq %rdi, %rax
divq %rsi
retq
.LBB0_1:
pushq %rbp
movq %rsp, %rbp
leaq .Lpanic_loc.2(%rip), %rdi
callq core::panicking::panic@PLT
ud2
I think I need to brush up on my x86 assembler
(I've lived my entire programming life inside virtual machines, it's only now with Rust it feels safe to escape the box!)