read_color/
lib.rs

1#![deny(missing_docs)]
2
3//! A simple library for reading hex colors.
4
5use std::str::Chars;
6
7/// Converts a character into a u8 value.
8pub fn char_to_hex(ch: char) -> Option<u8> {
9    Some(match ch {
10        '0' => 0,
11        '1' => 1,
12        '2' => 2,
13        '3' => 3,
14        '4' => 4,
15        '5' => 5,
16        '6' => 6,
17        '7' => 7,
18        '8' => 8,
19        '9' => 9,
20        'A' | 'a' => 10,
21        'B' | 'b' => 11,
22        'C' | 'c' => 12,
23        'D' | 'd' => 13,
24        'E' | 'e' => 14,
25        'F' | 'f' => 15,
26        _ => { return None; }
27    })
28}
29
30/// Reads a hex value from an iterator of characters.
31pub fn hex(chars: &mut Chars) -> Option<u8> {
32    match chars.next() {
33        None => { return None; }
34        Some(ch) => char_to_hex(ch)
35    }
36}
37
38/// Reads a pair of hex values, joining them in value range 0-255.
39pub fn hex_pair(chars: &mut Chars) -> Option<u8> {
40    let h1 = match hex(chars) {
41        None => { return None; }
42        Some(h1) => h1
43    };
44    let h2 = match hex(chars) {
45        None => { return None; }
46        Some(h2) => h2
47    };
48    Some((h1 << 4) | h2)
49}
50
51/// Reads RGB colors from iterator of characters.
52pub fn rgb(chars: &mut Chars) -> Option<[u8; 3]> {
53    let red = match hex_pair(chars) {
54        None => { return None; }
55        Some(x) => x
56    };
57    let green = match hex_pair(chars) {
58        None => { return None; }
59        Some(x) => x
60    };
61    let blue = match hex_pair(chars) {
62        None => { return None; }
63        Some(x) => x
64    };
65    Some([red, green, blue])
66}
67
68/// Reads RGBA colors from iterator of characters.
69pub fn rgba(chars: &mut Chars) -> Option<[u8; 4]> {
70    let red = match hex_pair(chars) {
71        None => { return None; }
72        Some(x) => x
73    };
74    let green = match hex_pair(chars) {
75        None => { return None; }
76        Some(x) => x
77    };
78    let blue = match hex_pair(chars) {
79        None => { return None; }
80        Some(x) => x
81    };
82    let alpha = match hex_pair(chars) {
83        None => { return None; }
84        Some(x) => x
85    };
86    Some([red, green, blue, alpha])
87}
88
89/// Reads RGB with optional alpha from iterator of characters.
90pub fn rgb_maybe_a(chars: &mut Chars) -> Option<([u8; 3], Option<u8>)> {
91    let rgb = match rgb(chars) {
92        None => { return None; }
93        Some(x) => x
94    };
95    let a = match hex_pair(chars) {
96        None => { return Some((rgb, None)); }
97        Some(x) => x
98    };
99    Some((rgb, Some(a)))
100}
101