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 MaxCollector<A>(pub Option<A>);

impl<A> FromIterator<A> for MaxCollector<A>
where
    A: Ord,
{
    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
        let max = iter.into_iter().fold1(|lhs, rhs| lhs.max(rhs));
        Self(max)
    }
}

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

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

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

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

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

    #[test]
    fn max_test() {
        let mut max: MaxCollector<usize> = (1..100).collect();
        assert_eq!(max.unwrap(), 99);

        max.extend(100..200);
        assert_eq!(max.unwrap(), 199);
    }
}