From cf81b09df0532ebf4fee2de0ff1384b63beb9955 Mon Sep 17 00:00:00 2001 From: Tony Crisci Date: Wed, 23 May 2018 22:02:10 -0400 Subject: [PATCH] cache lab calculation for color --- src/color.rs | 6 +++--- src/lib.rs | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/color.rs b/src/color.rs index 26a1ff0..9b7e4db 100644 --- a/src/color.rs +++ b/src/color.rs @@ -82,7 +82,7 @@ pub fn color_from_triplet(name: &'static str, t: (u8, u8, u8)) -> Color { impl Color { /// http://www.easyrgb.com/en/math.php - fn to_lab(&self) -> (f32, f32, f32) { + pub fn to_lab(&self) -> (f32, f32, f32) { let xyz_normalize = |c: f32| { let c_normal = c / 255.0; if c_normal > 0.04045 { @@ -119,9 +119,9 @@ impl Color { (l, a, b) } - pub fn distance(&self, other: &Self) -> f32 { + pub fn distance(&self, lab: (f32, f32, f32)) -> f32 { let (sl, sa, sb) = self.to_lab(); - let (ol, oa, ob) = other.to_lab(); + let (ol, oa, ob) = lab; let dl = sl - ol; let da = sa - oa; diff --git a/src/lib.rs b/src/lib.rs index 68bba84..ad533a7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,12 +66,13 @@ impl ColorNamer { pub fn name_hex_color(&self, hex: &str) -> Result { let color = color::color_from_hex("", &hex)?; + let lab = color.to_lab(); let mut min_distance: f32 = std::f32::MAX; let mut closest_color = color; for c in &self.colors { - let distance = color.distance(c); + let distance = c.distance(lab); if distance < min_distance { min_distance = distance; closest_color = *c;