Skip to main content

ssh_encoding/
checked.rs

1//! Checked arithmetic helpers.
2
3use crate::{Error, Result};
4
5/// Extension trait for providing checked [`Iterator::sum`]-like functionality.
6#[diagnostic::on_unimplemented(
7    note = "Consider adding an impl of `IntoIterator<Item = usize>` to `{Self}`"
8)]
9pub trait CheckedSum<A>: Sized {
10    /// Iterate over the values of this type, computing a checked sum.
11    ///
12    /// # Errors
13    /// Returns [`Error::Length`] on overflow.
14    fn checked_sum(self) -> Result<A>;
15}
16
17impl<T> CheckedSum<usize> for T
18where
19    T: IntoIterator<Item = usize>,
20{
21    fn checked_sum(self) -> Result<usize> {
22        self.into_iter()
23            .try_fold(0, usize::checked_add)
24            .ok_or(Error::Length)
25    }
26}