Provides a macro make checked math pretty easy.
# #[macro_use] extern crate cheque;
# fn main() {
let a = 10u8;
let b = 20u8;
let_checked![a, b];
assert_eq!(a + b, 30);
assert_eq!(b * b, None);
assert_eq!(b / 0, None);
assert_eq!(a - 20, None);
assert_eq!((a - b) + 1, None);
# }
let_checked!
redeclares each identifier as a checked numeric value.
You can then use +
, etc. on the checked variables, and then deref the result to get an
Option<_>
.
You can also use numeric literals/unchecked values, so long as they are on the right side of the operation.
# #[macro_use] extern crate cheque;
# fn main() {
let c = 20usize;
let_checked![c];
if let Some(scary) = *(c - 100) {
panic!("Ahh! {:?}", scary);
}
# }
If you are doing generic programming, you should add the [checked num_traits] to your
where
bounds.
[checked num_traits]: http://rust-num.github.io/num/num_traits/ops/checked/index.html