Debian Codegraph @

src/parser.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use crate::utils::parse_values;
2 use crate::utils::remap;
3 use crate::utils::ParamParser;
4 use crate::{Color, ParseColorError};
5
6 #[cfg(feature = "named-colors")]
7 use crate::NAMED_COLORS;
8
9 /// Parse CSS color string
10 ///
11 /// # Examples
12 ///
13 /// ```
14 /// # use core::error::Error;
15 /// # fn main() -> Result<(), Box<dyn Error>> {
16 /// let c = csscolorparser::parse("#ff0")?;
17 ///
18 /// assert_eq!(c.to_array(), [1.0, 1.0, 0.0, 1.0]);
19 /// assert_eq!(c.to_rgba8(), [255, 255, 0, 255]);
20 /// assert_eq!(c.to_css_hex(), "#ffff00");
21 /// assert_eq!(c.to_css_rgb(), "rgb(255 255 0)");
22 /// # Ok(())
23 /// # }
24 /// ```
25 ///
26 /// ```
27 /// # use core::error::Error;
28 /// # fn main() -> Result<(), Box<dyn Error>> {
29 /// let c = csscolorparser::parse("hsl(360deg,100%,50%)")?;
30 ///
31 /// assert_eq!(c.to_array(), [1.0, 0.0, 0.0, 1.0]);
32 /// assert_eq!(c.to_rgba8(), [255, 0, 0, 255]);
33 /// assert_eq!(c.to_css_hex(), "#ff0000");
34 /// assert_eq!(c.to_css_rgb(), "rgb(255 0 0)");
35 /// # Ok(())
36 /// # }
37 /// ```
38 #[inline(never)]
39 pub fn parse(s: &str) -> Result<Color, ParseColorError> {
40 let s = s.trim();
41
42 let err = match parse_abs(s) {
43 Ok(c) => return Ok(c),
44 Err(e @ ParseColorError::InvalidHex) => return Err(e),
45 Err(e @ ParseColorError::InvalidFunction) => return Err(e),
46 Err(e @ ParseColorError::InvalidUnknown) => return Err(e),
47 Err(e) => e,
48 };
49
50 if let (Some(idx), Some(s)) = (s.find('('), s.strip_suffix(')')) {
51 if !s.is_ascii() {
52 return Err(err);
53 }
54
55 let mut pp = ParamParser::new(&s[idx + 1..]);
56 pp.space();
57
58 #[rustfmt::skip]
59 let (
60 Some(from), true,
61 Some(color), true,
62 Some(val1), true,
63 Some(val2), true,
64 Some(val3),
65 ) = (
66 pp.value(), pp.space(),
67 pp.value(), pp.space(),
68 pp.value(), pp.space(),
69 pp.value(), pp.space(),
70 pp.value(),
71 ) else {
72 return Err(err);
73 };
74
75 if !from.eq_ignore_ascii_case("from") {
76 return Err(err);
77 }
78
79 let Ok(color) = parse(color) else {
80 return Err(err);
81 };
82
83 pp.space();
84
85 let val4 = if pp.is_end() {
86 "alpha"
87 } else if let (true, Some(alpha), _, true) =
88 (pp.slash(), pp.value(), pp.space(), pp.is_end())
89 {
90 alpha
91 } else {
92 return Err(err);
93 };
94
95 let values = [val1, val2, val3, val4];
96
97 match err {
98 ParseColorError::InvalidRgb => {
99 // r, g, b [0..255]
100 // alpha [0..1]
101 let variables = [
102 ("r", color.r * 255.0),
103 ("g", color.g * 255.0),
104 ("b", color.b * 255.0),
105 ("alpha", color.a),
106 ];
107 if let Some([r, g, b, a]) = parse_values(values, variables) {
108 return Ok(Color::new(r / 255.0, g / 255.0, b / 255.0, a));
109 };
110 }
111 ParseColorError::InvalidHwb => {
112 // h [0..360]
113 // w, b [0..100]
114 // alpha [0..1]
115 let [h, w, b, a] = color.to_hwba();
116 let variables = [("h", h), ("w", w * 100.0), ("b", b * 100.0), ("alpha", a)];
117 if let Some([h, w, b, a]) = parse_values(values, variables) {
118 return Ok(Color::from_hwba(h, w / 100.0, b / 100.0, a));
119 };
120 }
121 ParseColorError::InvalidHsl => {
122 // h [0..360]
123 // s, l [0..100]
124 // alpha [0..1]
125 let [h, s, l, a] = color.to_hsla();
126 let variables = [("h", h), ("s", s * 100.0), ("l", l * 100.0), ("alpha", a)];
127 if let Some([h, s, l, a]) = parse_values(values, variables) {
128 return Ok(Color::from_hsla(
129 h,
130 (s / 100.0).clamp(0.0, 1.0),
131 (l / 100.0).clamp(0.0, 1.0),
132 a,
133 ));
134 };
135 }
136 ParseColorError::InvalidHsv => {
137 // h [0..360]
138 // s, v [0..100]
139 // alpha [0..1]
140 let [h, s, v, a] = color.to_hsva();
141 let variables = [("h", h), ("s", s * 100.0), ("v", v * 100.0), ("alpha", a)];
142 if let Some([h, s, v, a]) = parse_values(values, variables) {
143 return Ok(Color::from_hsva(h, s / 100.0, v / 100.0, a));
144 };
145 }
146 ParseColorError::InvalidLab => {
147 // l [0..100]
148 // a, b [-125..125]
149 // alpha [0..1]
150 let [l, a, b, alpha] = color.to_laba();
151 let variables = [("l", l), ("a", a), ("b", b), ("alpha", alpha)];
152 if let Some([l, a, b, alpha]) = parse_values(values, variables) {
153 return Ok(Color::from_laba(l.max(0.0), a, b, alpha));
154 };
155 }
156 ParseColorError::InvalidLch => {
157 // l [0..100]
158 // c [0..150]
159 // h [0..360]
160 // alpha [0..1]
161 let [l, c, h, a] = color.to_lcha();
162 let variables = [("l", l), ("c", c), ("h", h.to_degrees()), ("alpha", a)];
163 if let Some([l, c, h, a]) = parse_values(values, variables) {
164 return Ok(Color::from_lcha(l.max(0.0), c.max(0.0), h.to_radians(), a));
165 };
166 }
167 ParseColorError::InvalidOklab => {
168 // l [0..1]
169 // a, b [-0.4 .. 0.4]
170 // alpha [0..1]
171 let [l, a, b, alpha] = color.to_oklaba();
172 let variables = [("l", l), ("a", a), ("b", b), ("alpha", alpha)];
173 if let Some([l, a, b, alpha]) = parse_values(values, variables) {
174 return Ok(Color::from_oklaba(l.max(0.0), a, b, alpha));
175 };
176 }
177 ParseColorError::InvalidOklch => {
178 // l [0..1]
179 // c [0..0.4]
180 // h [0..360]
181 // alpha [0..1]
182 let [l, c, h, a] = color.to_oklcha();
183 let variables = [("l", l), ("c", c), ("h", h.to_degrees()), ("alpha", a)];
184 if let Some([l, c, h, a]) = parse_values(values, variables) {
185 return Ok(Color::from_oklcha(
186 l.max(0.0),
187 c.max(0.0),
188 h.to_radians(),
189 a,
190 ));
191 };
192 }
193 _ => unreachable!(),
194 }
195 return Err(err);
196 }
197
198 unreachable!();
199 }
200
201 fn parse_abs(s: &str) -> Result<Color, ParseColorError> {
202 if s.eq_ignore_ascii_case("transparent") {
203 return Ok(Color::new(0.0, 0.0, 0.0, 0.0));
204 }
205
206 // Hex format
207 if let Some(s) = s.strip_prefix('#') {
208 return parse_hex(s);
209 }
210
211 if let (Some(idx), Some(s)) = (s.find('('), s.strip_suffix(')')) {
212 let fname = &s[..idx].trim_end();
213
214 let err = match fname {
215 s if s.eq_ignore_ascii_case("rgb") || s.eq_ignore_ascii_case("rgba") => {
216 ParseColorError::InvalidRgb
217 }
218 s if s.eq_ignore_ascii_case("hsl") || s.eq_ignore_ascii_case("hsla") => {
219 ParseColorError::InvalidHsl
220 }
221 s if s.eq_ignore_ascii_case("hwb") || s.eq_ignore_ascii_case("hwba") => {
222 ParseColorError::InvalidHwb
223 }
224 s if s.eq_ignore_ascii_case("hsv") || s.eq_ignore_ascii_case("hsva") => {
225 ParseColorError::InvalidHsv
226 }
227 s if s.eq_ignore_ascii_case("lab") => ParseColorError::InvalidLab,
228 s if s.eq_ignore_ascii_case("lch") => ParseColorError::InvalidLch,
229 s if s.eq_ignore_ascii_case("oklab") => ParseColorError::InvalidOklab,
230 s if s.eq_ignore_ascii_case("oklch") => ParseColorError::InvalidOklch,
231 _ => return Err(ParseColorError::InvalidFunction),
232 };
233
234 let s = &s[idx + 1..];
235
236 if !s.is_ascii() {
237 return Err(err);
238 }
239
240 let mut pp = ParamParser::new(s);
241 pp.space();
242
243 let (Some(val0), true, Some(val1), true, Some(val2)) = (
244 pp.value(),
245 pp.comma_or_space(),
246 pp.value(),
247 pp.comma_or_space(),
248 pp.value(),
249 ) else {
250 return Err(err);
251 };
252
253 let is_space = pp.space();
254
255 let alpha = if pp.is_end() {
256 1.0
257 } else if let (true, Some(a), _, true) = (
258 pp.comma_or_slash() || is_space,
259 pp.value(),
260 pp.space(),
261 pp.is_end(),
262 ) {
263 if let Some((v, _)) = parse_percent_or_float(a) {
264 v.clamp(0.0, 1.0)
265 } else {
266 return Err(err);
267 }
268 } else {
269 return Err(err);
270 };
271
272 match err {
273 ParseColorError::InvalidRgb => {
274 if let (Some(r), Some(g), Some(b)) = (
275 // red
276 parse_percent_or_255(val0),
277 // green
278 parse_percent_or_255(val1),
279 // blue
280 parse_percent_or_255(val2),
281 ) {
282 return Ok(Color {
283 r: r.clamp(0.0, 1.0),
284 g: g.clamp(0.0, 1.0),
285 b: b.clamp(0.0, 1.0),
286 a: alpha,
287 });
288 }
289 }
290 ParseColorError::InvalidHsl => {
291 if let (Some(h), Some((s, _)), Some((l, _))) = (
292 // hue
293 parse_angle(val0),
294 // saturation
295 parse_percent_or_float(val1),
296 // lightness
297 parse_percent_or_float(val2),
298 ) {
299 return Ok(Color::from_hsla(h, s, l, alpha));
300 }
301 }
302 ParseColorError::InvalidHwb => {
303 if let (Some(h), Some((w, _)), Some((b, _))) = (
304 // hue
305 parse_angle(val0),
306 // whiteness
307 parse_percent_or_float(val1),
308 // blackness
309 parse_percent_or_float(val2),
310 ) {
311 return Ok(Color::from_hwba(h, w, b, alpha));
312 }
313 }
314 ParseColorError::InvalidHsv => {
315 if let (Some(h), Some((s, _)), Some((v, _))) = (
316 // hue
317 parse_angle(val0),
318 // saturation
319 parse_percent_or_float(val1),
320 // value
321 parse_percent_or_float(val2),
322 ) {
323 return Ok(Color::from_hsva(h, s, v, alpha));
324 }
325 }
326 ParseColorError::InvalidLab => {
327 if let (Some((l, l_pct)), Some((a, a_pct)), Some((b, b_pct))) = (
328 // lightness
329 parse_percent_or_float(val0),
330 // a
331 parse_percent_or_float(val1),
332 // b
333 parse_percent_or_float(val2),
334 ) {
335 let l = if l_pct { l * 100.0 } else { l };
336 let a = if a_pct {
337 remap(a, -1.0, 1.0, -125.0, 125.0)
338 } else {
339 a
340 };
341 let b = if b_pct {
342 remap(b, -1.0, 1.0, -125.0, 125.0)
343 } else {
344 b
345 };
346 return Ok(Color::from_laba(l.max(0.0), a, b, alpha));
347 }
348 }
349 ParseColorError::InvalidLch => {
350 if let (Some((l, l_pct)), Some((c, c_pct)), Some(h)) = (
351 // lightness
352 parse_percent_or_float(val0),
353 // chroma
354 parse_percent_or_float(val1),
355 // hue
356 parse_angle(val2),
357 ) {
358 let l = if l_pct { l * 100.0 } else { l };
359 let c = if c_pct { c * 150.0 } else { c };
360 return Ok(Color::from_lcha(
361 l.max(0.0),
362 c.max(0.0),
363 h.to_radians(),
364 alpha,
365 ));
366 }
367 }
368 ParseColorError::InvalidOklab => {
369 if let (Some((l, _)), Some((a, a_pct)), Some((b, b_pct))) = (
370 // lightness
371 parse_percent_or_float(val0),
372 // a
373 parse_percent_or_float(val1),
374 // b
375 parse_percent_or_float(val2),
376 ) {
377 let a = if a_pct {
378 remap(a, -1.0, 1.0, -0.4, 0.4)
379 } else {
380 a
381 };
382 let b = if b_pct {
383 remap(b, -1.0, 1.0, -0.4, 0.4)
384 } else {
385 b
386 };
387 return Ok(Color::from_oklaba(l.max(0.0), a, b, alpha));
388 }
389 }
390 ParseColorError::InvalidOklch => {
391 if let (Some((l, _)), Some((c, c_pct)), Some(h)) = (
392 // lightness
393 parse_percent_or_float(val0),
394 // chroma
395 parse_percent_or_float(val1),
396 // hue
397 parse_angle(val2),
398 ) {
399 let c = if c_pct { c * 0.4 } else { c };
400 return Ok(Color::from_oklcha(
401 l.max(0.0),
402 c.max(0.0),
403 h.to_radians(),
404 alpha,
405 ));
406 }
407 }
408 _ => unreachable!(),
409 }
410 return Err(err);
411 }
412
413 // Hex format without prefix '#'
414 if let Ok(c) = parse_hex(s) {
415 return Ok(c);
416 }
417
418 // Named colors
419 #[cfg(feature = "named-colors")]
420 if s.len() > 2 && s.len() < 21 {
•421 let lower = s.to_ascii_lowercase();
422 if let Some([r, g, b]) = NAMED_COLORS.get(&lower as &str) {
423 return Ok(Color::from_rgba8(*r, *g, *b, 255));
424 }
425 }
426
427 Err(ParseColorError::InvalidUnknown)
428 }
429
430 fn parse_hex(s: &str) -> Result<Color, ParseColorError> {
431 if !s.is_ascii() {
432 return Err(ParseColorError::InvalidHex);
433 }
434
435 let n = s.len();
436
437 fn parse_single_digit(digit: &str) -> Result<u8, ParseColorError> {
438 u8::from_str_radix(digit, 16)
439 .map(|n| (n << 4) | n)
440 .map_err(|_| ParseColorError::InvalidHex)
441 }
442
443 if n == 3 || n == 4 {
444 let r = parse_single_digit(&s[0..1])?;
445 let g = parse_single_digit(&s[1..2])?;
446 let b = parse_single_digit(&s[2..3])?;
447
448 let a = if n == 4 {
449 parse_single_digit(&s[3..4])?
450 } else {
451 255
452 };
453
454 Ok(Color::from_rgba8(r, g, b, a))
455 } else if n == 6 || n == 8 {
456 let r = u8::from_str_radix(&s[0..2], 16).map_err(|_| ParseColorError::InvalidHex)?;
457 let g = u8::from_str_radix(&s[2..4], 16).map_err(|_| ParseColorError::InvalidHex)?;
458 let b = u8::from_str_radix(&s[4..6], 16).map_err(|_| ParseColorError::InvalidHex)?;
459
460 let a = if n == 8 {
461 u8::from_str_radix(&s[6..8], 16).map_err(|_| ParseColorError::InvalidHex)?
462 } else {
463 255
464 };
465
466 Ok(Color::from_rgba8(r, g, b, a))
467 } else {
468 Err(ParseColorError::InvalidHex)
469 }
470 }
471
472 // strip suffix ignore case
473 fn strip_suffix<'a>(s: &'a str, suffix: &str) -> Option<&'a str> {
474 if suffix.len() > s.len() {
475 return None;
476 }
477 let s_end = &s[s.len() - suffix.len()..];
478 if s_end.eq_ignore_ascii_case(suffix) {
479 Some(&s[..s.len() - suffix.len()])
480 } else {
481 None
482 }
483 }
484
485 fn parse_percent_or_float(s: &str) -> Option<(f32, bool)> {
486 if s.eq_ignore_ascii_case("none") {
487 return Some((0.0, false));
488 }
489 s.strip_suffix('%')
490 .and_then(|s| s.parse().ok().map(|t: f32| (t / 100.0, true)))
491 .or_else(|| s.parse().ok().map(|t| (t, false)))
492 }
493
494 fn parse_percent_or_255(s: &str) -> Option<f32> {
495 if s.eq_ignore_ascii_case("none") {
496 return Some(0.0);
497 }
498 s.strip_suffix('%')
499 .and_then(|s| s.parse().ok().map(|t: f32| t / 100.0))
500 .or_else(|| s.parse().ok().map(|t: f32| t / 255.0))
501 }
502
503 fn parse_angle(s: &str) -> Option<f32> {
504 if s.eq_ignore_ascii_case("none") {
505 return Some(0.0);
506 }
507 strip_suffix(s, "deg")
508 .and_then(|s| s.parse().ok())
509 .or_else(|| {
510 strip_suffix(s, "grad")
511 .and_then(|s| s.parse().ok())
512 .map(|t: f32| t * 360.0 / 400.0)
513 })
514 .or_else(|| {
515 strip_suffix(s, "rad")
516 .and_then(|s| s.parse().ok())
517 .map(|t: f32| t.to_degrees())
518 })
519 .or_else(|| {
520 strip_suffix(s, "turn")
521 .and_then(|s| s.parse().ok())
522 .map(|t: f32| t * 360.0)
523 })
524 .or_else(|| s.parse().ok())
525 }
526
527 #[cfg(test)]
528 mod t {
529 use super::*;
530
531 #[test]
532 fn strip_suffix_() {
533 assert_eq!(strip_suffix("45deg", "deg"), Some("45"));
534 assert_eq!(strip_suffix("90DEG", "deg"), Some("90"));
535 assert_eq!(strip_suffix("0.25turn", "turn"), Some("0.25"));
536 assert_eq!(strip_suffix("1.0Turn", "turn"), Some("1.0"));
537
538 assert_eq!(strip_suffix("", "deg"), None);
539 assert_eq!(strip_suffix("90", "deg"), None);
540 }
541
542 #[test]
543 fn parse_percent_or_float_() {
544 let test_data = [
545 ("none", Some((0.0, false))),
546 ("NONE", Some((0.0, false))),
547 ("0%", Some((0.0, true))),
548 ("100%", Some((1.0, true))),
549 ("50%", Some((0.5, true))),
550 ("0", Some((0.0, false))),
551 ("1", Some((1.0, false))),
552 ("0.5", Some((0.5, false))),
553 ("100.0", Some((100.0, false))),
554 ("-23.7", Some((-23.7, false))),
555 ("%", None),
556 ("1x", None),
557 ];
558 for (s, expected) in test_data {
559 assert_eq!(parse_percent_or_float(s), expected);
560 }
561 }
562
563 #[test]
564 fn parse_percent_or_255_() {
565 let test_data = [
566 ("none", Some(0.0)),
567 ("NONE", Some(0.0)),
568 ("0%", Some(0.0)),
569 ("100%", Some(1.0)),
570 ("50%", Some(0.5)),
571 ("-100%", Some(-1.0)),
572 ("0", Some(0.0)),
573 ("255", Some(1.0)),
574 ("127.5", Some(0.5)),
575 ("%", None),
576 ("255x", None),
577 ];
578 for (s, expected) in test_data {
579 assert_eq!(parse_percent_or_255(s), expected);
580 }
581 }
582
583 #[test]
584 fn parse_angle_() {
585 let test_data = [
586 ("none", Some(0.0)),
587 ("NONE", Some(0.0)),
588 ("360", Some(360.0)),
589 ("127.356", Some(127.356)),
590 ("+120deg", Some(120.0)),
591 ("90deg", Some(90.0)),
592 ("-127deg", Some(-127.0)),
593 ("100grad", Some(90.0)),
594 ("1.5707963267948966rad", Some(90.0)),
595 ("0.25turn", Some(90.0)),
596 ("-0.25turn", Some(-90.0)),
597 ("O", None),
598 ("Odeg", None),
599 ("rad", None),
600 ];
601 for (s, expected) in test_data {
602 assert_eq!(parse_angle(s), expected);
603 }
604 }
605
606 #[test]
607 fn parse_hex_() {
608 // case-insensitive tests
609 macro_rules! cmp {
610 ($a:expr, $b:expr) => {
611 assert_eq!(
612 parse_hex($a).unwrap().to_rgba8(),
613 parse_hex($b).unwrap().to_rgba8()
614 );
615 };
616 }
617 cmp!("abc", "ABC");
618 cmp!("DeF", "dEf");
619 cmp!("f0eB", "F0Eb");
620 cmp!("abcdef", "ABCDEF");
621 cmp!("Ff03E0cB", "fF03e0Cb");
622 }
623 }