1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use std::str;
use std::error;
use std::fmt;
use std::num;
use std::str::FromStr;
use color::named_colors::NAMED_COLORS;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: f32,
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"Color(r: {}, g: {}, b: {}, a: {})",
self.r,
self.g,
self.b,
self.a)
}
}
#[derive(Debug)]
pub struct ColorParseError;
impl From<num::ParseIntError> for ColorParseError {
#[allow(unused_variables)]
fn from(err: num::ParseIntError) -> ColorParseError {
return ColorParseError;
}
}
impl From<num::ParseFloatError> for ColorParseError {
#[allow(unused_variables)]
fn from(err: num::ParseFloatError) -> ColorParseError {
return ColorParseError;
}
}
impl error::Error for ColorParseError {
fn description(&self) -> &str {
"Failed to parse color"
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
impl fmt::Display for ColorParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ColorParseError: Invalid format")
}
}
impl str::FromStr for Color {
type Err = ColorParseError;
fn from_str(s: &str) -> Result<Self, ColorParseError> {
use std::ascii::AsciiExt;
let s = s.trim();
if s.is_empty() {
return Err(ColorParseError);
}
let mut string = s.replace(' ', "");
string.make_ascii_lowercase();
if let Some(&color) = NAMED_COLORS.get(&*string) {
return Ok(color);
}
if string.starts_with("#") {
let string_char_count = string.chars().count();
if string_char_count == 4 {
let (_, value_string) = string.split_at(1);
let iv = try!(u64::from_str_radix(value_string, 16));
if !(iv <= 0xfff) {
return Err(ColorParseError);
}
return Ok(Color {
r: (((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8)) as u8,
g: ((iv & 0xf0) | ((iv & 0xf0) >> 4)) as u8,
b: ((iv & 0xf) | ((iv & 0xf) << 4)) as u8,
a: 1.0,
});
} else if string_char_count == 7 {
let (_, value_string) = string.split_at(1);
let iv = try!(u64::from_str_radix(value_string, 16));
if !(iv <= 0xffffff) {
return Err(ColorParseError);
}
return Ok(Color {
r: ((iv & 0xff0000) >> 16) as u8,
g: ((iv & 0xff00) >> 8) as u8,
b: (iv & 0xff) as u8,
a: 1.0,
});
}
return Err(ColorParseError);
}
let op = try!(string.find("(").ok_or(ColorParseError));
let ep = try!(string.find(")").ok_or(ColorParseError));
if (ep + 1) != string.len() || ep < op {
return Err(ColorParseError);
}
let (fmt, right_string_half) = string.split_at(op);
if fmt.is_empty() {
return Err(ColorParseError);
}
let mut filtered_right_string_half = right_string_half.to_string();
filtered_right_string_half.remove(0);
filtered_right_string_half.pop();
let params: Vec<&str> = filtered_right_string_half.split(",").collect();
if params.len() < 3 || params.len() > 4 {
return Err(ColorParseError);
}
if fmt == "rgba" {
return parse_rgba(params);
} else if fmt == "rgb" {
return parse_rgb(params);
} else if fmt == "hsla" {
return parse_hsla(params);
} else if fmt == "hsl" {
return parse_hsl(params);
}
return Err(ColorParseError);
}
}
fn parse_rgba(mut rgba: Vec<&str>) -> Result<Color, ColorParseError> {
if rgba.len() != 4 {
return Err(ColorParseError);
}
let a_str = try!(rgba.pop().ok_or(ColorParseError));
let a = try!(parse_css_float(a_str));
let mut rgb_color = try!(parse_rgb(rgba));
rgb_color = Color { a: a, ..rgb_color };
return Ok(rgb_color);
}
fn parse_rgb(mut rgb: Vec<&str>) -> Result<Color, ColorParseError> {
if rgb.len() != 3 {
return Err(ColorParseError);
}
let b_str = try!(rgb.pop().ok_or(ColorParseError));
let g_str = try!(rgb.pop().ok_or(ColorParseError));
let r_str = try!(rgb.pop().ok_or(ColorParseError));
let r = try!(parse_css_int(r_str));
let g = try!(parse_css_int(g_str));
let b = try!(parse_css_int(b_str));
return Ok(Color {
r: r,
g: g,
b: b,
a: 1.0,
});
}
fn parse_hsla(mut hsla: Vec<&str>) -> Result<Color, ColorParseError> {
if hsla.len() != 4 {
return Err(ColorParseError);
}
let a_str = try!(hsla.pop().ok_or(ColorParseError));
let a = try!(parse_css_float(a_str));
let mut rgb_color: Color = try!(parse_hsl(hsla));
rgb_color = Color { a: a, ..rgb_color };
return Ok(rgb_color);
}
fn parse_hsl(mut hsl: Vec<&str>) -> Result<Color, ColorParseError> {
if hsl.len() != 3 {
return Err(ColorParseError);
}
let l_str = try!(hsl.pop().ok_or(ColorParseError));
let s_str = try!(hsl.pop().ok_or(ColorParseError));
let h_str = try!(hsl.pop().ok_or(ColorParseError));
let mut h = try!(f32::from_str(h_str));
h = (((h % 360.0) + 360.0) % 360.0) / 360.0;
let s = try!(parse_css_float(s_str));
let l = try!(parse_css_float(l_str));
let m2: f32;
if l <= 0.5 {
m2 = l * (s + 1.0)
} else {
m2 = l + s - l * s;
}
let m1 = l * 2.0 - m2;
let r = clamp_css_byte_from_float(css_hue_to_rgb(m1, m2, h + 1.0 / 3.0) * 255.0);
let g = clamp_css_byte_from_float(css_hue_to_rgb(m1, m2, h) * 255.0);
let b = clamp_css_byte_from_float(css_hue_to_rgb(m1, m2, h - 1.0 / 3.0) * 255.0);
return Ok(Color {
r: r,
g: g,
b: b,
a: 1.0,
});
}
fn parse_css_float(fv_str: &str) -> Result<f32, num::ParseFloatError> {
let fv: f32;
if fv_str.ends_with("%") {
let mut percentage_string = fv_str.to_string();
percentage_string.pop();
fv = try!(f32::from_str(&percentage_string));
return Ok(clamp_css_float(fv / 100.0));
}
fv = try!(f32::from_str(fv_str));
return Ok(clamp_css_float(fv));
}
fn parse_css_int(iv_or_percentage_str: &str) -> Result<u8, ColorParseError> {
if iv_or_percentage_str.ends_with("%") {
let mut percentage_string = iv_or_percentage_str.to_string();
percentage_string.pop();
let fv = try!(f32::from_str(&percentage_string));
return Ok(clamp_css_byte_from_float(fv / 100.0 * 255.0));
}
let iv = try!(u32::from_str(iv_or_percentage_str));
return Ok(clamp_css_byte(iv));
}
fn clamp_css_float(fv: f32) -> f32 {
if fv < 0.0 {
0.0
} else if fv > 1.0 {
1.0
} else {
fv
}
}
fn clamp_css_byte_from_float(mut fv: f32) -> u8 {
fv = fv.round();
if fv < 0.0 {
0
} else if fv > 255.0 {
255
} else {
fv as u8
}
}
fn clamp_css_byte(iv: u32) -> u8 {
if iv > 255 { 255 } else { iv as u8 }
}
fn css_hue_to_rgb(m1: f32, m2: f32, mut h: f32) -> f32 {
if h < 0.0 {
h += 1.0;
} else if h > 1.0 {
h -= 1.0;
}
if h * 6.0 < 1.0 {
return m1 + (m2 - m1) * h * 6.0;
}
if h * 2.0 < 1.0 {
return m2;
}
if h * 3.0 < 2.0 {
return m1 + (m2 - m1) * (2.0 / 3.0 - h) * 6.0;
}
return m1;
}