Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CheckedSum and CheckedProduct traits #250

Open
wainwrightmark opened this issue Nov 2, 2022 · 0 comments · May be fixed by #251
Open

Add CheckedSum and CheckedProduct traits #250

wainwrightmark opened this issue Nov 2, 2022 · 0 comments · May be fixed by #251

Comments

@wainwrightmark
Copy link

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

@wainwrightmark wainwrightmark linked a pull request Nov 2, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant