Rust / Basic / Lesson 7
Checked integer arithmetic
Select checked, saturating, or wrapping Rust integer operations.
On this page
Lesson goals
- Distinguish checked, saturating, and wrapping arithmetic.
- Validate conversions and boundary results.
- Select and trace checked, saturating, wrapping, and overflowing operations for a specified domain.
- Validate intermediate arithmetic, numeric conversions, and independent resource bounds.
Choose an overflow policy
Integer types have finite ranges, so an arithmetic result may not fit even when both operands are valid. A program should choose a policy for that case rather than depending on build settings or a wraparound accident. The right policy depends on the domain: reject an invalid total, saturate a bounded measurement, or deliberately use wrapping arithmetic when that behavior is part of the specification.
Check arithmetic
The checked arithmetic methods return an Option: Some contains a representable result and None indicates overflow. The example adds two u8 values and matches both outcomes. It does not perform a potentially overflowing ordinary addition first. Make the caller decide how to report or recover from None, and test both the maximum representable result and the first rejected result.
fn main() {
match 250_u8.checked_add(10) {
Some(value) => println!("{value}"),
None => println!("overflow"),
}
}
overflow
The exact sum does not fit in u8, so checked_add returns None.
Compare explicit policies
Saturating arithmetic clamps an out-of-range result to the type boundary; wrapping arithmetic uses modular behavior. Neither is an error check. The example contrasts the two policies for the same values. Choose one only when its meaning is useful to the domain, and document it so a reader does not mistake a clamped or wrapped value for the exact mathematical result.
fn main() {
let value = 250_u8;
println!("{} {}", value.saturating_add(10), value.wrapping_add(10));
}
255 4
Saturation selects 255; wrapping produces 4.
Validate conversions
Conversions also need a policy. A cast with as can truncate or otherwise change a numeric value according to conversion rules; it is not a general range validator. Use a checked conversion such as TryFrom when the target range must be enforced, and handle its error. Validate units as well as range: a count of bytes and a count of elements may both be integers but are not interchangeable.
Test numeric boundaries
Create tests for zero, ordinary values, the largest accepted value, and a result just beyond the boundary. Check the returned variant as well as its content. If a later multiplication computes a buffer size, validate that operation independently before allocating. Testing only small inputs cannot establish what happens at the type limit or prove that the chosen failure policy reaches the caller.
Finite representations and policy
A fixed-width integer represents only a finite interval. For u8 the interval is 0 through 255; for i8 it is -128 through 127. Both inputs can be valid while their mathematical result lies outside the result type. For example, 200 and 60 are valid u8 values, but their sum 260 is not. The relevant question is not whether the inputs were parsed, but whether each operation’s exact result fits the type chosen for that operation. A wider intermediate can help, but it too has a limit and a later narrowing conversion still requires a policy.
Choose behavior based on the domain. A financial total or allocation size normally needs an explicit failure when its exact result is unavailable. A bounded display level might deliberately clamp to its limits. A sequence counter or checksum may deliberately use modular arithmetic if its specification requires it. Record that choice at the operation, not only in a comment at the top of a module. Units also matter: a byte count and an element count may share usize but cannot be added meaningfully without an explicit conversion and a justified formula. Boundary tests should include both limits and the first result beyond them.
Checked operations and failure propagation
checked_add, checked_sub and checked_mul return Some(result) when the exact result fits and None when it does not. Check before using the result: performing ordinary arithmetic first and checking afterward may already have overflowed. Subtraction can fail at the lower bound as well as addition at the upper bound. checked_div also returns None for a zero divisor and for signed MIN divided by -1, whose mathematical positive result does not fit. Thus None from a division can have more than one cause; validate the divisor separately if the user needs distinct diagnostics.
A chain can use and_then to perform the next checked operation only when the previous one succeeds. Converting Option to Result with ok_or lets an application report a domain-specific error and use ? in a function with a compatible return type. Do not replace None with zero unless zero is genuinely the required fallback; otherwise a failed calculation becomes a plausible but false result. For a buffer size, check element count times bytes per element, then check any header addition independently before applying a separate resource limit. Arithmetic representability does not guarantee that an allocation is permitted or will succeed.
Clamping, modular results, and overflow flags
saturating operations clamp an out-of-range mathematical result to the nearest type bound. For example, 250_u8.saturating_add(10) is 255, not 260; 3_u8.saturating_sub(5) is zero. This is appropriate only when clamping is intended, since the result alone does not say whether a limit was reached by overflow or exactly. Wrapping operations compute the result modulo the width of the integer representation. For u8, 250 plus 10 wraps to 4; wrapping subtraction from zero goes to 255. A wrapped result is not the exact total and is unsuitable for a size or balance unless modular behavior is the actual rule.
The overflowing family returns a pair: the wrapped result and a boolean indicating overflow for that operation. For example, 250_u8.overflowing_add(10) returns (4, true), while 2_u8.overflowing_add(3) returns (5, false). Inspect the flag before using the wrapped value if overflow requires a different action. These explicit methods make their selected policy independent of ordinary overflow-check settings. They do not make arbitrary input safe by themselves: a later index, allocation, division, or conversion still has its own preconditions.
Ordinary operators and build configuration
Ordinary integer operators are not a portable overflow policy. Cargo’s default dev profile enables overflow checks, while its default release profile disables them; a project can override those profile settings, and compiler flags can also change checks. When checks are enabled, ordinary runtime arithmetic overflow panics. When checks are disabled, integer overflow follows the defined two’s-complement wrapping behavior; do not extrapolate that to every arithmetic error. In particular, integer division or remainder by zero panics, and signed MIN divided by -1 is an overflow case that panics even when overflow checks are disabled. Constant evaluation can also reject an overflow before a program runs.
Use named methods for the behavior that the domain needs rather than treating debug and release as permanent guarantees. Build profiles control more than arithmetic, and custom profiles need inspection. A test should assert Some or None, a clamped bound, or the wrapped result and flag as appropriate; it should not assume that an unconfigured ordinary + will report an error in every build. The snippets in these examples are illustrative fragments and were not executed or qualified in a local Rust toolchain. Their outcomes follow the documented operations and stated operand types.
Conversions, shifts, and verification
An as cast is not a checked conversion. For integer-to-integer narrowing, it truncates high bits; for example, 300_u16 as u8 produces 44. TryFrom returns a Result so that u8::try_from(300_u16) fails while u8::try_from(255_u16) succeeds. Signed-to-unsigned conversion also needs a range decision: -1_i16 is not a valid u8, even though a cast can produce a different bit-pattern-based numeric result. A successful conversion establishes representability, not the application’s own smaller range or unit requirement.
Shift checks need careful interpretation. checked_shl returns None when the shift count is at least the number of bits, but a valid shift count does not prove that significant high bits are preserved. For example, 128_u8.checked_shl(1) is Some(0): the count is valid while the high bit is discarded. Use a checked multiplication by a power of two when preserving the exact product is the intended requirement, subject to validating that power too. Test exact maximum and minimum, one beyond the range, zero divisors, signed MIN divided by -1, narrowing conversions, and each step of multi-operation calculations. Inspect the result variant or flag and verify that rejected work does not alter state.
20 worked examples
1. Exact upper boundary
Problem: Determine whether this addition fits the result type.
- The mathematical sum of 200 and 55 is 255.
- That value is the maximum representable u8.
let result = 200_u8.checked_add(55);
Illustrative fragment; not executed as a standalone program.
Expected result: result = Some(255)
Why this result follows: checked_add returns the exact value when it fits.
2. First overflowing sum
Problem: Determine the result just above the u8 maximum.
- The mathematical sum is 256.
- A u8 cannot represent any value above 255.
let result = 200_u8.checked_add(56);
Illustrative fragment; not executed as a standalone program.
Expected result: result = None
Why this result follows: checked_add reports the unrepresentable sum with None.
3. Lower-bound subtraction
Problem: Compare exact zero with subtraction below unsigned zero.
- Zero minus zero remains at the lower bound.
- Zero minus one is negative and outside u8.
let a = 0_u8.checked_sub(0);
let b = 0_u8.checked_sub(1);
Illustrative fragment; not executed as a standalone program.
Expected result: a = Some(0); b = None
Why this result follows: checked_sub distinguishes a valid boundary from underflow.
4. Multiplication boundary
Problem: Compare two products near the unsigned upper bound.
- Fifteen times seventeen is exactly 255.
- Sixteen times sixteen is 256 and cannot fit in u8.
let a = 15_u8.checked_mul(17);
let b = 16_u8.checked_mul(16);
Illustrative fragment; not executed as a standalone program.
Expected result: a = Some(255); b = None
Why this result follows: checked_mul validates the product rather than its operands alone.
5. Checked zero divisor
Problem: Determine the outcome without dividing by zero normally.
- The divisor supplied to checked_div is zero.
- There is no integer quotient for this operation.
let result = 10_u8.checked_div(0);
Illustrative fragment; not executed as a standalone program.
Expected result: result = None
Why this result follows: checked_div returns None for a zero divisor.
6. Signed division overflow
Problem: Determine why this nonzero divisor still fails.
- i8::MIN is -128, and dividing by -1 mathematically gives 128.
- The i8 upper bound is 127, so that quotient does not fit.
let result = i8::MIN.checked_div(-1);
Illustrative fragment; not executed as a standalone program.
Expected result: result = None
Why this result follows: checked_div detects the signed overflow as well as zero divisors.
7. Negating signed limits
Problem: Compare negation near the negative boundary.
- Negating -127 gives the representable value 127.
- Negating -128 would require positive 128, outside i8.
let a = (-127_i8).checked_neg();
let b = i8::MIN.checked_neg();
Illustrative fragment; not executed as a standalone program.
Expected result: a = Some(127); b = None
Why this result follows: The signed range is asymmetric around zero.
8. Checked powers
Problem: Compare two successive powers of two in u8.
- Two to the seventh power equals 128.
- Two to the eighth is 256, one beyond the maximum.
let a = 2_u8.checked_pow(7);
let b = 2_u8.checked_pow(8);
Illustrative fragment; not executed as a standalone program.
Expected result: a = Some(128); b = None
Why this result follows: checked_pow reports whether the computed power fits.
9. Checked chain succeeds
Problem: Trace multiplication and addition in the checked chain.
- Twenty times ten fits and produces Some(200).
- The following checked addition yields the representable 250.
let result = 20_u8.checked_mul(10).and_then(|n| n.checked_add(50));
Illustrative fragment; not executed as a standalone program.
Expected result: result = Some(250)
Why this result follows: and_then runs the next step only when the first succeeds.
10. Second step fails
Problem: Locate the failure in this two-operation calculation.
- The multiplication fits and yields 200.
- Adding 60 would produce 260, which does not fit u8.
let result = 20_u8.checked_mul(10).and_then(|n| n.checked_add(60));
Illustrative fragment; not executed as a standalone program.
Expected result: result = None
Why this result follows: Each operation needs its own check even after an earlier success.
11. Saturation at both ends
Problem: Find the clamped values for addition and subtraction.
- The sum 270 exceeds the u8 upper bound 255.
- The difference -5 falls below the u8 lower bound zero.
let upper = 240_u8.saturating_add(30);
let lower = 4_u8.saturating_sub(9);
Illustrative fragment; not executed as a standalone program.
Expected result: upper = 255; lower = 0
Why this result follows: Saturating operations select the corresponding type boundary.
12. Signed saturation
Problem: Determine both signed saturation boundaries.
- The mathematical sum 140 exceeds i8::MAX, which is 127.
- The mathematical difference -140 is below i8::MIN, which is -128.
let upper = 120_i8.saturating_add(20);
let lower = (-120_i8).saturating_sub(20);
Illustrative fragment; not executed as a standalone program.
Expected result: upper = 127; lower = -128
Why this result follows: Signed saturation clamps to the appropriate asymmetric endpoint.
13. Unsigned wrapping
Problem: Compute both results modulo 256.
- The sum 260 has remainder four modulo 256.
- Subtracting one from zero wraps to the largest u8.
let a = 250_u8.wrapping_add(10);
let b = 0_u8.wrapping_sub(1);
Illustrative fragment; not executed as a standalone program.
Expected result: a = 4; b = 255
Why this result follows: Explicit wrapping gives modular results, not exact signed totals.
14. Signed wrapping
Problem: Trace wrapping across both i8 endpoints.
- Adding one to the maximum wraps to the minimum.
- Subtracting one from the minimum wraps to the maximum.
let a = 127_i8.wrapping_add(1);
let b = (-128_i8).wrapping_sub(1);
Illustrative fragment; not executed as a standalone program.
Expected result: a = -128; b = 127
Why this result follows: The explicit methods wrap within the eight-bit signed representation.
15. Wrapped value and flag
Problem: Compare the overflow flags on these two sums.
- The first exact sum 260 wraps to four and sets the flag.
- The second exact sum five fits, leaving its flag false.
let a = 250_u8.overflowing_add(10);
let b = 2_u8.overflowing_add(3);
Illustrative fragment; not executed as a standalone program.
Expected result: a = (4, true); b = (5, false)
Why this result follows: overflowing_add returns both the wrapped result and overflow indicator.
16. Overflow flag for subtraction
Problem: Trace the result and flag below the unsigned minimum.
- The exact difference is negative one, below zero.
- The wrapped byte is 255 and the underflow flag is true.
let result = 0_u8.overflowing_sub(1);
Illustrative fragment; not executed as a standalone program.
Expected result: result = (255, true)
Why this result follows: overflowing_sub reports that the exact result did not fit.
17. Cast versus checked conversion
Problem: Compare narrowing by cast and checked conversion.
- Narrowing the integer cast retains the low eight bits, which represent 44.
- TryFrom rejects 300 because it exceeds the u8 maximum.
let a = 300_u16 as u8;
let b = u8::try_from(300_u16);
Illustrative fragment; not executed as a standalone program.
Expected result: a = 44; b = Err(...)
Why this result follows: A cast applies conversion rules rather than validating the target range.
18. Signed conversion boundaries
Problem: Compare negative and maximum unsigned conversions.
- Negative one is outside the unsigned u8 interval.
- The value 255 is exactly the maximum and converts successfully.
let a = u8::try_from(-1_i16);
let b = u8::try_from(255_i16);
Illustrative fragment; not executed as a standalone program.
Expected result: a = Err(...); b = Ok(255)
Why this result follows: TryFrom reports whether the target type can represent the value.
19. Shift count versus value loss
Problem: Explain why only one checked shift returns None.
- Shift count eight equals the width of u8 and is rejected.
- Count one is valid, but shifting 128 left discards its high bit.
let a = 1_u8.checked_shl(8);
let b = 128_u8.checked_shl(1);
Illustrative fragment; not executed as a standalone program.
Expected result: a = None; b = Some(0)
Why this result follows: checked_shl checks the count, not preservation of the exact product.
20. Size and resource limit
Problem: Compute the checked record size and apply the limit.
- One hundred records times four bytes gives 400; the header makes 412.
- The result fits usize and does not exceed the limit 500.
let size = 100_usize.checked_mul(4).and_then(|n| n.checked_add(12));
let accepted = size.filter(|&n| n <= 500);
Illustrative fragment; not executed as a standalone program.
Expected result: size = Some(412); accepted = Some(412)
Why this result follows: Representability and the separate resource limit are both checked.
Common errors and fixes
A sum exceeds the type range
- Why it happens
- The exact result is not representable.
- How to fix it
- Use checked arithmetic and handle None.
- Prevent it next time
- Test the upper boundary.
A value changes during conversion
- Why it happens
- A narrowing cast did not validate the range.
- How to fix it
- Use a checked conversion.
- Prevent it next time
- Test values outside the target range.
A wrapped value is treated as exact
- Why it happens
- The arithmetic policy was not documented.
- How to fix it
- Choose the domain-required policy.
- Prevent it next time
- Document and test overflow behavior.
20 practice exercises
1. What does 250_u8.checked_add(5) return?
Show hint
Compare the exact sum with u8::MAX.
Show worked solution
It returns Some(255), the maximum u8 value. Adding one more would return None.
250 plus 5 equals 255, exactly u8::MAX, so checked_add returns Some(255). Adding one more to 255 returns None because 256 is outside the type’s range.
Check your solution
- 250_u8.checked_add(5) is Some(255)
- 255_u8.checked_add(1) is None
2. Why is value as u8 not a range check?
Show hint
Compare narrowing a value outside the target range with TryFrom.
Show worked solution
The cast applies conversion rules rather than reporting that every out-of-range value is invalid. Use a checked conversion when rejection is required.
For example, 300_u16 as u8 produces 44 after integer narrowing, whereas u8::try_from(300_u16) returns an error. A cast applies conversion rules without reporting that the original value was outside the target range.
Check your solution
- The cast produces 44
- TryFrom reports an error for 300
3. A u8 counter starts at 230 and receives increments of 20 then 6. Reject any increment that does not fit and retain the old count. Give both outcomes.
Show hint
Check each addition before assigning.
Show worked solution
230_u8.checked_add(20) returns Some(250), so store 250. Then 250_u8.checked_add(6) returns None because 256 is out of range; reject it and retain 250.
Check your solution
- The first increment stores 250
- The second is rejected and the count remains 250
4. A u8 inventory holds 4 units. Design a checked withdrawal for requests 4 and 5 from separate fresh inventories, preserving state on failure.
Show hint
Subtract only after checked_sub succeeds.
Show worked solution
For each fresh inventory call 4_u8.checked_sub(request). Request 4 returns Some(0) and can be stored; request 5 returns None, so report rejection and retain the original 4.
Check your solution
- Request 4 leaves 0
- Request 5 fails and leaves 4
5. A u16 order has 400 units at 200 cents each. Compute the exact total with checked multiplication and choose a wider intermediate if necessary.
Show hint
The mathematical product is 80000, above 65535.
Show worked solution
Convert both operands to u32 before multiplication and use checked_mul, producing Some(80000). A u16 checked multiplication would return None; the application must still enforce any separate price limit.
Check your solution
- The u16 product fails
- The u32 product is Some(80000)
6. A parser must distinguish a zero divisor from signed division overflow for i8 inputs. Classify (10, 0), (-128, -1), and (9, 3).
Show hint
Test the divisor separately before checked_div.
Show worked solution
If the divisor is zero report division by zero. Otherwise checked_div returns None for (-128, -1), which signals the unrepresentable quotient; (9, 3) returns Some(3).
Check your solution
- The first case reports zero divisor
- The second overflows and the third yields 3
7. Calculate 12 records times 10 bytes plus a 4-byte header using checked u8 operations. Then replace 12 with 26 and identify the failing step.
Show hint
Check the product before the addition.
Show worked solution
12_u8.checked_mul(10) gives 120 and checked_add(4) gives Some(124). With 26 records the product 260 exceeds u8, so multiplication returns None and the header addition must not run.
Check your solution
- The first calculation yields Some(124)
- The second fails during multiplication
8. An application returns Result<u8, &str> for a checked sum of 200 and 70. Explain how to preserve a meaningful error instead of silently returning zero.
Show hint
Convert the Option into a Result.
Show worked solution
Use 200_u8.checked_add(70).ok_or("total overflow"). The exact sum 270 does not fit, so the result is Err("total overflow"); the caller can propagate or handle that error.
Check your solution
- The operation returns Err("total overflow")
- No fabricated zero is returned
9. A display level u8 must clamp between 0 and 255. Starting at 10, apply a decrease of 20 and then an increase of 3 using saturating operations.
Show hint
Apply each operation to the previous clamped value.
Show worked solution
10_u8.saturating_sub(20) gives 0, then 0_u8.saturating_add(3) gives 3. Clamping intentionally loses the exact negative intermediate, so this policy must match the display requirement.
Check your solution
- The first result is 0
- The final level is 3
10. A u8 packet sequence deliberately wraps modulo 256. Starting from 254, generate the next three sequence values and explain why this differs from a checked counter.
Show hint
Use wrapping_add for each increment.
Show worked solution
The values are 255, 0, and 1. wrapping_add encodes the protocol’s modular rule; checked_add would return None at 255 + 1 and require an explicit error or alternative action.
Check your solution
- The sequence is 255, 0, 1
- Checked addition would reject the second step
11. Using overflowing_add on 180_u8 and 100, design a branch that rejects overflow. Give both the pair and the final decision.
Show hint
Inspect the boolean before accepting the value.
Show worked solution
180_u8.overflowing_add(100) returns (24, true), since 280 wraps modulo 256. Branch on the flag and reject the operation instead of treating 24 as the exact total.
Check your solution
- The pair is (24, true)
- The branch rejects the operation
12. For a u8 value of 250 plus 5, compare checked_add, saturating_add, wrapping_add, and overflowing_add. What can the saturated result alone tell you?
Show hint
All exact sums reach the boundary without exceeding it.
Show worked solution
The results are Some(255), 255, 255, and (255, false). Saturation alone cannot distinguish this exact boundary from an overflowing sum that also clamps to 255.
Check your solution
- All values are 255 and the overflow flag is false
- Saturation alone does not prove overflow
13. A developer tests ordinary u8 addition only with Cargo’s default release profile and assumes all builds wrap. Explain the flaw and propose an explicit policy.
Show hint
Profiles can enable checks and can be overridden.
Show worked solution
Default release disables overflow checks, while default dev enables them, and either can be configured differently. Use wrapping_add when modular behavior is required or checked_add when overflow must be rejected, and test that method directly.
Check your solution
- The dev and release defaults differ
- The selected explicit method encodes the required behavior
14. A division feature assumes disabling overflow checks makes every invalid division wrap. Evaluate 7_i8 / 0 and i8::MIN / -1, and propose a checked alternative.
Show hint
Division has special failure cases.
Show worked solution
Both ordinary divisions panic: one has a zero divisor, and the other has an unrepresentable signed quotient. checked_div returns None for both, so inspect the divisor separately if diagnostics must distinguish them.
Check your solution
- Both ordinary operations panic
- checked_div returns None for both
15. Convert 256_u16 and 42_u16 to u8 only if representable. Give the checked outcomes and contrast the first with an as cast.
Show hint
Use u8::try_from for a fallible conversion.
Show worked solution
u8::try_from(256_u16) returns Err, while u8::try_from(42_u16) returns Ok(42). By contrast, 256_u16 as u8 truncates high bits and gives 0, so it does not reject the out-of-range input.
Check your solution
- 256 gives Err and 42 gives Ok(42)
- The narrowing cast of 256 gives 0
16. A signed i16 reading must be converted to u8 and then limited to 0 through 100. Classify -1, 100, and 200.
Show hint
Type conversion and domain validation are separate.
Show worked solution
u8::try_from rejects -1. It accepts 100 and 200 as representable, after which the application accepts 100 but rejects 200 for exceeding its domain maximum.
Check your solution
- -1 fails conversion
- 100 is accepted and 200 fails domain validation
17. A developer uses 64_u8.checked_shl(2) to prove an exact multiplication by four. Evaluate it and propose a correct checked multiplication.
Show hint
A valid shift count does not preserve high bits.
Show worked solution
checked_shl(2) returns Some(0) because two is a valid shift count but the high bit is discarded. 64_u8.checked_mul(4) returns None because the exact product 256 does not fit.
Check your solution
- The shift yields Some(0)
- The exact checked multiplication yields None
18. A signed i8 sensor value is -128. Explain why abs as an ordinary signed result cannot represent its positive magnitude and give a checked operation.
Show hint
The positive endpoint is one smaller in magnitude.
Show worked solution
The mathematical absolute value is 128 but i8 ends at 127. i8::MIN.checked_abs() returns None, allowing the caller to reject or convert to an appropriately wider type before computing the magnitude.
Check your solution
- The exact magnitude 128 does not fit i8
- checked_abs returns None
19. A buffer has 40 records of 8 bytes and a 16-byte header, with an application limit of 300 bytes. Calculate the checked size and decide whether to allocate.
Show hint
Representability and the resource limit are independent.
Show worked solution
40_usize.checked_mul(8) yields Some(320), then checked_add(16) yields Some(336). The size is representable but exceeds 300, so the application rejects it before allocation.
Check your solution
- The computed size is Some(336)
- The resource limit rejects allocation
20. Design four tests for a u8 addition function that must reject overflow and leave an existing total unchanged. Include exact maximum and first overflow.
Show hint
Check result and state for both sides of each boundary.
Show worked solution
Test 0+0 gives 0, 10+20 gives 30, and 254+1 gives 255. Then test 255+1 reports failure and retains the old total 255; these cover ordinary behavior and the transition across the maximum.
Check your solution
- 254+1 succeeds with 255
- 255+1 fails while the stored total remains 255
Key takeaways
- Choose overflow behavior explicitly.
- Test boundary values and conversion failures.
- Check each arithmetic step before committing state.
- Saturation and wrapping implement policies rather than proving an exact result.
- Cargo profiles can change ordinary overflow checks; explicit methods encode the intended behavior.