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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use std::collections::HashMap;
use std::iter::{FromIterator, IntoIterator};
use super::*;
pub struct Histogram {
data: HashMap<Color, usize>,
}
#[derive(Clone)]
pub struct ColorCount {
pub color: Colorf,
pub count: usize,
}
impl Histogram {
pub fn new() -> Histogram {
Histogram { data: HashMap::new() }
}
pub fn to_color_counts(&self, colorspace: &ColorSpace) -> Vec<ColorCount> {
self.data
.iter()
.map(|(color, count)| {
ColorCount {
color: colorspace.to_float(*color),
count: *count,
}
})
.collect()
}
pub fn iter<'a>(&'a self) -> Box<Iterator<Item = (&Color, &usize)> + 'a> {
Box::new(self.data.iter())
}
}
impl Extend<Color> for Histogram {
fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = Color>
{
for pixel in iter {
let count = self.data.entry(pixel).or_insert(0);
*count += 1;
}
}
}
impl FromIterator<Color> for Histogram {
fn from_iter<T>(iter: T) -> Self
where T: IntoIterator<Item = Color>
{
let mut histogram = Histogram::new();
histogram.extend(iter.into_iter());
histogram
}
}
#[cfg(test)]
mod tests {
use super::super::*;
#[test]
fn count_duplicates() {
let mut hist: Histogram =
[Color::new(10, 20, 30, 99), Color::new(0, 99, 0, 99)].iter().cloned().collect();
hist.extend([Color::new(20, 0, 40, 99), Color::new(0, 99, 0, 99)].iter().cloned());
assert_eq!(*hist.data.get(&Color::new(0, 99, 0, 99)).unwrap(), 2usize);
}
}