rgb2hex/
lib.rs

1/// Convert RGB to Hex
2/// Example: `rgb2hex`
3pub fn rgb2hex(r: u8, g: u8, b: u8) -> Result<u32, String> {
4    let colors = [r, g, b];
5    let mut result = String::new();
6
7    for color in colors.iter() {
8        result.push_str(format!("{:02x?}", color).as_str());
9    }
10
11    Ok(match u32::from_str_radix(result.as_str(), 16) {
12        Ok(v) => v,
13        Err(e) => Err(e.to_string())?,
14    })
15}
16
17/// Convert RGB (str) to Hex
18/// Example: `rgb2hex_from_str("251 ,169,12")`
19pub fn rgb2hex_from_str(value: &str) -> Result<u32, String> {
20    let color = value
21        .split(",")
22        .map(|x| x.replace(" ", ""))
23        .collect::<Vec<_>>();
24
25    if color.len() != 3 {
26        Err(format!("Invalid color format: {}", value))
27    } else {
28        let to_color = |v: &str| -> Result<u8, String> {
29            match v.parse::<u8>() {
30                Ok(v) => Ok(v),
31                Err(e) => Err(e.to_string())?,
32            }
33        };
34
35        return rgb2hex(
36            to_color(color[0].as_str())?,
37            to_color(color[1].as_str())?,
38            to_color(color[2].as_str())?,
39        );
40    }
41}
42
43#[cfg(test)]
44mod test {
45    use crate::{rgb2hex, rgb2hex_from_str};
46
47    #[test]
48    fn test() {
49        assert_eq!(rgb2hex(251, 169, 12), Ok(0xfba90c));
50        assert_eq!(rgb2hex_from_str("251, 169, 12"), Ok(0xfba90c));
51        assert_eq!(rgb2hex_from_str("251 ,169,12 "), Ok(0xfba90c));
52    }
53}