Skip to content

Check Arithmetic Before Assigning State

The Course
•
28 min study

Day 4 turns the checked values from earlier in the week into state that changes. A stock quantity is a u32: it can never be negative and it has a fixed maximum. A change arrives as a signed delta, an i64, because a batch can both add and remove stock. Rust will not let you write old + delta across two integer types, and even within one type the plain + operator is the wrong tool for a ledger: in a debug build it panics on overflow, and in a release build it silently wraps around. Neither is an error your caller can handle.

The approach in this lesson has three stages. Widen the old quantity to i64 with the lossless i64::from, add with checked_add, which returns None instead of overflowing, and then narrow the result back with u32::try_from. Each stage can fail for a different reason. The addition fails only when the mathematical sum does not fit an i64. The conversion fails when the sum is a perfectly good i64 that is not a valid stock quantity: negative, or above u32::MAX. Keeping those two errors apart tells the caller whether the input was absurd or merely too large for this domain. The old value stays untouched in every failure, because nothing is assigned until all three stages succeed.

Predict and run

Which case fails the addition itself? Which fails the quantity conversion?

Predict, then run Rust
fn adjust(old: u32, delta: i64) -> Result<u32, &'static str> {
    let next = i64::from(old).checked_add(delta).ok_or("overflow")?;
    u32::try_from(next).map_err(|_| "out of range")
}
fn main() {
    for delta in [-6, -5, 2, i64::MAX] {
        println!("{delta}: {:?}", adjust(5, delta));
    }
}
Check your prediction
Text
-6: Err("out of range")
-5: Ok(0)
2: Ok(7)
9223372036854775807: Err("overflow")

-6 produces the i64 value -1, which exists but is not a quantity, so the conversion rejects it. -5 lands exactly on zero, the lowest valid stock. Only i64::MAX overflows the addition. Now try adjust(u32::MAX, 1) and predict before running: the i64 sum 4294967296 is fine, so the error must come from the conversion. Notice that the overflow branch is reachable only for enormous deltas, since any u32 plus any delta below about nine quintillion fits an i64. It is still worth handling, because the parser accepts every i64.

Why not saturate or wrap?

The standard library offers several arithmetic families, and choosing among them is a design decision, not a style preference. Run this comparison of four ways to take 3 units from a stock of 2.

Compare the arithmetic families Rust
fn main() {
    let stock: u32 = 2;
    let take: u32 = 3;
    println!("checked:    {:?}", stock.checked_sub(take));
    println!("saturating: {}", stock.saturating_sub(take));
    println!("wrapping:   {}", stock.wrapping_sub(take));
    let delta: i32 = -3;
    println!("signed:     {:?}", stock.checked_add_signed(delta));
}
Text
checked:    None
saturating: 0
wrapping:   4294967295
signed:     None

Saturating arithmetic clamps to zero, so the ledger would record that 3 units were removed while only 2 existed. Wrapping arithmetic invents four billion units. Both are correct tools elsewhere, saturation for a volume slider and wrapping for hashes, but in a ledger they hide a rejected request behind a plausible number. checked_* makes the failure a value the type system forces you to handle.

checked_add_signed is a tidy one-step alternative, but on u32 it takes an i32 delta. Using it would mean narrowing the parsed i64 first, adding a third failure case. Widening to i64 keeps one conversion at the end and works for every delta the format accepts.

If you reach for the operator anyway, the compiler stops you before the overflow question even arises:

Rust
fn adjust(old: u32, delta: i64) -> u32 {
    old + delta
}

Compiling reports error[E0308]: mismatched types together with error[E0277]: cannot add i64 to u32. Rust never converts integer types implicitly, so every widening and narrowing is visible in the source.

Widen, compute, narrow once

Do the arithmetic in a type wide enough to hold every intermediate value, then narrow once at the end. That gives you exactly one place where domain limits are enforced, and later rules, such as a maximum quantity, can sit right after it.

Practice

Exercise

Your turn

Write transfer(from: u32, to: u32, amount: u32) -> Result<(u32, u32), &'static str> that returns both new balances. Reject a source that cannot cover the amount with "insufficient funds" and a destination that would overflow with "destination overflow". Print these four calls:

  • transfer(5, 10, 5) should be Ok((0, 15)), the exact-depletion boundary.
  • transfer(4, 10, 5) should be Err("insufficient funds").
  • transfer(5, u32::MAX, 1) should be Err("destination overflow").
  • transfer(4, u32::MAX, 5) fails both checks. Decide which error wins and make the choice deliberate.
Your working space Rust
fn main() {
    // Return the two new balances together after checking both calculations.
}
Hint 1: the idea

Compute both candidate values in local variables. Return the pair only when both checks succeed, so no caller can ever receive half a transfer.

Hint 2: a first step

Use from.checked_sub(amount) and to.checked_add(amount), each followed by .ok_or(...)?. The order of those two lines decides which error is reported when both would fail.

Worked solution
Run the solution Rust
fn transfer(from: u32, to: u32, amount: u32) -> Result<(u32, u32), &'static str> {
    let from = from.checked_sub(amount).ok_or("insufficient funds")?;
    let to = to.checked_add(amount).ok_or("destination overflow")?;
    Ok((from, to))
}

fn main() {
    println!("{:?}", transfer(5, 10, 5));
    println!("{:?}", transfer(4, 10, 5));
    println!("{:?}", transfer(5, u32::MAX, 1));
    println!("{:?}", transfer(4, u32::MAX, 5));
}
Text
Ok((0, 15))
Err("insufficient funds")
Err("destination overflow")
Err("insufficient funds")

Returning the pair gives the caller a complete replacement state or an error, never a debited source with an unchanged destination. The last line shows that check order is part of the contract: the source is checked first, so a caller sees the problem they can most likely fix. The next lesson applies the same rule to a whole batch of changes.

Was this article helpful?

Your response is saved on this device.