#iterator #checked #up #sum #integer #implemented #safely

checked_sum

A library safely summing up iterators

1 unstable release

0.1.0 Oct 25, 2024

#1220 in Rust patterns

Download history 95/week @ 2024-10-20 18/week @ 2024-10-27

113 downloads per month

MIT license

6KB
59 lines

checked_sum

Crates.io Docs.rs License

Utility crate for summing up iterators in a safe way. The CheckedSum trait is implemented for any iterator of items implementing CheckedAdd, which in turn is implemented for all integer primitives but can also be implemented for other types like newtypes wrapping integers.

use checked_sum::CheckedSum;

// If the sum fits into the type, it is returned
let numbers = vec![1u8, 2, 3, 4, 5];
assert_eq!(numbers.into_iter().checked_sum(), Some(15),);

// If the sum overflows, `None` is returned
let numbers = vec![255u8, 1];
assert_eq!(numbers.into_iter().checked_sum(), None,);

lib.rs:

Utility crate for summing up iterators in a safe way. The CheckedSum trait is implemented for any iterator of items implementing CheckedAdd, which in turn is implemented for all integer primitives but can also be implemented for other types like newtypes wrapping integers.

use checked_sum::CheckedSum;

// If the sum fits into the type, it is returned
let numbers = vec![1u8, 2, 3, 4, 5];
assert_eq!(numbers.into_iter().checked_sum(), Some(15),);

// If the sum overflows, `None` is returned
let numbers = vec![255u8, 1];
assert_eq!(numbers.into_iter().checked_sum(), None,);

No runtime deps