stats/
minmax.rs

1use std::default::Default;
2use std::fmt;
3use std::iter::{FromIterator, IntoIterator};
4
5use Commute;
6
7/// A commutative data structure for tracking minimum and maximum values.
8///
9/// This also stores the number of samples.
10#[derive(Clone)]
11pub struct MinMax<T> {
12    len: u64,
13    min: Option<T>,
14    max: Option<T>,
15}
16
17impl<T: PartialOrd + Clone> MinMax<T> {
18    /// Create an empty state where min and max values do not exist.
19    pub fn new() -> MinMax<T> {
20        Default::default()
21    }
22
23    /// Add a sample to the data.
24    pub fn add(&mut self, sample: T) {
25        self.len += 1;
26        if self.min.as_ref().map(|v| &sample < v).unwrap_or(true) {
27            self.min = Some(sample.clone());
28        }
29        if self.max.as_ref().map(|v| &sample > v).unwrap_or(true) {
30            self.max = Some(sample);
31        }
32    }
33
34    /// Returns the minimum of the data set.
35    ///
36    /// `None` is returned if and only if the number of samples is `0`.
37    pub fn min(&self) -> Option<&T> {
38        self.min.as_ref()
39    }
40
41    /// Returns the maximum of the data set.
42    ///
43    /// `None` is returned if and only if the number of samples is `0`.
44    pub fn max(&self) -> Option<&T> {
45        self.max.as_ref()
46    }
47
48    /// Returns the number of data point.
49    pub fn len(&self) -> usize {
50        self.len as usize
51    }
52}
53
54impl<T: PartialOrd> Commute for MinMax<T> {
55    fn merge(&mut self, v: MinMax<T>) {
56        self.len += v.len;
57        if self.min.is_none() || (!v.min.is_none() && v.min < self.min) {
58            self.min = v.min;
59        }
60        if self.max.is_none() || (!v.max.is_none() && v.max > self.max) {
61            self.max = v.max;
62        }
63    }
64}
65
66impl<T: PartialOrd> Default for MinMax<T> {
67    fn default() -> MinMax<T> {
68        MinMax {
69            len: 0,
70            min: None,
71            max: None,
72        }
73    }
74}
75
76impl<T: fmt::Debug> fmt::Debug for MinMax<T> {
77    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78        match (&self.min, &self.max) {
79            (&Some(ref min), &Some(ref max)) => {
80                write!(f, "[{:?}, {:?}]", min, max)
81            }
82            (&None, &None) => write!(f, "N/A"),
83            _ => unreachable!(),
84        }
85    }
86}
87
88impl<T: PartialOrd + Clone> FromIterator<T> for MinMax<T> {
89    fn from_iter<I: IntoIterator<Item=T>>(it: I) -> MinMax<T> {
90        let mut v = MinMax::new();
91        v.extend(it);
92        v
93    }
94}
95
96impl<T: PartialOrd + Clone> Extend<T> for MinMax<T> {
97    fn extend<I: IntoIterator<Item=T>>(&mut self, it: I) {
98        for sample in it {
99            self.add(sample);
100        }
101    }
102}
103
104#[cfg(test)]
105mod test {
106    use super::MinMax;
107    use Commute;
108
109    #[test]
110    fn minmax() {
111        let minmax: MinMax<u32> =
112            vec![1u32, 4, 2, 3, 10].into_iter().collect();
113        assert_eq!(minmax.min(), Some(&1u32));
114        assert_eq!(minmax.max(), Some(&10u32));
115    }
116
117    #[test]
118    fn minmax_merge_empty() {
119        let mut mx1: MinMax<u32> = vec![1, 4, 2, 3, 10].into_iter().collect();
120        assert_eq!(mx1.min(), Some(&1u32));
121        assert_eq!(mx1.max(), Some(&10u32));
122
123        mx1.merge(MinMax::default());
124        assert_eq!(mx1.min(), Some(&1u32));
125        assert_eq!(mx1.max(), Some(&10u32));
126    }
127}