skip to content

As the lead of a Rust codebase doing balance and fee arithmetic on untrusted amounts, what arithmetic rule would you set, and how would you enforce it?

level: principalimportance: should knowfreq 30%

answer

  1. intent per operation, not per profile
  2. error, panic, wrap or clamp
  3. make the type carry the rule
  4. a lint that sees every operator

basics

~20 s

Make every overflow-prone operation on money state its intent: checked methods returning errors for untrusted amounts, strict methods for internal invariants, Wrapping only where modular math is meant. Enforce it with Clippy's arithmetic_side_effects lint in money modules and amount newtypes.

solid answer

~40 s

I would ban bare `+`, `-`, `*`, `/` and narrowing `as` in the modules that handle balances and fees, because their behaviour depends on the build profile: debug panics, a default release build wraps. Untrusted amounts go through a domain newtype such as `Cents(u64)` whose methods use `checked_add` and `checked_sub` and return a `Result`, so overflow and insufficient funds become client errors rather than wrong balances or crashes. Internal invariants that can only fail through a bug use the `strict_` methods, stable since Rust 1.91, which panic in every build. Modular arithmetic, such as hashes, uses `Wrapping<T>`, and saturation is reserved for telemetry. Enforcement is mechanical: `#![deny(clippy::arithmetic_side_effects, clippy::cast_possible_truncation)]` on those modules, run in CI, plus overflow checks in the release profile as a backstop, accepting their small cost and the panic-as-denial-of-service risk they carry.

code

rust · 44 lines
rust
#![deny(clippy::arithmetic_side_effects, clippy::cast_possible_truncation)]

use std::num::Wrapping;

#[derive(Debug, PartialEq)]
pub enum LedgerError {
    Overflow,
    Insufficient,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cents(u64);

impl Cents {
    pub fn new(cents: u64) -> Self {
        Cents(cents)
    }
    /// Untrusted amounts: overflow is an error the caller must handle.
    pub fn credit(self, amount: Cents) -> Result<Cents, LedgerError> {
        self.0.checked_add(amount.0).map(Cents).ok_or(LedgerError::Overflow)
    }
    pub fn debit(self, amount: Cents) -> Result<Cents, LedgerError> {
        self.0.checked_sub(amount.0).map(Cents).ok_or(LedgerError::Insufficient)
    }
}

/// Internal invariant: overflow here is a bug, so panic in every build.
pub fn next_batch_id(id: u32) -> u32 {
    id.strict_add(1)
}

/// Deliberately modular arithmetic says so in its type.
pub fn checksum(bytes: &[u8]) -> u32 {
    let mut h = Wrapping(2_166_136_261u32);
    for &b in bytes {
        h ^= Wrapping(u32::from(b));
        h *= Wrapping(16_777_619u32);
    }
    h.0
}

pub fn fee(amount: u64) -> u64 {
    amount * 3 / 100 // rejected by the lint
}

go deeper

for a junior

Know that plain operators behave differently in debug and release, and that checked, wrapping, saturating and strict methods each fix one behaviour.

for a middle

Map each intent to its tool: checked plus Result for input, strict for invariants, Wrapping for modular math, Saturating for meters.

for a senior

Show how the policy is enforced: an amount newtype without operators, Clippy's arithmetic_side_effects and cast lints in CI, and edge tests at the type's limits.

for a principal

Own the trade-offs: lint scope versus noise, release overflow checks versus speed and panic risk, and why a ledger accepts a crash before a wrong balance.

## Why a rule is needed at all Rust gives every integer operator a profile-dependent behaviour: with Cargo's defaults, a debug build panics on overflow and a release build wraps in two's complement. Neither is a choice anyone made for the money path. A wrapped balance is silent corruption; a panic in a request handler is a crash an attacker can trigger. For a codebase that sums balances, computes fees and debits accounts from **untrusted amounts**, the lead's job is to replace "whatever the profile does" with an explicit, reviewable policy and a tool that enforces it. ## The policy, by intent Each overflow-prone operation falls into one of four intents, and each intent has one tool: | Intent | Tool | Failure mode | |---|---|---| | Untrusted input, money | `checked_*` inside an amount newtype, returning `Result` | error returned to the caller | | Internal invariant, overflow means a bug | `strict_*` (stable since Rust 1.91) | panic in every build | | Deliberately modular | `Wrapping<T>` or `wrapping_*` | wraps by design | | Bounded measurement | `Saturating<T>` or `saturating_*` | clamps by design | Two further rules cover conversions and division: - **Narrowing and sign-changing `as` casts are banned** in the money modules; fallible conversions return an error instead. Where a reinterpretation is genuinely intended, `cast_signed` and `cast_unsigned` (stable since Rust 1.87) make it visible by name. - **Divisors from input go through `checked_div` and `checked_rem`**, because division by zero and `MIN / -1` panic even in release. ## Making the type carry it The strongest enforcement is a type with no unchecked operators. A `Cents(u64)` newtype that does not implement `Add` exposes only `credit` and `debit` methods built on `checked_add` and `checked_sub`, so a reviewer cannot be handed `a + b` on money at all. Fees in basis points, currency precision and rounding rules live in the same type, which keeps the arithmetic in one audited place rather than spread across handlers. ## Enforcing the rest with lints - **`clippy::arithmetic_side_effects`** is an allow-by-default restriction lint that flags integer arithmetic that can overflow or panic. It skips `Wrapping`, `Saturating`, floats and constant contexts, so code that follows the policy passes and a stray `amount * 3` is rejected. - **`clippy::cast_possible_truncation`**, **`cast_sign_loss`** and **`cast_possible_wrap`** flag the lossy `as` casts; `as_conversions` bans every `as` where that is preferable. - Scope matters: denying these crate-wide in a large codebase produces noise in index arithmetic that is already bounded, and noise trains people to `#[allow]` reflexively. Apply them to the money crates or modules, or set them in the manifest's lints table for those crates (Cargo's lint configuration), and run `cargo clippy` with warnings as errors in CI. ## The release-profile backstop and its trade-offs Turning on overflow checks in the release profile (a Cargo profile setting covered with Cargo's profiles) converts any operator the policy missed from silent wrapping into a panic. Weigh it honestly: 1. **Cost**: a compare and branch per operation; usually small, sometimes measurable in tight numeric loops, so benchmark the hot paths rather than guess. 2. **Availability**: a panic in a server is a crash or a dropped request; a single malicious input can become a denial of service. The policy above, not the backstop, is what turns overflow into a clean error response. 3. **Correctness**: for a ledger, a crash is far better than a wrong balance written to storage. That asymmetry is why money code usually accepts the cost. ## What to review and test - Edge tests at `u64::MAX`, zero, and the debit-exceeds-balance case for every amount method. - Property tests over random large amounts, which find overflow paths hand-written cases miss (the property-testing material covers the tooling). - A short written rule in the contributing guide naming the four intents, so a reviewer can ask "which intent is this?" of every new operator. There is no single right answer for all codebases: a game engine's physics loop and a ledger's settlement path deserve different defaults. The judgment a lead is asked to show is placing the strict rule where a wrong number costs money and leaving bounded, performance-sensitive code alone.

  • Why does Clippy flag `amount * 3` but not `amount * 3 / 100`'s division by 100?
    `arithmetic_side_effects` skips operations it can prove cannot overflow or panic, and dividing an unsigned value by a non-zero constant can do neither. The multiplication by 3 can overflow for large amounts, so that is the part reported. A `checked_mul(3)` followed by the division satisfies the lint.
  • When would you not turn on release overflow checks?
    When the code is performance-critical, its arithmetic is already bounded by construction, and a panic costs more than the risk it covers: a frame-time-sensitive game loop, or a decoder benchmarked to regress. Even then, the money and input-parsing crates keep explicit checked methods, because the backstop was only ever the second line.

  • Release builds check overflow, so no explicit policy is needed.
  • saturating arithmetic is the safe default for balances.
  • Denying arithmetic_side_effects across the whole codebase has no cost.
  • Turning on release overflow checks makes the code correct, not just loud.
  • strict_add returns None on overflow like checked_add.

Assumes Rust 1.99 and the Clippy it ships; the strict_ integer methods are stable since Rust 1.91 and cast_signed / cast_unsigned since Rust 1.87.