73. u64::midpoint — Average Two Numbers Without Overflow
Computing the average of two integers sounds trivial — until it overflows. The midpoint method gives you a correct result every time, no wider types required.
The classic binary search bug lurks in this innocent-looking line:
| |
When low and high are both large, the addition wraps around and you get garbage. This has bitten production code in every language for decades.
The textbook workaround avoids the addition entirely:
| |
This works — but only when low <= high, and it’s one more thing to get wrong under pressure.
Rust’s midpoint method handles all of this for you:
| |
It works on signed integers too, rounding toward zero:
| |
And on floats, where it’s computed without intermediate overflow:
| |
Here’s a binary search that actually works for the full u64 range:
| |
Available on all integer types (u8 through u128, i8 through i128, usize, isize) and floats (f32, f64). No crate needed — it’s in the standard library.