1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use std::iter::{self, empty, once};

use crate::Reductor;

/// Reductor that adds items yielded by an iterator to each other (similary to [`Iterator::sum`]).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Sum<T>(pub T);

impl<T> Default for Sum<T>
where
    T: iter::Sum,
{
    #[inline]
    fn default() -> Self {
        Self(empty::<T>().sum())
    }
}

impl<A, T> Reductor<A> for Sum<T>
where
    T: iter::Sum + iter::Sum<A>,
{
    type State = T;

    fn new(item: A) -> Self::State {
        once(item).sum()
    }

    fn reduce(state: Self::State, item: A) -> Self::State {
        once(state).chain(once(Self::new(item))).sum()
    }

    fn into_result(state: Self::State) -> Self {
        Self(state)
    }
}

#[cfg(test)]
mod tests {
    use crate::Reduce;

    use super::*;

    #[test]
    fn test_sum_borrowed() {
        let Sum::<f64>(_) = [].iter().reduce_with();
    }
}