Financial Ops
This crate provides a set of operations for working with financial data, more specifically, avoiding the usage of floating point types.
Usage
use CheckedDecimalOperations;
Very useful when dealing with money or blockchain transactions.
Supported operations
Checked
This set of operations will return an Result with the result and the number of decimals,
if the operation is successful. If the operation is not successful, it will return a DecimalOperationError.
use CheckedDecimalOperations;
add_decimals_checkedsub_decimals_checkedmul_decimals_checkeddiv_decimals_checkedrem_decimals_checked
Each of these has an _or variant that lets you choose the error type (any
value — your own enum, or even a &str — no external crate required), mirroring
the @ syntax of the checked! macro:
use CheckedDecimalOperations;
let result = u32MAX.add_decimals_checked_or;
assert_eq!;
// The error can also just be a string:
let r: = 10u64.divide_decimals_checked_or;
assert_eq!;
add_decimals_checked_orsub_decimals_checked_ormultiply_decimals_checked_ordivide_decimals_checked_orrem_decimals_checked_or
Unchecked
This set of operations will return the result and the number of decimals, without any checks, carrying the underlying operation way of handling overflows and underflows.
use DecimalOperations;
add_decimalssub_decimalsmul_decimalsdiv_decimalsrem_decimals
The checked! macro
The checked! macro rewrites a normal arithmetic expression into a chain of
checked operations, recursively, while respecting operator precedence and
parentheses. Without an error it evaluates to an Option; with a trailing
@ <error> it evaluates to a Result.
use checked;
// Respects precedence: this is `a + (b * c)`, fully checked.
let value: = checked! ;
assert_eq!;
// Overflow short-circuits to `None`.
assert_eq!;
// With `@ <error>` you get a `Result<T, E>`, where `E` is simply the type of
// the expression you pass. A string literal makes `E = &str` — no `anyhow`,
// no external crate, no trait bounds.
let ok: = checked! ;
assert_eq!;
let err: = checked! ;
assert_eq!;
Because @ <error> expands to .ok_or(<error>), the error can be anything: a
&str, your own enum variant, etc. To use ? on the result, the surrounding
function's error type just needs to be the same type (or From it).
Supported operators: +, -, *, /, % (mapped to checked_add,
checked_sub, checked_mul, checked_div, checked_rem). Each operand is
evaluated exactly once, in left-to-right order.