#no-std #numeric

no-std upcast-arithmetic

Arithmetic that is upcasted on overflow

6 releases

0.1.2 Aug 13, 2022
0.1.1 Aug 13, 2022
0.0.2 Jul 11, 2022

#1144 in Math

MIT license

19KB
292 lines

upcast-arithmetic

Utility library for dealing with arithmetic on type limits by upcasting into types with higher limits.

Examples

Without upcast_arithmetic

let a = u8::MAX;
let b = 2u8;

let modulo = u8::MAX;

let res = (a + b) % modulo;
assert_eq!(res, 2);

With upcast_arithmetic

use upcast_arithmetic::*;

let a = u8::MAX;
let b = 2u8;

let modulo = u8::MAX;

let res = a.upcast_add_mod(b, modulo);
assert_eq!(res, 2);

License: MIT


lib.rs:

Crates.io docs.rs GitHub license Rust

Utility library for dealing with arithmetic on type limits by upcasting into types with higher limits.

Examples

Without upcast_arithmetic (panics)

let a = u8::MAX;
let b = 2u8;

let modulo = u8::MAX;

let res = (a + b) % modulo;
assert_eq!(res, 2);

With upcast_arithmetic

use upcast_arithmetic::*;

let a = u8::MAX;
let b = 2u8;

let modulo = u8::MAX;

let res = a.upcast_add_mod(b, modulo);
assert_eq!(res, 2);

Performance

The performance overhead is very small. In benchmarks it seems like there is only a neglegible performance penelty, compared to assuming no overflow occurs.

no_std

The crate is fully #![no_std] compatible.

Unsafe

There is no unsafe code and the flag #![deny(unsafe_code)] is set.

No runtime deps