safe_math
A procedural macro-based library that transforms standard arithmetic operations into their checked equivalents at compile time, preventing overflow, underflow, and division by zero errors.
Overview
safe-math
provides:
- Compile-time transformation of arithmetic operations into checked variants without runtime overhead
- Comprehensive error handling via
Result
types - Support for custom types through derive macros
Core Functionality
Basic Operations
The #[safe_math]
attribute transforms arithmetic operations into their checked equivalents:
use safe_math;
assert_eq!;
assert_eq!;
Supported Operations
All basic arithmetic operations are supported:
- Addition (
+
,+=
) - Subtraction (
-
,-=
) - Multiplication (
*
,*=
) - Division (
/
,/=
) - Remainder (
%
,%=
)
Error Handling
Operations return SafeMathError
for exceptional cases:
Type Support
Built-in support for:
- Unsigned integers:
u8
throughu128
,usize
- Signed integers:
i8
throughi128
,isize
- Floating point:
f32
,f64
(with infinity/NaN handling)
Advanced Usage
Custom Types
Enable the derive
feature to implement safe arithmetic for custom types:
use SafeMathOps;
;
Note: For the derive to work, your type must implement both the standard arithmetic traits
(like Add
, Sub
, Mul
, Div
, Rem
) and their checked counterparts (like CheckedAdd
,
CheckedSub
, CheckedMul
, CheckedDiv
, CheckedRem
) from the num-traits
crate.
This requirement exists because without knowing what a type represents, it's impossible to determine what operations are safe to perform or what constitutes a "checked" operation.
Block-Level Safety
Use safe_math_block!
to apply checked operations to a specific block of code:
use safe_math_block;
This is useful when you want to:
- Apply safe arithmetic to specific expression
- Mix checked and unchecked operations in the same function
Roadmap
Planned upcoming features:
-
Option-returning functions Support for functions that return
Option<T>
instead ofResult<T, SafeMathError>
. -
Crate-level macro support Ability to apply
#[safe_math]
to the entire crate with a single attribute:
// main.rs or lib.rs
License
Licensed under either:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
Contributing
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you shall be dual licensed as above, without any additional terms or conditions.