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