reductor/reductors/
sum.rs

1use std::iter::{self, empty, once};
2
3use crate::Reductor;
4
5/// Reductor that adds items yielded by an iterator to each other (similarly to [`Iterator::sum`]).
6#[repr(transparent)]
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub struct Sum<T>(pub T);
9
10impl<T> Default for Sum<T>
11where
12    T: iter::Sum,
13{
14    #[inline]
15    fn default() -> Self {
16        Self(empty::<T>().sum())
17    }
18}
19
20impl<A, T> Reductor<A> for Sum<T>
21where
22    T: iter::Sum + iter::Sum<A>,
23{
24    type State = T;
25
26    fn new(item: A) -> Self::State {
27        once(item).sum()
28    }
29
30    fn reduce(state: Self::State, item: A) -> Self::State {
31        once(state).chain(once(Self::new(item))).sum()
32    }
33
34    fn into_result(state: Self::State) -> Self {
35        Self(state)
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use crate::Reduce;
42
43    use super::*;
44
45    #[test]
46    fn test_sum_borrowed() {
47        let Sum::<f64>(_) = [].iter().reduce_with();
48    }
49}