nearest-color 0.1.0

Find the nearest color from a palette by RGB distance, for hex / rgb() / named CSS colors. A faithful port of the nearest-color npm package. Zero dependencies.
Documentation
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! # nearest-color — find the nearest color from a palette
//!
//! Given a target color and a list of available colors, find the closest one by Euclidean
//! distance in RGB space — useful for snapping arbitrary colors to a theme palette, naming
//! colors, or quantizing. Colors may be given as hex (`#f00`, `#ff0000`), `rgb(…)` strings,
//! or the 17 standard CSS color names.
//!
//! A faithful Rust port of the [`nearest-color`](https://www.npmjs.com/package/nearest-color)
//! npm package. **Zero dependencies.**
//!
//! ```
//! use nearest_color::Matcher;
//!
//! let palette = Matcher::from_named(&[
//!     ("maroon", "#800"),
//!     ("pale blue", "#def"),
//!     ("white", "fff"),
//! ]).unwrap();
//!
//! let m = palette.nearest("#f00").unwrap().unwrap();
//! assert_eq!(m.name.as_deref(), Some("maroon"));
//! assert_eq!(m.value, "#800");
//! assert_eq!(m.rgb, nearest_color::Rgb { r: 136, g: 0, b: 0 });
//! ```
//!
//! With an unnamed palette (or the built-in rainbow defaults), the match's `name` is
//! `None` and `value` holds the nearest color's source string:
//!
//! ```
//! use nearest_color::nearest_color;
//! assert_eq!(nearest_color("#f88").unwrap().value, "#f80");
//! ```

#![forbid(unsafe_code)]
#![doc(html_root_url = "https://docs.rs/nearest-color/0.1.0")]
#![allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::must_use_candidate
)]

use std::fmt;

// Compile-test the README's examples as part of `cargo test`.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

/// An RGB color. Components are stored as `i32` to faithfully carry through out-of-range
/// `rgb()` inputs (the reference does not clamp).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rgb {
    /// Red component (0–255 for valid input).
    pub r: i32,
    /// Green component.
    pub g: i32,
    /// Blue component.
    pub b: i32,
}

/// The result of a nearest-color match.
#[derive(Debug, Clone, PartialEq)]
pub struct ColorMatch {
    /// The matched color's name, if the palette was named.
    pub name: Option<String>,
    /// The matched color's source string (e.g. `#800`).
    pub value: String,
    /// The matched color's RGB value.
    pub rgb: Rgb,
    /// The Euclidean RGB distance from the needle to the match.
    pub distance: f64,
}

/// The error returned for an unparseable color string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidColor(pub String);

impl fmt::Display for InvalidColor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{}\" is not a valid color", self.0)
    }
}

impl std::error::Error for InvalidColor {}

/// The 17 standard CSS color names recognized by [`parse_color`].
pub const STANDARD_COLORS: &[(&str, &str)] = &[
    ("aqua", "#0ff"),
    ("black", "#000"),
    ("blue", "#00f"),
    ("fuchsia", "#f0f"),
    ("gray", "#808080"),
    ("green", "#008000"),
    ("lime", "#0f0"),
    ("maroon", "#800000"),
    ("navy", "#000080"),
    ("olive", "#808000"),
    ("orange", "#ffa500"),
    ("purple", "#800080"),
    ("red", "#f00"),
    ("silver", "#c0c0c0"),
    ("teal", "#008080"),
    ("white", "#fff"),
    ("yellow", "#ff0"),
];

/// The default rainbow palette (ROY G BIV) used by [`nearest_color`].
const DEFAULT_COLORS: &[&str] = &["#f00", "#f80", "#ff0", "#0f0", "#00f", "#008", "#808"];

/// Parse a color string into [`Rgb`].
///
/// Accepts a standard CSS color name, a 3- or 6-digit hex string (with or without a leading
/// `#`), or an `rgb(r, g, b)` string whose components may be `0–255` integers or
/// percentages.
///
/// # Errors
/// Returns [`InvalidColor`] if `source` is not a recognizable color.
///
/// ```
/// # use nearest_color::{parse_color, Rgb};
/// assert_eq!(parse_color("#f00").unwrap(), Rgb { r: 255, g: 0, b: 0 });
/// assert_eq!(parse_color("rgb(50%, 0%, 50%)").unwrap(), Rgb { r: 128, g: 0, b: 128 });
/// assert_eq!(parse_color("aqua").unwrap(), Rgb { r: 0, g: 255, b: 255 });
/// assert!(parse_color("foo").is_err());
/// ```
pub fn parse_color(source: &str) -> Result<Rgb, InvalidColor> {
    if let Some((_, hex)) = STANDARD_COLORS.iter().find(|(name, _)| *name == source) {
        return parse_color(hex);
    }
    if let Some(rgb) = parse_hex(source) {
        return Ok(rgb);
    }
    if let Some(rgb) = parse_rgb(source) {
        return Ok(rgb);
    }
    Err(InvalidColor(source.to_string()))
}

/// `/^#?((?:[0-9a-f]{3}){1,2})$/i`
fn parse_hex(source: &str) -> Option<Rgb> {
    let hex = source.strip_prefix('#').unwrap_or(source);
    if !(hex.len() == 3 || hex.len() == 6) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let pair = |a: u8, b: u8| -> i32 { i32::from(hex_val(a)) * 16 + i32::from(hex_val(b)) };
    let bytes = hex.as_bytes();
    let rgb = if hex.len() == 3 {
        Rgb {
            r: pair(bytes[0], bytes[0]),
            g: pair(bytes[1], bytes[1]),
            b: pair(bytes[2], bytes[2]),
        }
    } else {
        Rgb {
            r: pair(bytes[0], bytes[1]),
            g: pair(bytes[2], bytes[3]),
            b: pair(bytes[4], bytes[5]),
        }
    };
    Some(rgb)
}

fn hex_val(b: u8) -> u8 {
    match b {
        b'0'..=b'9' => b - b'0',
        b'a'..=b'f' => b - b'a' + 10,
        b'A'..=b'F' => b - b'A' + 10,
        _ => 0,
    }
}

/// `/^rgb\(\s*(\d{1,3}%?),\s*(\d{1,3}%?),\s*(\d{1,3}%?)\s*\)$/i`
fn parse_rgb(source: &str) -> Option<Rgb> {
    const WS: [char; 6] = [' ', '\t', '\n', '\r', '\u{0c}', '\u{0b}'];
    // Case-insensitive `rgb(` prefix and `)` suffix.
    let lower = source.to_ascii_lowercase();
    let inner = lower.strip_prefix("rgb(")?.strip_suffix(')')?;
    let segs: Vec<&str> = inner.split(',').collect();
    if segs.len() != 3 {
        return None;
    }
    // Each comma is followed by `\s*`; the first component allows leading `\s*` and the
    // last allows trailing `\s*`. A component itself contains no whitespace, so
    // `parse_component` rejects any that leaks through.
    let r = parse_component(segs[0].trim_start_matches(WS))?;
    let g = parse_component(segs[1].trim_start_matches(WS))?;
    let b = parse_component(segs[2].trim_start_matches(WS).trim_end_matches(WS))?;
    Some(Rgb { r, g, b })
}

/// A component is `\d{1,3}` optionally followed by `%`.
fn parse_component(s: &str) -> Option<i32> {
    let (digits, percent) = match s.strip_suffix('%') {
        Some(d) => (d, true),
        None => (s, false),
    };
    if digits.is_empty() || digits.len() > 3 || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let n: i32 = digits.parse().ok()?;
    if percent {
        // Math.round(n * 255 / 100), round half up.
        Some(((f64::from(n) * 255.0 / 100.0) + 0.5).floor() as i32)
    } else {
        Some(n)
    }
}

#[derive(Debug, Clone)]
struct Spec {
    name: Option<String>,
    source: String,
    rgb: Rgb,
}

/// A reusable nearest-color matcher built from a fixed palette.
#[derive(Debug, Clone)]
pub struct Matcher {
    colors: Vec<Spec>,
}

impl Matcher {
    /// Build a matcher from a list of unnamed color strings.
    ///
    /// # Errors
    /// Returns [`InvalidColor`] if any entry is not a valid color.
    pub fn from_colors(colors: &[&str]) -> Result<Self, InvalidColor> {
        let colors = colors
            .iter()
            .map(|&c| {
                Ok(Spec {
                    name: None,
                    source: c.to_string(),
                    rgb: parse_color(c)?,
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self { colors })
    }

    /// Build a matcher from `(name, color)` pairs.
    ///
    /// # Errors
    /// Returns [`InvalidColor`] if any color is not valid.
    pub fn from_named(colors: &[(&str, &str)]) -> Result<Self, InvalidColor> {
        let colors = colors
            .iter()
            .map(|&(name, c)| {
                Ok(Spec {
                    name: Some(name.to_string()),
                    source: c.to_string(),
                    rgb: parse_color(c)?,
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self { colors })
    }

    /// Combine this palette with another, returning a matcher over both.
    #[must_use]
    pub fn or(mut self, mut other: Matcher) -> Matcher {
        self.colors.append(&mut other.colors);
        self
    }

    /// Find the nearest palette color to `needle`.
    ///
    /// # Errors
    /// Returns [`InvalidColor`] if `needle` is not a valid color. Returns `Ok(None)` only if
    /// the palette is empty.
    pub fn nearest(&self, needle: &str) -> Result<Option<ColorMatch>, InvalidColor> {
        let needle = parse_color(needle)?;
        let mut best: Option<(&Spec, i64)> = None;
        for spec in &self.colors {
            let dr = i64::from(needle.r - spec.rgb.r);
            let dg = i64::from(needle.g - spec.rgb.g);
            let db = i64::from(needle.b - spec.rgb.b);
            let dist_sq = dr * dr + dg * dg + db * db;
            if best.map_or(true, |(_, bd)| dist_sq < bd) {
                best = Some((spec, dist_sq));
            }
        }
        Ok(best.map(|(spec, dist_sq)| ColorMatch {
            name: spec.name.clone(),
            value: spec.source.clone(),
            rgb: spec.rgb,
            #[allow(clippy::cast_precision_loss)]
            distance: (dist_sq as f64).sqrt(),
        }))
    }
}

/// A matcher over the built-in default palette (the rainbow colors, unnamed).
///
/// # Panics
/// Never; the built-in default colors are always valid.
#[must_use]
pub fn default_matcher() -> Matcher {
    Matcher::from_colors(DEFAULT_COLORS).expect("default colors are valid")
}

/// Find the nearest of the built-in default (rainbow) colors to `needle`.
///
/// # Errors
/// Returns [`InvalidColor`] if `needle` is not a valid color.
///
/// # Panics
/// Never; the built-in default palette is non-empty.
///
/// ```
/// # use nearest_color::nearest_color;
/// assert_eq!(nearest_color("#0e0").unwrap().value, "#0f0");
/// ```
pub fn nearest_color(needle: &str) -> Result<ColorMatch, InvalidColor> {
    Ok(default_matcher()
        .nearest(needle)?
        .expect("default palette is non-empty"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_hex_forms() {
        assert_eq!(parse_color("#f00").unwrap(), Rgb { r: 255, g: 0, b: 0 });
        assert_eq!(parse_color("f00").unwrap(), Rgb { r: 255, g: 0, b: 0 });
        assert_eq!(
            parse_color("#04fbc8").unwrap(),
            Rgb {
                r: 4,
                g: 251,
                b: 200
            }
        );
        assert_eq!(
            parse_color("#FF0").unwrap(),
            Rgb {
                r: 255,
                g: 255,
                b: 0
            }
        );
        assert_eq!(
            parse_color("abc").unwrap(),
            Rgb {
                r: 170,
                g: 187,
                b: 204
            }
        );
    }

    #[test]
    fn parses_rgb_and_names() {
        assert_eq!(
            parse_color("rgb(3, 10, 100)").unwrap(),
            Rgb {
                r: 3,
                g: 10,
                b: 100
            }
        );
        assert_eq!(
            parse_color("rgb(50%, 0%, 50%)").unwrap(),
            Rgb {
                r: 128,
                g: 0,
                b: 128
            }
        );
        assert_eq!(
            parse_color("aqua").unwrap(),
            Rgb {
                r: 0,
                g: 255,
                b: 255
            }
        );
        assert_eq!(
            parse_color("gray").unwrap(),
            Rgb {
                r: 128,
                g: 128,
                b: 128
            }
        );
    }

    #[test]
    fn rejects_invalid() {
        for bad in ["foo", "#ff", "#fffff", "rgb(1,2)", "Red", "", "#12g"] {
            assert!(parse_color(bad).is_err(), "{bad:?} should be invalid");
        }
    }

    #[test]
    fn default_nearest() {
        assert_eq!(nearest_color("#f11").unwrap().value, "#f00");
        assert_eq!(nearest_color("#f88").unwrap().value, "#f80");
        assert_eq!(nearest_color("#ffe").unwrap().value, "#ff0");
        assert_eq!(nearest_color("#efe").unwrap().value, "#ff0");
        assert_eq!(nearest_color("#abc").unwrap().value, "#808");
        assert_eq!(nearest_color("red").unwrap().value, "#f00");
    }

    #[test]
    fn named_match_has_metadata() {
        let m = Matcher::from_named(&[("maroon", "#800"), ("white", "fff")]).unwrap();
        let got = m.nearest("#f00").unwrap().unwrap();
        assert_eq!(got.name.as_deref(), Some("maroon"));
        assert_eq!(got.value, "#800");
        assert_eq!(got.rgb, Rgb { r: 136, g: 0, b: 0 });
        assert!((got.distance - 119.0).abs() < 0.5);
    }

    #[test]
    fn combine_with_or() {
        let a = Matcher::from_colors(&["#eee"]).unwrap();
        let b = Matcher::from_colors(&["#444"]).unwrap();
        let both = a.or(b);
        assert_eq!(both.nearest("#000").unwrap().unwrap().value, "#444");
        assert_eq!(both.nearest("#fff").unwrap().unwrap().value, "#eee");
    }

    #[test]
    fn ties_keep_first() {
        // "#111" is exactly equidistant from "#000" and "#222"; the earlier entry wins.
        let m = Matcher::from_colors(&["#000", "#222"]).unwrap();
        assert_eq!(m.nearest("#111").unwrap().unwrap().value, "#000");
    }
}