Safe-math-rs – write normal math expressions safely(overflow-checked, no panics)

1 gotenjbz 1 6/16/2025, 3:02:53 AM github.com ↗

Comments (1)

gotenjbz · 3h ago
Hi all, I just released safe-math-rs, a Rust library that lets you write normal arithmetic expressions (a + b * c / d) while automatically checking all operations for overflow and underflow.

It uses a simple procedural macro: #[safe_math], which rewrites standard math into its checked_* equivalents behind the scenes.

Example: use safe_math_rs::safe_math;

#[safe_math] fn calculate(a: u8, b: u8) -> Result<u8, ()> { Ok((a + b * 2) / 3) }

assert_eq!(calculate(9, 3), Ok(5)); assert!(calculate(255, 1).is_err()); // overflow Under the hood: Your code:

#[safe_math] fn add(a: u8, b: u8) -> Result<u8, ()> { Ok(a + b) } Becomes:

fn add(a: u8, b: u8) -> Result<u8, ()> { Ok(self.checked_add(rhs).ok_or(())?) } Looking for: Feedback on the macro's usability, syntax, and integration into real-world code

Bug reports

GitHub: https://github.com/GotenJBZ/safe-math-rs

So long, and thanks for all the fish