Open
Description
The Rust language team decided not to add CheckedSum
and CheckedProduct
traits to core rust-lang/rust#95485 but it was suggested that they be added here.
These traits allow you to add (or multiply) together all numbers in an iterator but return None
instead of panicking or wrapping if an overflow occurs.
I think the best way to do it is with a blanket implementation:
pub trait CheckedSum<A = Self> : Sized {
fn checked_sum<I: Iterator<Item = A>>(iter: I) -> Option<Self>;
}
impl<T> CheckedSum<T> for T where T : CheckedAdd + Sized + crate::identities::Zero
{
fn checked_sum<I: Iterator<Item = Self>>(iter: I) -> Option<Self> {
let mut total = Self::zero();
for i in iter{
total = total.checked_add(&i)?;
}
Some(total)
}
}
I will submit a pull request and if that is accepted I might do the same for Overflowing, Saturating, and Wrapping
Metadata
Metadata
Assignees
Labels
No labels