Crate safe_arith

Crate safe_arith 

Source
Expand description

Safe arithmetic on integers, avoiding overflow and division by zero.

§Why not just use checked_* methods?

Rust’s built-in checked_add, checked_mul, etc. return Option<T>, which requires you to manually handle None cases without context about what went wrong. This crate provides:

  1. Explicit errors: Returns Result<T, ArithError> with explicit Overflow and DivisionByZero variants
  2. Mutation in place: Methods like SafeArith::safe_add_assign that mutate in place
  3. Iterator support: SafeArithIter::safe_sum method for safely summing iterators without overflow

§Examples

§Basic

use safe_arith::{ArithError, SafeArith};

let x = 10u32;
let y = 20u32;

// Returns Result<u32, ArithError> instead of Option<u32>
let sum = x.safe_add(y)?;
let diff = y.safe_sub(x)?;
let product = x.safe_mul(y)?;
let quotient = y.safe_div(x)?;

assert_eq!(u32::MAX.safe_add(1), Err(ArithError::Overflow));

assert_eq!(x.safe_div(0), Err(ArithError::DivisionByZero));

§Mutating methods

use safe_arith::SafeArith;

let mut x = 10u32;
x.safe_add_assign(5)?;
x.safe_mul_assign(2)?;
assert_eq!(x, 30);

§Safe sum for iterators

use safe_arith::SafeArithIter;

let numbers = vec![1u64, 2, 3, 4, 5];
let total = numbers.into_iter().safe_sum()?;

let overflow = vec![u64::MAX, 1];
assert!(overflow.into_iter().safe_sum().is_err());

Enums§

ArithError
Error representing the failure of an arithmetic operation.

Traits§

SafeArith
Trait providing safe arithmetic operations for built-in types.
SafeArithIter
Extension trait for iterators, providing a safe replacement for sum.

Type Aliases§

Result