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
//! Integration tests exercising the public API of `nearest-color`.

use nearest_color::{nearest_color, parse_color, Matcher, Rgb};

#[test]
fn parses_all_input_forms() {
    assert_eq!(parse_color("#04fbc8").unwrap(), Rgb { r: 4, g: 251, b: 200 });
    assert_eq!(parse_color("0ff").unwrap(), Rgb { r: 0, g: 255, b: 255 });
    assert_eq!(parse_color("rgb(3, 10, 100)").unwrap(), Rgb { r: 3, g: 10, b: 100 });
    assert_eq!(parse_color("rgb(100%, 0%, 0%)").unwrap(), Rgb { r: 255, g: 0, b: 0 });
    assert_eq!(parse_color("orange").unwrap(), Rgb { r: 255, g: 165, b: 0 });
    assert!(parse_color("not-a-color").is_err());
}

#[test]
fn snaps_to_named_palette() {
    let palette = Matcher::from_named(&[
        ("maroon", "#800"),
        ("light yellow", "rgb(255, 255, 51)"),
        ("white", "fff"),
    ])
    .unwrap();
    let m = palette.nearest("#ff0").unwrap().unwrap();
    assert_eq!(m.name.as_deref(), Some("light yellow"));
    assert_eq!(m.rgb, Rgb { r: 255, g: 255, b: 51 });
}

#[test]
fn default_rainbow_matches() {
    assert_eq!(nearest_color("#f11").unwrap().value, "#f00");
    assert_eq!(nearest_color("#abc").unwrap().value, "#808");
    assert_eq!(nearest_color("red").unwrap().value, "#f00");
}

#[test]
fn invalid_needle_errors() {
    let palette = Matcher::from_colors(&["#000", "#fff"]).unwrap();
    assert!(palette.nearest("bogus").is_err());
}

#[test]
fn invalid_palette_color_errors() {
    assert!(Matcher::from_colors(&["#000", "nope"]).is_err());
}