checked!() { /* proc-macro */ }Expand description
Recursively rewrites an arithmetic expression into checked arithmetic.
See the financial_ops_macros::checked documentation for details and
examples.
Recursively rewrites an arithmetic expression into checked arithmetic.
The macro walks the parsed expression tree, so it honors normal Rust operator precedence and parentheses. Every binary operator is replaced by its checked counterpart and the operands are threaded together so each sub-expression is evaluated exactly once, in left-to-right order.
§Result vs. Option
- Without an error, the macro evaluates to an
Option<T>(it isNoneas soon as any step overflows or divides by zero):
ⓘ
let total: Option<u64> = checked! { a + b * c };- With a trailing
@ <error expression>, the macro evaluates to aResult<T, E>, mapping the first failing step to the given error:
ⓘ
let total = checked! { a + b * c @ MyError::Overflow }?;§Supported operators
+ → checked_add, - → checked_sub, * → checked_mul,
/ → checked_div, % → checked_rem.
§Examples
ⓘ
use financial_ops::checked;
// Respects precedence: this is `a + (b * c)`, fully checked.
let value = checked! { 2u64 + 3 * 4 };
assert_eq!(value, Some(14));
// Overflow short-circuits to `None`.
assert_eq!(checked! { u8::MAX + 1u8 }, None);