255. rotate_left / rotate_right — Bit Rotation Without the Shift-Overflow Trap
Shifting throws bits away. The manual “wrap them around” idiom panics on n == 0. Rotation has been one method call the whole time.
The problem with shifts
A left shift pushes the top bits off the edge — they’re gone:
| |
When you need the bits to wrap around — hashing, checksums, circular counters — the textbook idiom combines two shifts:
| |
Which works right up until n == 0: then x >> 8 is a shift by the full bit width — a panic in debug builds, and a masked, silently-wrong result in release. A correct version needs masking both shift amounts, and now you’re writing a code comment again.
The built-in
Every integer type has rotate_left and rotate_right. Bits that fall off one end come back on the other:
| |
No edge cases: the rotation amount is taken modulo the bit width, so n == 0, n == 8, even n == 1000 are all fine —
| |
— and like bite 254’s isolate_lowest_one, it compiles to a single instruction (ROL/ROR on x86) instead of the three ops the manual idiom costs.
Round trips for free
Rotation never destroys information, so it’s trivially reversible — handy for mixing bits in a hash and for tests:
| |
Note this rotates the bit pattern, not bytes: for endianness work you want swap_bytes or bite 240’s to_le_bytes. But when the task is “slide bits around a circle”, rotate_left says exactly that — with no (8 - n) waiting to panic.