midpoint Averages Without Overflow
Average two integers safely with i32::midpoint, which rounds toward negative infinity and never overflows where (a + b) / 2 would.
Code
fn main() {
let big = i32::MAX;
let small = i32::MAX - 1;
// 朴素做法 (a + b) / 2 在大数上溢出:用 checked_add 先探一下
println!("(a+b)/2 overflows: {}", small.checked_add(big).is_none());
// midpoint:无溢出取中值
println!("midpoint: {}", small.midpoint(big));
// 负数场景:midpoint 向负无穷取整,/2 向零截断,两者不同
let a = -3i32;
let b = 2i32;
println!("midpoint({}, {}) = {}", a, b, a.midpoint(b));
println!("(a+b)/2 = {}", (a + b) / 2);
// 边界值:floor 语义下 MIN 与 MAX 的中值是 -1,不是直觉里的 0
println!("mid(MIN, MAX) = {} (floor of the average)", i32::MIN.midpoint(i32::MAX));
// 二分查找防溢出的经典写法就是 midpoint
let needle = 21;
let sorted = [2, 5, 9, 14, 21, 33];
let (mut lo, mut hi) = (0usize, sorted.len());
while lo < hi {
let mid = lo.midpoint(hi);
match sorted[mid].cmp(&needle) {
std::cmp::Ordering::Less => lo = mid + 1,
std::cmp::Ordering::Greater => hi = mid,
std::cmp::Ordering::Equal => {
println!("binary search found index {mid}");
break;
}
}
}
}How it works
Structurally, expect the function main and nothing else.
The cycling part of this snippet is while lo < hi. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
Caveats
- Nothing sits in the dependency list; the runtime itself supplies it all.
Applying it
The signature doing the primary work is fn main()
The demo output is labeled ((a+b)/2 overflows:, midpoint:, midpoint(), so each printed line points back to the operation that produced it.
Statements that matter
match sorted[mid].cmp(&needle) {
std::cmp::Ordering::Less => lo = mid + 1,
std::cmp::Ordering::Greater => hi = mid,
std::cmp::Ordering::Equal => {
println!("binary search found index {mid}");
break;
}
}
Interactive Tools for This Topic
FAQ
- What does midpoint Averages Without Overflow print when run?
- Run it as a complete program — the output lines carry labels such as `(a+b)/2 overflows:`, `midpoint:`, `midpoint(`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.