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
50
51
52
53
54
55
56
57
58
59
use crate::common::*;

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Default)]
pub struct AddCollector<A>(pub Option<A>);

impl<A> FromIterator<A> for AddCollector<A>
where
    A: Add<A, Output = A>,
{
    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
        let sum = iter.into_iter().fold1(|lhs, rhs| lhs + rhs);
        Self(sum)
    }
}

impl<A> AddCollector<A> {
    pub fn unwrap(self) -> A {
        self.0.unwrap()
    }

    pub fn get(self) -> Option<A> {
        self.0
    }
}

impl<A> From<AddCollector<A>> for Option<A> {
    fn from(collector: AddCollector<A>) -> Self {
        collector.0
    }
}

impl<A> Extend<A> for AddCollector<A>
where
    A: Add<A, Output = A>,
{
    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
        let sum = self
            .0
            .take()
            .into_iter()
            .chain(iter)
            .fold1(|lhs, rhs| lhs + rhs);
        self.0 = sum;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn add_test() {
        let mut sum: AddCollector<usize> = iter::repeat(1).take(100).collect();
        assert_eq!(sum.unwrap(), 100);

        sum.extend(1..=100);
        assert_eq!(sum.unwrap(), 5150);
    }
}