chroma_rust/utils/
valid.rs

1/// Checking if a color can be parsed by chroma-rust
2///
3/// you can use `chroma_rust::valid` to try if a color argument can be correctly parsed as color by `chroma_rust`.
4///
5/// ```rust
6/// chroma_rust::valid("red");
7/// chroma_rust::valid("bread");
8/// chroma_rust::valid("#F0000D");
9/// chroma_rust::valid("#FOOOOD");
10/// ```
11pub fn valid(str: &str) -> bool {
12    let valid = match str {
13        str if str.starts_with("#") => {
14            if str.len() == 4 || str.len() == 7 {
15                str.chars().skip(1).all(|c| c.is_ascii_hexdigit())
16            } else {
17                false
18            }
19        }
20        // TODO: check if rgb/rgba/hsl/hsla/hsv/hsva are valid
21        str if str.starts_with("rgba") => true,
22        str if str.starts_with("rgb") => true,
23        str if str.starts_with("lab") => true,
24        str if str.starts_with("hsl") => true,
25        str if str.starts_with("hsv") => true,
26        str if str.starts_with("cmyk") => true,
27        _ => match crate::W3CX11.get(str) {
28            Some(_) => true,
29            None => false,
30        },
31    };
32    valid
33}
34
35#[cfg(test)]
36mod tests {
37
38    use super::*;
39
40    #[test]
41    fn test_valid_hex() {
42        assert!(valid("#abcdef"));
43    }
44
45    #[test]
46    fn test_valid_hex_short() {
47        assert!(valid("#abc"));
48    }
49
50    #[test]
51    fn test_valid_hex_invalid() {
52        assert!(!valid("#FOOOOD"));
53    }
54
55    #[test]
56    fn test_valid_hex_invalid_length() {
57        assert!(!valid("#abcde"));
58    }
59
60    #[test]
61    fn test_valid_rgb() {
62        assert!(valid("rgb(255, 255, 255)"));
63    }
64
65    #[test]
66    fn test_valid_rgba() {
67        assert!(valid("rgba(255, 255, 255, 0.6)"));
68    }
69
70    #[test]
71    fn test_valid_lab() {
72        assert!(valid("lab(100, 0, 0)"));
73    }
74
75    #[test]
76    fn test_valid_name() {
77        assert!(valid("mediumspringgreen"));
78    }
79
80    #[test]
81    fn test_invalid() {
82        assert!(!valid("invalid"));
83    }
84}