collected/
min.rs

1use crate::common::*;
2
3/// A collection that computes the minimum value.
4#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Default)]
5pub struct MinVal<A>(Option<A>);
6
7impl<A> FromIterator<A> for MinVal<A>
8where
9    A: Ord,
10{
11    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
12        let min = iter.into_iter().fold1(|lhs, rhs| lhs.min(rhs));
13        Self(min)
14    }
15}
16
17impl<A> MinVal<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<MinVal<A>> for Option<A> {
32    fn from(collector: MinVal<A>) -> Self {
33        collector.0
34    }
35}
36
37impl<A> Extend<A> for MinVal<A>
38where
39    A: Ord,
40{
41    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
42        let min = self
43            .0
44            .take()
45            .into_iter()
46            .chain(iter)
47            .fold1(|lhs, rhs| lhs.min(rhs));
48        self.0 = min;
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn min_test() {
58        let mut min: MinVal<isize> = (1..100).collect();
59        assert_eq!(min.unwrap(), 1);
60
61        min.extend((-200)..(-100));
62        assert_eq!(min.unwrap(), -200);
63    }
64}