liveBook · Manning

Integer wraparound

As explained in Code Like a Pro in Rust

Integer wraparound is arithmetic behavior in which an out-of-range fixed-width integer result cycles or is reduced modulo the type’s representable range.

Integer wraparound makes an out-of-range result cycle within a fixed-width integer type. In Rust, use an explicit `wrapping_*` method when that behavior is part of the operation’s contract, rather than relying on the build mode’s overflow behavior. section 4.5.1 section 6.3

Wrap at the boundary

`assert_eq!(0xffu8.wrapping_add(1), 0);` and `assert_eq!(0u32.wrapping_sub(1), 0xffffffff);` make the intended boundary behavior visible in both the code and its tests. section 4.5.1

Ordinary addition can pass through different overflow behavior in tests and release builds: debug-mode tests check for overflow, while release builds use unchecked arithmetic. A property test over `i64` inputs exposes this pitfall when an addition panics on a generated pair. section 6.3

For generic addition, `num_traits::ops::wrapping::WrappingAdd` supplies a trait bound; the standard library has no equivalent trait. Test the result against `a.wrapping_add(b)`. Rust also offers `std::num::Wrapping` and per-type wrapping methods. Do not treat “C-compatible” as a guarantee for signed overflow in C, where it is undefined. section 6.3 section 4.5.1

How Code Like a Pro in Rust covers it

How deep it goes
Demonstrates boundary assertions and a property-test repair, but defers deeper treatment of traits.
Examples
Uses unsigned boundary assertions and an `i64` property test that first fails on overflow, then passes with wrapping addition.
What it assumes
Assumes familiarity with Rust integer operations and tests; introduces the wrapping operation directly while deferring deeper trait coverage.
What you can do after
Apply it via Rust’s `wrapping_*` methods or `num_traits::WrappingAdd`, and test overflow behavior explicitly.
How it connects
Links modular arithmetic to primitive integer types, overflow checking, generic traits, and property testing.

Also explained in

Compare how 3 books explain integer wraparound →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.