[Solved] Rust round usize to nearest multiple of 8

What is the most efficient way of rounding a usize up to a nearest multiple of 8? What I have so far is:

((x + 7) / 8) * 8

How about (x + 7) & !7usize, which can usually be written simply as x + 7 & !7.


@TomP : I don't think it's possible to reduce it to 1 op. You win. :slight_smile:

Of course both your approach and mine are susceptible to overflow when x is just slightly less than usize::MAX. I presumed that you didn't care about that condition, since you didn't address it in your code.

Incidentally, your measure of "efficiency", in number of operators, is not what I inferred. I thought that you meant CPU efficiency. Logical And is almost certainly more efficient (in both time and energy) than Divide followed by Multiply. It is also less likely to leak information through a timing side-channel.

What you have is fine, @zeroexcuses; the compiler will turn it into what @TomP said.

This is the kind of simple, local transformation that LLVM is extraordinary good at. Write the clear thing; let LLVM optimize the exact instructions.

... but do check/measure the performance (or the asm itself) or else things like this can get you :slight_smile:

1 Like