254. isolate_lowest_one — The x & x.wrapping_neg() Hack Finally Has a Name
Every bitmask codebase has an unexplained x & x.wrapping_neg() in it somewhere. Rust 1.97 gives the trick a name — and a sibling for the other end.
The folklore version
To keep only the lowest set bit of an integer, the two’s-complement trick is to AND the value with its own negation:
| |
It works, it compiles to one instruction (BLSI on x86) — and it explains nothing to the next reader. For the highest set bit there isn’t even a one-liner: you shift 1 by leading_zeros arithmetic and special-case zero.
Named, on every integer type
Rust 1.97 stabilizes isolate_lowest_one and isolate_highest_one. They return the isolated bit as a mask — the value with all other bits cleared:
| |
Where bite 250’s lowest_one / highest_one answer “at which position?” (as an Option), the isolate_ pair answers “which bit?” — same information, shaped for masking instead of indexing.
The pattern: walk the set bits
The mask shape is exactly what you want for iterating over flags — grab the lowest bit, handle it, XOR it away:
| |
No positions, no shifting back and forth — each iteration hands you a ready-to-use single-bit mask. Signed types work too ((-8_i8).isolate_lowest_one() == 8), since the methods operate on the raw bit pattern.
If your code review comments still include “this ANDs x with its negation to isolate the lowest set bit…”, Rust 1.97 lets the method name say it for you.