chroma_rust/utils/parser/
rgb.rs

1use std::str::FromStr;
2
3/// Parse a string as a color in the RGB format.
4pub fn parse_rgb_str(str: &str) -> (u8, u8, u8, f64) {
5    let v_u8: Vec<u8> = str
6        .trim()
7        .replace(" ", "")
8        .replace("rgb(", "")
9        .replace(")", "")
10        .split(",")
11        .map(|s| s.parse::<f64>().unwrap().round() as u8)
12        .collect();
13    (v_u8[0], v_u8[1], v_u8[2], 1.)
14}
15
16/// Parse a string as a color in the RGBA format.
17pub fn parse_rgba_str(str: &str) -> (u8, u8, u8, f64) {
18    let v: Vec<String> = str
19        .trim()
20        .replace(" ", "")
21        .replace("rgba(", "")
22        .replace(")", "")
23        .split(",")
24        .map(|s| s.to_string())
25        .collect();
26    let (r, g, b) = (
27        v[0].parse::<f64>().unwrap().round() as u8,
28        v[1].parse::<f64>().unwrap().round() as u8,
29        v[2].parse::<f64>().unwrap().round() as u8,
30    );
31    let alpha = f64::from_str(v[3].as_str()).unwrap();
32    (r, g, b, alpha)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_parse_rgb_str() {
41        let rgb = parse_rgb_str("rgb(0, 0, 0)");
42        assert_eq!(rgb, (0, 0, 0, 1.));
43
44        let rgb = parse_rgb_str("rgb(255, 255, 255)");
45        assert_eq!(rgb, (255, 255, 255, 1.));
46
47        let rgb = parse_rgb_str("rgb(254, 255, 255, 0.5)");
48        assert_eq!(rgb, (254, 255, 255, 1.));
49    }
50
51    #[test]
52    fn test_parse_rgba_str() {
53        let rgba = parse_rgba_str("rgba(0, 0, 0, 0)");
54        assert_eq!(rgba, (0, 0, 0, 0.));
55
56        let rgba = parse_rgba_str("rgba(255, 255, 255, 1)");
57        assert_eq!(rgba, (255, 255, 255, 1.));
58
59        let rgba = parse_rgba_str("rgba(255, 255, 255, 0.5)");
60        assert_eq!(rgba, (255, 255, 255, 0.5));
61    }
62}