#210
Jun 18, 2026
210. next_power_of_two — Round Up to a Power of Two Without the Bit-Twiddling
Sizing a buffer or hash table to the next power of two is a classic — and people keep reinventing it with shifts and leading_zeros. The standard library already has it.
You’ve probably seen (or written) the bit-twiddling version, which is easy to get subtly wrong on edge cases like 0 or exact powers:
| |
next_power_of_two does exactly this, correctly, for every unsigned integer type:
| |
A common use is rounding an allocation up so masking can replace modulo:
| |
The one trap: if the next power of two doesn’t fit in the type, next_power_of_two panics in debug and wraps to 0 in release. When the input is untrusted, reach for checked_next_power_of_two, which hands you an Option instead:
| |