merge: Money::checked_add and checked_sub return an error on overflow (branch t3/fix-money-checked-overflow, bac0ea22; reviewed)
check / check (push) Canceled after 0s
portable-macos / portable (macos-latest) (push) Canceled after 0s
portable-windows / portable (windows-latest) (push) Canceled after 0s
two-user / two-user (push) Canceled after 0s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-08 10:14:00 -07:00
commit 69cfc81bb4
1 file changed
+46 -4
+46 -4
View File
@@ -129,16 +129,27 @@ impl Money {
Ok(())
}
/// Add two money values. Fails on currency mismatch.
/// Add two money values. Fails on currency mismatch, and with
/// `TooLargeToCompute` when the sum is past exact arithmetic (never a
/// panic, never rounded).
pub fn checked_add(self, rhs: Money) -> Result<Money, LedgerError> {
self.check_currency(&rhs)?;
Ok(Money::new(self.amount + rhs.amount, self.currency))
let amount = self
.amount
.checked_add(rhs.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{} plus {}", self, rhs)))?;
Ok(Money::new(amount, self.currency))
}
/// Subtract two money values. Fails on currency mismatch.
/// Subtract two money values. Fails on currency mismatch, and with
/// `TooLargeToCompute` when the difference is past exact arithmetic.
pub fn checked_sub(self, rhs: Money) -> Result<Money, LedgerError> {
self.check_currency(&rhs)?;
Ok(Money::new(self.amount - rhs.amount, self.currency))
let amount = self
.amount
.checked_sub(rhs.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{} minus {}", self, rhs)))?;
Ok(Money::new(amount, self.currency))
}
}
@@ -247,6 +258,37 @@ mod tests {
);
}
#[test]
fn checked_arithmetic_refuses_overflow_instead_of_panicking() {
let max = usd(Decimal::MAX);
let min = usd(Decimal::MIN);
assert!(matches!(
max.checked_add(max),
Err(LedgerError::TooLargeToCompute(_))
));
assert!(matches!(
min.checked_add(min),
Err(LedgerError::TooLargeToCompute(_))
));
assert!(matches!(
min.checked_sub(max),
Err(LedgerError::TooLargeToCompute(_))
));
assert!(matches!(
max.checked_sub(min),
Err(LedgerError::TooLargeToCompute(_))
));
// At the edge, exact results still work.
assert_eq!(max.checked_add(min).unwrap().amount, Decimal::ZERO);
assert_eq!(max.checked_sub(max).unwrap().amount, Decimal::ZERO);
// Currency mismatch still reports as a mismatch.
let eur = Money::new(Decimal::ONE, Currency::new("EUR").unwrap());
assert!(matches!(
max.checked_add(eur),
Err(LedgerError::CurrencyMismatch { .. })
));
}
/// ISO 4217 list one (docs/spec/sources/iso-4217.md): one code from
/// each exponent class, and the codes with no minor unit.
#[test]