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
use crate::Color;
pub fn distance(c1: &Color, c2: &Color, mode: Option<&str>) -> f64 {
let mode = match mode {
Some(mode) => mode,
None => "lab",
};
let c1 = c1.mode(mode);
let c2 = c2.mode(mode);
let mut sum_sq = 0.0;
c1.iter().zip(c2.iter()).for_each(|(a, b)| {
sum_sq += (a - b).powi(2);
});
sum_sq.sqrt()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calc_rgb_distance() {
let c1 = Color::from("rgb(255, 0, 0)");
let c2 = Color::from("rgb(0, 255, 0)");
assert_eq!(distance(&c1, &c2, Some("rgb")), 360.62445840513925);
}
#[test]
fn test_calc_lab_distance() {
let c1 = Color::from("rgb(255, 0, 0)");
let c2 = Color::from("rgb(0, 255, 0)");
assert_eq!(distance(&c1, &c2, None), 170.56524200601007);
assert_eq!(distance(&c1, &c2, Some("lab")), 170.56524200601007);
let c1 = Color::from("#fff");
let c2 = Color::from("#ff0");
assert_eq!(distance(&c1, &c2, Some("rgb")), 255.0);
assert_eq!(distance(&c1, &c2, Some("lab")), 96.94758206572062);
}
}