1use crate::error::{Error, Result};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub struct Color(pub [u8; 4]);
31
32impl Color {
33 pub const TRANSPARENT: Color = Color([0, 0, 0, 0]);
35 pub const WHITE: Color = Color([255, 255, 255, 255]);
37 pub const BLACK: Color = Color([0, 0, 0, 255]);
39
40 pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
42 Color([r, g, b, a])
43 }
44
45 pub const fn has_alpha(self) -> bool {
47 self.0[3] != 255
48 }
49
50 pub fn parse(text: &str) -> Result<Self> {
53 Self::try_parse(text).ok_or_else(|| Error::InvalidArgument(format!("Invalid color: {text}")))
54 }
55
56 fn try_parse(text: &str) -> Option<Self> {
57 let text = text.trim();
58 if text.is_empty() {
59 return Some(Color::WHITE);
60 }
61 if let Some(hex) = text.strip_prefix('#') {
62 return parse_hex(hex);
63 }
64 let lower = text.to_ascii_lowercase();
65 if let Some(args) = lower.strip_prefix("rgba(").and_then(|s| s.strip_suffix(')')) {
66 return parse_functional(args, true);
67 }
68 if let Some(args) = lower.strip_prefix("rgb(").and_then(|s| s.strip_suffix(')')) {
69 return parse_functional(args, false);
70 }
71 if lower == "none" || lower == "transparent" {
72 return Some(Color::TRANSPARENT);
73 }
74 NAMES.binary_search_by(|(name, _)| name.cmp(&lower.as_str())).ok().map(|i| {
75 let v = NAMES[i].1;
76 Color([(v >> 16) as u8, (v >> 8) as u8, v as u8, 255])
77 })
78 }
79}
80
81fn parse_hex(hex: &str) -> Option<Color> {
82 if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
83 return None;
84 }
85 let nibble = |i: usize| u8::from_str_radix(&hex[i..=i], 16).ok();
86 let byte = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
87 let word = |i: usize| u16::from_str_radix(&hex[i..i + 4], 16).ok().map(|v| (v >> 8) as u8);
88 match hex.len() {
89 3 => Some(Color([nibble(0)? * 17, nibble(1)? * 17, nibble(2)? * 17, 255])),
90 4 => Some(Color([nibble(0)? * 17, nibble(1)? * 17, nibble(2)? * 17, nibble(3)? * 17])),
91 6 => Some(Color([byte(0)?, byte(2)?, byte(4)?, 255])),
92 8 => Some(Color([byte(0)?, byte(2)?, byte(4)?, byte(6)?])),
93 12 => Some(Color([word(0)?, word(4)?, word(8)?, 255])),
94 16 => Some(Color([word(0)?, word(4)?, word(8)?, word(12)?])),
95 _ => None,
96 }
97}
98
99fn parse_functional(args: &str, alpha: bool) -> Option<Color> {
100 let parts: Vec<&str> = args.split(',').map(str::trim).collect();
101 if parts.len() != if alpha { 4 } else { 3 } {
102 return None;
103 }
104 let channel = |s: &str| -> Option<u8> {
105 let value = if let Some(p) = s.strip_suffix('%') {
106 p.parse::<f64>().ok()? * 255.0 / 100.0
107 } else {
108 s.parse::<f64>().ok()?
109 };
110 value.is_finite().then(|| value.clamp(0.0, 255.0).round() as u8)
111 };
112 let a = if alpha {
113 let s = parts[3];
114 let value = if let Some(p) = s.strip_suffix('%') { p.parse::<f64>().ok()? / 100.0 } else { s.parse().ok()? };
115 if !value.is_finite() {
116 return None;
117 }
118 (value.clamp(0.0, 1.0) * 255.0).round() as u8
119 } else {
120 255
121 };
122 Some(Color([channel(parts[0])?, channel(parts[1])?, channel(parts[2])?, a]))
123}
124
125const NAMES: &[(&str, u32)] = &[
127 ("aliceblue", 0xF0F8FF),
128 ("antiquewhite", 0xFAEBD7),
129 ("aqua", 0x00FFFF),
130 ("aquamarine", 0x7FFFD4),
131 ("azure", 0xF0FFFF),
132 ("beige", 0xF5F5DC),
133 ("bisque", 0xFFE4C4),
134 ("black", 0x000000),
135 ("blanchedalmond", 0xFFEBCD),
136 ("blue", 0x0000FF),
137 ("blueviolet", 0x8A2BE2),
138 ("brown", 0xA52A2A),
139 ("burlywood", 0xDEB887),
140 ("cadetblue", 0x5F9EA0),
141 ("chartreuse", 0x7FFF00),
142 ("chocolate", 0xD2691E),
143 ("coral", 0xFF7F50),
144 ("cornflowerblue", 0x6495ED),
145 ("cornsilk", 0xFFF8DC),
146 ("crimson", 0xDC143C),
147 ("cyan", 0x00FFFF),
148 ("darkblue", 0x00008B),
149 ("darkcyan", 0x008B8B),
150 ("darkgoldenrod", 0xB8860B),
151 ("darkgray", 0xA9A9A9),
152 ("darkgreen", 0x006400),
153 ("darkgrey", 0xA9A9A9),
154 ("darkkhaki", 0xBDB76B),
155 ("darkmagenta", 0x8B008B),
156 ("darkolivegreen", 0x556B2F),
157 ("darkorange", 0xFF8C00),
158 ("darkorchid", 0x9932CC),
159 ("darkred", 0x8B0000),
160 ("darksalmon", 0xE9967A),
161 ("darkseagreen", 0x8FBC8F),
162 ("darkslateblue", 0x483D8B),
163 ("darkslategray", 0x2F4F4F),
164 ("darkslategrey", 0x2F4F4F),
165 ("darkturquoise", 0x00CED1),
166 ("darkviolet", 0x9400D3),
167 ("deeppink", 0xFF1493),
168 ("deepskyblue", 0x00BFFF),
169 ("dimgray", 0x696969),
170 ("dimgrey", 0x696969),
171 ("dodgerblue", 0x1E90FF),
172 ("firebrick", 0xB22222),
173 ("floralwhite", 0xFFFAF0),
174 ("forestgreen", 0x228B22),
175 ("fuchsia", 0xFF00FF),
176 ("gainsboro", 0xDCDCDC),
177 ("ghostwhite", 0xF8F8FF),
178 ("gold", 0xFFD700),
179 ("goldenrod", 0xDAA520),
180 ("gray", 0x808080),
181 ("green", 0x008000),
182 ("greenyellow", 0xADFF2F),
183 ("grey", 0x808080),
184 ("honeydew", 0xF0FFF0),
185 ("hotpink", 0xFF69B4),
186 ("indianred", 0xCD5C5C),
187 ("indigo", 0x4B0082),
188 ("ivory", 0xFFFFF0),
189 ("khaki", 0xF0E68C),
190 ("lavender", 0xE6E6FA),
191 ("lavenderblush", 0xFFF0F5),
192 ("lawngreen", 0x7CFC00),
193 ("lemonchiffon", 0xFFFACD),
194 ("lightblue", 0xADD8E6),
195 ("lightcoral", 0xF08080),
196 ("lightcyan", 0xE0FFFF),
197 ("lightgoldenrodyellow", 0xFAFAD2),
198 ("lightgray", 0xD3D3D3),
199 ("lightgreen", 0x90EE90),
200 ("lightgrey", 0xD3D3D3),
201 ("lightpink", 0xFFB6C1),
202 ("lightsalmon", 0xFFA07A),
203 ("lightseagreen", 0x20B2AA),
204 ("lightskyblue", 0x87CEFA),
205 ("lightslategray", 0x778899),
206 ("lightslategrey", 0x778899),
207 ("lightsteelblue", 0xB0C4DE),
208 ("lightyellow", 0xFFFFE0),
209 ("lime", 0x00FF00),
210 ("limegreen", 0x32CD32),
211 ("linen", 0xFAF0E6),
212 ("magenta", 0xFF00FF),
213 ("maroon", 0x800000),
214 ("mediumaquamarine", 0x66CDAA),
215 ("mediumblue", 0x0000CD),
216 ("mediumorchid", 0xBA55D3),
217 ("mediumpurple", 0x9370DB),
218 ("mediumseagreen", 0x3CB371),
219 ("mediumslateblue", 0x7B68EE),
220 ("mediumspringgreen", 0x00FA9A),
221 ("mediumturquoise", 0x48D1CC),
222 ("mediumvioletred", 0xC71585),
223 ("midnightblue", 0x191970),
224 ("mintcream", 0xF5FFFA),
225 ("mistyrose", 0xFFE4E1),
226 ("moccasin", 0xFFE4B5),
227 ("navajowhite", 0xFFDEAD),
228 ("navy", 0x000080),
229 ("oldlace", 0xFDF5E6),
230 ("olive", 0x808000),
231 ("olivedrab", 0x6B8E23),
232 ("orange", 0xFFA500),
233 ("orangered", 0xFF4500),
234 ("orchid", 0xDA70D6),
235 ("palegoldenrod", 0xEEE8AA),
236 ("palegreen", 0x98FB98),
237 ("paleturquoise", 0xAFEEEE),
238 ("palevioletred", 0xDB7093),
239 ("papayawhip", 0xFFEFD5),
240 ("peachpuff", 0xFFDAB9),
241 ("peru", 0xCD853F),
242 ("pink", 0xFFC0CB),
243 ("plum", 0xDDA0DD),
244 ("powderblue", 0xB0E0E6),
245 ("purple", 0x800080),
246 ("red", 0xFF0000),
247 ("rosybrown", 0xBC8F8F),
248 ("royalblue", 0x4169E1),
249 ("saddlebrown", 0x8B4513),
250 ("salmon", 0xFA8072),
251 ("sandybrown", 0xF4A460),
252 ("seagreen", 0x2E8B57),
253 ("seashell", 0xFFF5EE),
254 ("sienna", 0xA0522D),
255 ("silver", 0xC0C0C0),
256 ("skyblue", 0x87CEEB),
257 ("slateblue", 0x6A5ACD),
258 ("slategray", 0x708090),
259 ("slategrey", 0x708090),
260 ("snow", 0xFFFAFA),
261 ("springgreen", 0x00FF7F),
262 ("steelblue", 0x4682B4),
263 ("tan", 0xD2B48C),
264 ("teal", 0x008080),
265 ("thistle", 0xD8BFD8),
266 ("tomato", 0xFF6347),
267 ("turquoise", 0x40E0D0),
268 ("violet", 0xEE82EE),
269 ("wheat", 0xF5DEB3),
270 ("white", 0xFFFFFF),
271 ("whitesmoke", 0xF5F5F5),
272 ("yellow", 0xFFFF00),
273 ("yellowgreen", 0x9ACD32),
274];
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279
280 #[test]
281 fn names_are_sorted() {
282 assert!(NAMES.windows(2).all(|w| w[0].0 < w[1].0));
283 }
284
285 #[test]
286 fn parses_the_forms_imagemagick_accepts() {
287 assert_eq!(Color::parse("").unwrap(), Color::WHITE);
288 assert_eq!(Color::parse("#f00").unwrap(), Color::rgba(255, 0, 0, 255));
289 assert_eq!(Color::parse("#0000ff80").unwrap(), Color::rgba(0, 0, 255, 128));
290 assert_eq!(Color::parse("rgba(0,0,255,0.5)").unwrap(), Color::rgba(0, 0, 255, 128));
291 assert_eq!(Color::parse("Transparent").unwrap(), Color::TRANSPARENT);
292 assert_eq!(Color::parse("bad").unwrap_err().to_string(), "Invalid color: bad");
293 }
294}