Guard Billing Totals With checked_mul And saturating_add
Chain checked_mul and checked_add to catch integer overflow when summing invoice lines, while using saturating_add to clamp cumulative telemetry caps.
Code
fn invoice_total_cents(lines: &[(u64, u64)], fee_cents: u64) -> Option<u64> {
let mut subtotal: u64 = 0;
for &(unit_cents, qty) in lines {
let line_cost = unit_cents.checked_mul(qty)?;
subtotal = subtotal.checked_add(line_cost)?;
}
subtotal.checked_add(fee_cents)
}
fn add_bounded_usage(current: u32, delta: u32, cap: u32) -> u32 {
current.saturating_add(delta).min(cap)
}
fn main() {
let valid_lines = [(1_250, 4), (499, 3)];
println!("valid invoice: {:?}", invoice_total_cents(&valid_lines, 150));
let overflow_lines = [(u64::MAX / 2, 3)];
println!("overflow mul: {:?}", invoice_total_cents(&overflow_lines, 0));
let near_max_lines = [(u64::MAX - 5, 1), (10, 1)];
println!("overflow add: {:?}", invoice_total_cents(&near_max_lines, 0));
let mut quota_used = 950_u32;
for batch in [40, 100, u32::MAX] {
quota_used = add_bounded_usage(quota_used, batch, 1_000);
println!("usage after +{batch}: {quota_used}");
}
}Behavior overview — Guard Billing Totals With checked_mul And saturating_add
Guard Billing Totals With checked_mul And saturating_add keeps everything in the functions invoice_total_cents, add_bounded_usage and main.
One loop does the cycling here: for &(unit_cents, qty) in lines.
Points of care
- Isolated implementation — zero imports outside capabilities shipped with the runtime.
Using it
Entry signature: fn invoice_total_cents(lines: &[(u64, u64)
The demo output is labeled (valid invoice:, overflow mul:, overflow add:); each label names the call that printed it.
The demo flow inside main is invoice_total_cents and add_bounded_usage — run the file to see it end to end.
Key statements
fn invoice_total_cents(lines: &[(u64, u64)], fee_cents: u64) -> Option<u64> {
let mut subtotal: u64 = 0;
for &(unit_cents, qty) in lines {
let line_cost = unit_cents.checked_mul(qty)?;
subtotal = subtotal.checked_add(line_cost)?;
}
subtotal.checked_add(fee_cents)
}
fn add_bounded_usage(current: u32, delta: u32, cap: u32) -> u32 {
current.saturating_add(delta).min(cap)
}
Interactive Tools for This Topic
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.
FAQ
- What does Guard Billing Totals With checked_mul And saturating_add print when run?
- Execute the whole file; each printed line is prefixed with a label like `valid invoice:`, `overflow mul:`, `overflow add:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.