249. bit_width — How Many Bits Does This Number Need? (New in Rust 1.97)
“How many bits do I need for this value?” used to mean 32 - n.leading_zeros() — a formula you rewrite every time the integer type changes. Rust 1.97 — hitting stable today — ships bit_width and friends.
The old dance
Bit packing, varint encoding, sizing a field: they all start with the same question — the position of the highest set bit, plus one. The classic answers both have sharp edges:
| |
The leading_zeros version encodes the type width (32) by hand. The ilog2 version blows up on zero, so real code needs an if n == 0 guard around it.
bit_width says what you mean
Stable since Rust 1.97 on all integers:
| |
Zero needs zero bits — no panic, no guard. The width of the type is no longer baked into your arithmetic, so the same line keeps working when a refactor turns u32 into u64.
Bonus: isolate_lowest_one kills the wrapping_neg hack
The same release stabilizes isolate_lowest_one and isolate_highest_one, which keep just the lowest or highest set bit. The lowest-bit version replaces the venerable x & x.wrapping_neg() two’s-complement trick — the one you either know or google every time:
| |
That makes the standard “iterate the set bits” loop readable:
| |
No two’s-complement folklore in sight — the intent is right there in the method names.