collected/
max.rs

1use crate::common::*;
2
3/// A collection that computes the maximum value.
4#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Default)]
5pub struct MaxVal<A>(Option<A>);
6
7impl<A> FromIterator<A> for MaxVal<A>
8where
9    A: Ord,
10{
11    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
12        let max = iter.into_iter().fold1(|lhs, rhs| lhs.max(rhs));
13        Self(max)
14    }
15}
16
17impl<A> MaxVal<A> {
18    pub fn unwrap(self) -> A {
19        self.0.unwrap()
20    }
21
22    pub fn get(&self) -> Option<&A> {
23        self.0.as_ref()
24    }
25
26    pub fn into_inner(self) -> Option<A> {
27        self.0
28    }
29}
30
31impl<A> From<MaxVal<A>> for Option<A> {
32    fn from(collector: MaxVal<A>) -> Self {
33        collector.0
34    }
35}
36
37impl<A> Extend<A> for MaxVal<A>
38where
39    A: Ord,
40{
41    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
42        let max = self
43            .0
44            .take()
45            .into_iter()
46            .chain(iter)
47            .fold1(|lhs, rhs| lhs.max(rhs));
48        self.0 = max;
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn max_test() {
58        let mut max: MaxVal<usize> = (1..100).collect();
59        assert_eq!(max.unwrap(), 99);
60
61        max.extend(100..200);
62        assert_eq!(max.unwrap(), 199);
63    }
64}