1use image::Rgb;
4
5mod palette_color_provider;
6mod random_color_provider;
7
8pub use palette_color_provider::*;
9pub use random_color_provider::*;
10
11pub trait ColorProvider {
12 fn random_color(&mut self) -> Rgb<u8>;
13}
14
15pub fn color_from_hex(hex: &str) -> Result<Rgb<u8>, String> {
16 let mut hex = hex;
17 if hex.starts_with('#') {
18 hex = &hex[1..hex.len()];
19 }
20 if hex.len() != 6 {
21 return Err(format!("Not a color: '{}'", hex));
22 }
23
24 let r = &hex[0..=1];
25 let g = &hex[2..=3];
26 let b = &hex[4..=5];
27
28 let r = match u8::from_str_radix(r, 16) {
29 Ok(v) => v,
30 Err(e) => return Err(e.to_string()),
31 };
32 let g = match u8::from_str_radix(g, 16) {
33 Ok(v) => v,
34 Err(e) => return Err(e.to_string()),
35 };
36 let b = match u8::from_str_radix(b, 16) {
37 Ok(v) => v,
38 Err(e) => return Err(e.to_string()),
39 };
40
41 Ok(Rgb([r, g, b]))
42}
43
44#[cfg(test)]
45mod test {
46 use super::*;
47
48 #[test]
49 fn color_from_hex() {
50 assert_eq!(
51 Rgb([239, 89, 123]),
52 super::color_from_hex("EF597B").unwrap()
53 );
54 }
55
56 #[test]
57 fn color_from_hex_not_a_color() {
58 let c = super::color_from_hex("foobar");
59 assert!(c.is_err());
60
61 let c = super::color_from_hex("foo");
62 assert!(c.is_err());
63 }
64}