78. div_ceil — Divide and Round Up Without the Overflow Bug
Need to split items into fixed-size pages or chunks? The classic (n + size - 1) / size trick silently overflows. div_ceil does it correctly.
The classic footgun
Paging, chunking, allocating — any time you divide and need to round up, this pattern shows up:
| |
It works until total + per_page - 1 wraps around. With u64::MAX items and a page size of 10, you get a wrong answer instead of a panic or correct result.
The fix: div_ceil
Stabilized in Rust 1.73, div_ceil handles the rounding without intermediate overflow:
| |
One method call, no overflow risk, intent crystal clear.
Real-world examples
Allocating pixel rows for a tiled renderer:
| |
Splitting work across threads:
| |
It works on all unsigned integers
div_ceil is available on u8, u16, u32, u64, u128, and usize. Signed integers also have it (since Rust 1.73), but watch out — it rounds toward positive infinity, which for negative dividends means rounding away from zero.
| |
Next time you reach for (a + b - 1) / b, stop — div_ceil already exists and it won’t betray you at the boundaries.