21

x86 and likely other architectures provide a method to get the quotient and remainder in a single operation (DIV). Because of this many languages have a DIVMOD combined operation, (like DIVREM in C#, DIVMOD in Python, or with div and div_t in C. How can I do this in Rust?

Is there an optimized method to perform both

let res = (a / b, a % b);
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • 6
    I think modern compilers such as LLVM are able to guess that you are doing the same division and module and optimize both operation to a single operation, such as in this [playground](https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=95c25b479730f221a5a5283ad3e2a664). – rodrigo Sep 04 '21 at 01:14
  • 1
    I would also like this, not as a performance optimization, but because it breaks my brain to see a single semantic operation expressed twice, as two similar yet subtly different expressions, in code. For example, the checked_div() and checked_rem() calls in [Bevy's Timer::tick()](https://github.com/bevyengine/bevy/blob/main/crates/bevy_time/src/timer.rs#L227-L236) method seem like they should be a single expression that evaluates to a (div, rem) pair. – Jeff Schwab Jun 24 '23 at 12:04

1 Answers1

10

As rodrigo commented already, the compiler is able to optimize this away. For the sake of completeness, there is a num_integer::div_rem method if you need it for generic integer types, but I'd vote against using this library if you don't need to be generic

mineichen
  • 470
  • 2
  • 11