Debian Codegraph @

src/color.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use core::convert::TryFrom;
2 use core::fmt;
3 use core::str::FromStr;
4
5 use alloc::format;
6 use alloc::string::String;
7 use alloc::string::ToString;
8
9 #[cfg(not(feature = "std"))]
10 use num_traits::float::Float;
11
12 #[cfg(feature = "rust-rgb")]
13 use rgb::{RGB, RGBA};
14
15 #[cfg(feature = "serde")]
16 use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
17
18 use crate::lab::{lab_to_linear_rgb, linear_rgb_to_lab};
19 use crate::utils::*;
20 use crate::{parse, ParseColorError};
21
22 #[cfg(feature = "named-colors")]
23 use crate::NAMED_COLORS;
24
25 #[derive(Debug, Clone, PartialEq, PartialOrd)]
26 /// The color
27 pub struct Color {
28 /// Red
29 pub r: f32,
30 /// Green
31 pub g: f32,
32 /// Blue
33 pub b: f32,
34 /// Alpha
35 pub a: f32,
36 }
37
38 impl Color {
39 /// Arguments:
40 ///
41 /// * `r`: Red value [0..1]
42 /// * `g`: Green value [0..1]
43 /// * `b`: Blue value [0..1]
44 /// * `a`: Alpha value [0..1]
45 pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
46 Self { r, g, b, a }
47 }
48
49 /// Arguments:
50 ///
51 /// * `r`: Red value [0..255]
52 /// * `g`: Green value [0..255]
53 /// * `b`: Blue value [0..255]
54 /// * `a`: Alpha value [0..255]
55 pub const fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
56 Self {
57 r: r as f32 / 255.0,
58 g: g as f32 / 255.0,
59 b: b as f32 / 255.0,
60 a: a as f32 / 255.0,
61 }
62 }
63
64 /// Arguments:
65 ///
66 /// * `r`: Red value [0..1]
67 /// * `g`: Green value [0..1]
68 /// * `b`: Blue value [0..1]
69 /// * `a`: Alpha value [0..1]
70 pub fn from_linear_rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
71 fn from_linear(x: f32) -> f32 {
72 if x >= 0.0031308 {
73 return 1.055 * x.powf(1.0 / 2.4) - 0.055;
74 }
75 12.92 * x
76 }
77 Self::new(from_linear(r), from_linear(g), from_linear(b), a)
78 }
79
80 /// Arguments:
81 ///
82 /// * `r`: Red value [0..255]
83 /// * `g`: Green value [0..255]
84 /// * `b`: Blue value [0..255]
85 /// * `a`: Alpha value [0..255]
86 pub fn from_linear_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
87 Self::from_linear_rgba(
88 r as f32 / 255.0,
89 g as f32 / 255.0,
90 b as f32 / 255.0,
91 a as f32 / 255.0,
92 )
93 }
94
95 /// Arguments:
96 ///
97 /// * `h`: Hue angle [0..360]
98 /// * `s`: Saturation [0..1]
99 /// * `v`: Value [0..1]
100 /// * `a`: Alpha [0..1]
101 pub const fn from_hsva(h: f32, s: f32, v: f32, a: f32) -> Self {
102 let [r, g, b] = hsv_to_rgb(normalize_angle(h), s.clamp(0.0, 1.0), v.clamp(0.0, 1.0));
103 Self::new(r, g, b, a)
104 }
105
106 /// Arguments:
107 ///
108 /// * `h`: Hue angle [0..360]
109 /// * `s`: Saturation [0..1]
110 /// * `l`: Lightness [0..1]
111 /// * `a`: Alpha [0..1]
112 pub const fn from_hsla(h: f32, s: f32, l: f32, a: f32) -> Self {
113 let [r, g, b] = hsl_to_rgb(normalize_angle(h), s.clamp(0.0, 1.0), l.clamp(0.0, 1.0));
114 Self::new(r, g, b, a)
115 }
116
117 /// Arguments:
118 ///
119 /// * `h`: Hue angle [0..360]
120 /// * `w`: Whiteness [0..1]
121 /// * `b`: Blackness [0..1]
122 /// * `a`: Alpha [0..1]
123 pub const fn from_hwba(h: f32, w: f32, b: f32, a: f32) -> Self {
124 let [r, g, b] = hwb_to_rgb(normalize_angle(h), w.clamp(0.0, 1.0), b.clamp(0.0, 1.0));
125 Self::new(r, g, b, a)
126 }
127
128 /// Arguments:
129 ///
130 /// * `l`: Perceived lightness
131 /// * `a`: How green/red the color is
132 /// * `b`: How blue/yellow the color is
133 /// * `alpha`: Alpha [0..1]
134 pub fn from_oklaba(l: f32, a: f32, b: f32, alpha: f32) -> Self {
135 let [r, g, b] = oklab_to_linear_rgb(l, a, b);
136 Self::from_linear_rgba(r, g, b, alpha)
137 }
138
139 /// Arguments:
140 ///
141 /// * `l`: Perceived lightness
142 /// * `c`: Chroma
143 /// * `h`: Hue angle in radians
144 /// * `alpha`: Alpha [0..1]
145 pub fn from_oklcha(l: f32, c: f32, h: f32, alpha: f32) -> Self {
146 Self::from_oklaba(l, c * h.cos(), c * h.sin(), alpha)
147 }
148
149 /// Arguments:
150 ///
151 /// * `l`: Lightness
152 /// * `a`: Distance along the `a` axis
153 /// * `b`: Distance along the `b` axis
154 /// * `alpha`: Alpha [0..1]
155 pub fn from_laba(l: f32, a: f32, b: f32, alpha: f32) -> Self {
156 let [r, g, b] = lab_to_linear_rgb(l, a, b);
157 Self::from_linear_rgba(r, g, b, alpha)
158 }
159
160 /// Arguments:
161 ///
162 /// * `l`: Lightness
163 /// * `c`: Chroma
164 /// * `h`: Hue angle in radians
165 /// * `alpha`: Alpha [0..1]
166 pub fn from_lcha(l: f32, c: f32, h: f32, alpha: f32) -> Self {
167 Self::from_laba(l, c * h.cos(), c * h.sin(), alpha)
168 }
169
170 /// Create color from CSS color string.
171 ///
172 /// # Examples
173 /// ```
174 /// use csscolorparser::Color;
175 /// # use core::error::Error;
176 /// # fn main() -> Result<(), Box<dyn Error>> {
177 ///
178 /// let c = Color::from_html("rgb(255,0,0)")?;
179 ///
180 /// assert_eq!(c.to_array(), [1.0, 0.0, 0.0, 1.0]);
181 /// assert_eq!(c.to_rgba8(), [255, 0, 0, 255]);
182 /// assert_eq!(c.to_css_hex(), "#ff0000");
183 /// assert_eq!(c.to_css_rgb(), "rgb(255 0 0)");
184 /// # Ok(())
185 /// # }
186 /// ```
187 pub fn from_html<S: AsRef<str>>(s: S) -> Result<Self, ParseColorError> {
188 parse(s.as_ref())
189 }
190
191 /// Restricts R, G, B, A values to the range [0..1].
192 #[must_use = "method returns a new Color and does not mutate the original Color"]
193 pub const fn clamp(&self) -> Self {
194 Self {
195 r: self.r.clamp(0.0, 1.0),
196 g: self.g.clamp(0.0, 1.0),
197 b: self.b.clamp(0.0, 1.0),
198 a: self.a.clamp(0.0, 1.0),
199 }
200 }
201
202 /// Returns name if there is a name for this color.
203 ///
204 /// **Note:** It ignores transparency (alpha value).
205 ///
206 /// ```
207 /// use csscolorparser::Color;
208 ///
209 /// assert_eq!(Color::from_rgba8(255, 0, 0, 255).name(), Some("red"));
210 /// assert_eq!(Color::from_rgba8(238, 130, 238, 255).name(), Some("violet"));
211 /// assert_eq!(Color::from_rgba8(90, 150, 200, 255).name(), None);
212 /// ```
213 #[cfg(feature = "named-colors")]
214 pub fn name(&self) -> Option<&'static str> {
215 let rgb = &self.to_rgba8()[0..3];
216 for (&k, v) in NAMED_COLORS.entries() {
217 if v == rgb {
•218 return Some(k);
219 }
220 }
221 None
222 }
223
224 /// Returns: `[r, g, b, a]`
225 ///
226 /// * Red, green, blue and alpha in the range [0..1]
227 pub const fn to_array(&self) -> [f32; 4] {
228 [
229 self.r.clamp(0.0, 1.0),
230 self.g.clamp(0.0, 1.0),
231 self.b.clamp(0.0, 1.0),
232 self.a.clamp(0.0, 1.0),
233 ]
234 }
235
236 /// Returns: `[r, g, b, a]`
237 ///
238 /// * Red, green, blue and alpha in the range [0..255]
239 pub const fn to_rgba8(&self) -> [u8; 4] {
240 [
241 (self.r * 255.0 + 0.5) as u8,
242 (self.g * 255.0 + 0.5) as u8,
243 (self.b * 255.0 + 0.5) as u8,
244 (self.a * 255.0 + 0.5) as u8,
245 ]
246 }
247
248 /// Returns: `[r, g, b, a]`
249 ///
250 /// * Red, green, blue and alpha in the range [0..65535]
251 pub const fn to_rgba16(&self) -> [u16; 4] {
252 [
253 (self.r * 65535.0 + 0.5) as u16,
254 (self.g * 65535.0 + 0.5) as u16,
255 (self.b * 65535.0 + 0.5) as u16,
256 (self.a * 65535.0 + 0.5) as u16,
257 ]
258 }
259
260 /// Returns: `[h, s, v, a]`
261 ///
262 /// * `h`: Hue angle [0..360]
263 /// * `s`: Saturation [0..1]
264 /// * `v`: Value [0..1]
265 /// * `a`: Alpha [0..1]
266 pub const fn to_hsva(&self) -> [f32; 4] {
267 let [h, s, v] = rgb_to_hsv(
268 self.r.clamp(0.0, 1.0),
269 self.g.clamp(0.0, 1.0),
270 self.b.clamp(0.0, 1.0),
271 );
272 [
273 h,
274 s.clamp(0.0, 1.0),
275 v.clamp(0.0, 1.0),
276 self.a.clamp(0.0, 1.0),
277 ]
278 }
279
280 /// Returns: `[h, s, l, a]`
281 ///
282 /// * `h`: Hue angle [0..360]
283 /// * `s`: Saturation [0..1]
284 /// * `l`: Lightness [0..1]
285 /// * `a`: Alpha [0..1]
286 pub const fn to_hsla(&self) -> [f32; 4] {
287 let [h, s, l] = rgb_to_hsl(
288 self.r.clamp(0.0, 1.0),
289 self.g.clamp(0.0, 1.0),
290 self.b.clamp(0.0, 1.0),
291 );
292 [
293 h,
294 s.clamp(0.0, 1.0),
295 l.clamp(0.0, 1.0),
296 self.a.clamp(0.0, 1.0),
297 ]
298 }
299
300 /// Returns: `[h, w, b, a]`
301 ///
302 /// * `h`: Hue angle [0..360]
303 /// * `w`: Whiteness [0..1]
304 /// * `b`: Blackness [0..1]
305 /// * `a`: Alpha [0..1]
306 pub const fn to_hwba(&self) -> [f32; 4] {
307 let [h, w, b] = rgb_to_hwb(
308 self.r.clamp(0.0, 1.0),
309 self.g.clamp(0.0, 1.0),
310 self.b.clamp(0.0, 1.0),
311 );
312 [
313 h,
314 w.clamp(0.0, 1.0),
315 b.clamp(0.0, 1.0),
316 self.a.clamp(0.0, 1.0),
317 ]
318 }
319
320 /// Returns: `[r, g, b, a]`
321 ///
322 /// * Red, green, blue and alpha in the range [0..1]
323 pub fn to_linear_rgba(&self) -> [f32; 4] {
324 fn to_linear(x: f32) -> f32 {
325 if x >= 0.04045 {
326 return ((x + 0.055) / 1.055).powf(2.4);
327 }
328 x / 12.92
329 }
330 [
331 to_linear(self.r),
332 to_linear(self.g),
333 to_linear(self.b),
334 self.a,
335 ]
336 }
337
338 /// Returns: `[r, g, b, a]`
339 ///
340 /// * Red, green, blue and alpha in the range [0..255]
341 pub fn to_linear_rgba_u8(&self) -> [u8; 4] {
342 let [r, g, b, a] = self.to_linear_rgba();
343 [
344 (r * 255.0).round() as u8,
345 (g * 255.0).round() as u8,
346 (b * 255.0).round() as u8,
347 (a * 255.0).round() as u8,
348 ]
349 }
350
351 /// Returns: `[l, a, b, alpha]`
352 pub fn to_oklaba(&self) -> [f32; 4] {
353 let [r, g, b, _] = self.to_linear_rgba();
354 let [l, a, b] = linear_rgb_to_oklab(r, g, b);
355 [l, a, b, self.a.clamp(0.0, 1.0)]
356 }
357
358 /// Returns: `[l, c, h, alpha]`
359 pub fn to_oklcha(&self) -> [f32; 4] {
360 let [l, a, b, alpha] = self.to_oklaba();
361 let c = (a * a + b * b).sqrt();
362 let h = b.atan2(a);
363 [l, c, h, alpha]
364 }
365
366 /// Returns: `[l, a, b, alpha]`
367 pub fn to_laba(&self) -> [f32; 4] {
368 let [r, g, b, alpha] = self.to_linear_rgba();
369 let [l, a, b] = linear_rgb_to_lab(r, g, b);
370 [l, a, b, alpha.clamp(0.0, 1.0)]
371 }
372
373 /// Returns: `[l, c, h, alpha]`
374 pub fn to_lcha(&self) -> [f32; 4] {
375 let [l, a, b, alpha] = self.to_laba();
376 let c = (a * a + b * b).sqrt();
377 let h = b.atan2(a);
378 [l, c, h, alpha.clamp(0.0, 1.0)]
379 }
380
381 /// Get CSS RGB hexadecimal color representation
382 pub fn to_css_hex(&self) -> String {
383 self.to_string()
384 }
385
386 /// Get CSS `rgb()` color representation
387 pub fn to_css_rgb(&self) -> String {
388 let [r, g, b, _] = self.to_rgba8();
389 format!("rgb({r} {g} {b}{})", AlphaFmt(self.a))
390 }
391
392 /// Get CSS `hsl()` color representation
393 pub fn to_css_hsl(&self) -> String {
394 let [h, s, l, alpha] = self.to_hsla();
395 let h = FloatFmt(h);
396 let s = (s * 100.0 + 0.5).floor();
397 let l = (l * 100.0 + 0.5).floor();
398 format!("hsl({h} {s}% {l}%{})", AlphaFmt(alpha))
399 }
400
401 /// Get CSS `hwb()` color representation
402 pub fn to_css_hwb(&self) -> String {
403 let [h, w, b, alpha] = self.to_hwba();
404 let h = FloatFmt(h);
405 let w = (w * 100.0 + 0.5).floor();
406 let b = (b * 100.0 + 0.5).floor();
407 format!("hwb({h} {w}% {b}%{})", AlphaFmt(alpha))
408 }
409
410 /// Get CSS `oklab()` color representation
411 pub fn to_css_oklab(&self) -> String {
412 let [l, a, b, alpha] = self.to_oklaba();
413 let l = FloatFmt(l);
414 let a = FloatFmt(a);
415 let b = FloatFmt(b);
416 format!("oklab({l} {a} {b}{})", AlphaFmt(alpha))
417 }
418
419 /// Get CSS `oklch()` color representation
420 pub fn to_css_oklch(&self) -> String {
421 let [l, c, h, alpha] = self.to_oklcha();
422 let l = FloatFmt(l);
423 let c = FloatFmt(c);
424 let h = FloatFmt(normalize_angle(h.to_degrees()));
425 format!("oklch({l} {c} {h}{})", AlphaFmt(alpha))
426 }
427
428 /// Get CSS `lab()` color representation
429 pub fn to_css_lab(&self) -> String {
430 let [l, a, b, alpha] = self.to_laba();
431 let l = FloatFmt(l);
432 let a = FloatFmt(a);
433 let b = FloatFmt(b);
434 format!("lab({l} {a} {b}{})", AlphaFmt(alpha))
435 }
436
437 /// Get CSS `lch()` color representation
438 pub fn to_css_lch(&self) -> String {
439 use core::f32::consts::PI;
440
441 fn to_degrees(t: f32) -> f32 {
442 if t > 0.0 {
443 t / PI * 180.0
444 } else {
445 360.0 - (t.abs() / PI) * 180.0
446 }
447 }
448
449 let [l, c, h, alpha] = self.to_lcha();
450 let l = FloatFmt(l);
451 let c = FloatFmt(c);
452 let h = FloatFmt(to_degrees(h));
453 format!("lch({l} {c} {h}{})", AlphaFmt(alpha))
454 }
455
456 /// Blend this color with the other one, in the RGB color-space. `t` in the range [0..1].
457 pub const fn interpolate_rgb(&self, other: &Color, t: f32) -> Self {
458 Self {
459 r: self.r + t * (other.r - self.r),
460 g: self.g + t * (other.g - self.g),
461 b: self.b + t * (other.b - self.b),
462 a: self.a + t * (other.a - self.a),
463 }
464 }
465
466 /// Blend this color with the other one, in the linear RGB color-space. `t` in the range [0..1].
467 pub fn interpolate_linear_rgb(&self, other: &Color, t: f32) -> Self {
468 let [r1, g1, b1, a1] = self.to_linear_rgba();
469 let [r2, g2, b2, a2] = other.to_linear_rgba();
470 Self::from_linear_rgba(
471 r1 + t * (r2 - r1),
472 g1 + t * (g2 - g1),
473 b1 + t * (b2 - b1),
474 a1 + t * (a2 - a1),
475 )
476 }
477
478 /// Blend this color with the other one, in the HSV color-space. `t` in the range [0..1].
479 pub const fn interpolate_hsv(&self, other: &Color, t: f32) -> Self {
480 let [h1, s1, v1, a1] = self.to_hsva();
481 let [h2, s2, v2, a2] = other.to_hsva();
482 Self::from_hsva(
483 interp_angle(h1, h2, t),
484 s1 + t * (s2 - s1),
485 v1 + t * (v2 - v1),
486 a1 + t * (a2 - a1),
487 )
488 }
489
490 /// Blend this color with the other one, in the [Oklab](https://bottosson.github.io/posts/oklab/) color-space. `t` in the range [0..1].
491 pub fn interpolate_oklab(&self, other: &Color, t: f32) -> Self {
492 let [l1, a1, b1, alpha1] = self.to_oklaba();
493 let [l2, a2, b2, alpha2] = other.to_oklaba();
494 Self::from_oklaba(
495 l1 + t * (l2 - l1),
496 a1 + t * (a2 - a1),
497 b1 + t * (b2 - b1),
498 alpha1 + t * (alpha2 - alpha1),
499 )
500 }
501
502 /// Blend this color with the other one, in the Lab color-space. `t` in the range [0..1].
503 pub fn interpolate_lab(&self, other: &Color, t: f32) -> Self {
504 let [l1, a1, b1, alpha1] = self.to_laba();
505 let [l2, a2, b2, alpha2] = other.to_laba();
506 Self::from_laba(
507 l1 + t * (l2 - l1),
508 a1 + t * (a2 - a1),
509 b1 + t * (b2 - b1),
510 alpha1 + t * (alpha2 - alpha1),
511 )
512 }
513
514 /// Blend this color with the other one, in the LCH color-space. `t` in the range [0..1].
515 pub fn interpolate_lch(&self, other: &Color, t: f32) -> Self {
516 let [l1, c1, h1, alpha1] = self.to_lcha();
517 let [l2, c2, h2, alpha2] = other.to_lcha();
518 Self::from_lcha(
519 l1 + t * (l2 - l1),
520 c1 + t * (c2 - c1),
521 interp_angle_rad(h1, h2, t),
522 alpha1 + t * (alpha2 - alpha1),
523 )
524 }
525 }
526
527 impl Default for Color {
528 fn default() -> Self {
529 Self {
530 r: 0.0,
531 g: 0.0,
532 b: 0.0,
533 a: 1.0,
534 }
535 }
536 }
537
538 impl fmt::Display for Color {
539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
540 let [r, g, b, a] = self.to_rgba8();
541 if a < 255 {
542 write!(f, "#{r:02x}{g:02x}{b:02x}{a:02x}")
543 } else {
544 write!(f, "#{r:02x}{g:02x}{b:02x}")
545 }
546 }
547 }
548
549 impl FromStr for Color {
550 type Err = ParseColorError;
551
552 fn from_str(s: &str) -> Result<Self, Self::Err> {
553 parse(s)
554 }
555 }
556
557 impl TryFrom<&str> for Color {
558 type Error = ParseColorError;
559
560 fn try_from(s: &str) -> Result<Self, Self::Error> {
561 parse(s)
562 }
563 }
564
565 impl TryFrom<String> for Color {
566 type Error = ParseColorError;
567
568 fn try_from(s: String) -> Result<Self, Self::Error> {
569 parse(s.as_ref())
570 }
571 }
572
573 impl From<(f32, f32, f32, f32)> for Color {
574 fn from((r, g, b, a): (f32, f32, f32, f32)) -> Self {
575 Self { r, g, b, a }
576 }
577 }
578
579 impl From<(f32, f32, f32)> for Color {
580 fn from((r, g, b): (f32, f32, f32)) -> Self {
581 Self { r, g, b, a: 1.0 }
582 }
583 }
584
585 impl From<[f32; 4]> for Color {
586 fn from([r, g, b, a]: [f32; 4]) -> Self {
587 Self { r, g, b, a }
588 }
589 }
590
591 impl From<[f32; 3]> for Color {
592 fn from([r, g, b]: [f32; 3]) -> Self {
593 Self { r, g, b, a: 1.0 }
594 }
595 }
596
597 impl From<[f64; 4]> for Color {
598 fn from([r, g, b, a]: [f64; 4]) -> Self {
599 Self {
600 r: r as f32,
601 g: g as f32,
602 b: b as f32,
603 a: a as f32,
604 }
605 }
606 }
607
608 impl From<[f64; 3]> for Color {
609 fn from([r, g, b]: [f64; 3]) -> Self {
610 Self {
611 r: r as f32,
612 g: g as f32,
613 b: b as f32,
614 a: 1.0,
615 }
616 }
617 }
618
619 impl From<(u8, u8, u8, u8)> for Color {
620 fn from((r, g, b, a): (u8, u8, u8, u8)) -> Self {
621 Self::from_rgba8(r, g, b, a)
622 }
623 }
624
625 impl From<(u8, u8, u8)> for Color {
626 fn from((r, g, b): (u8, u8, u8)) -> Self {
627 Self::from_rgba8(r, g, b, 255)
628 }
629 }
630
631 impl From<[u8; 4]> for Color {
632 fn from([r, g, b, a]: [u8; 4]) -> Self {
633 Self::from_rgba8(r, g, b, a)
634 }
635 }
636
637 impl From<[u8; 3]> for Color {
638 fn from([r, g, b]: [u8; 3]) -> Self {
639 Self::from_rgba8(r, g, b, 255)
640 }
641 }
642
643 /// Convert rust-rgb's `RGB<f32>` type into `Color`.
644 #[cfg(feature = "rust-rgb")]
645 impl From<RGB<f32>> for Color {
646 fn from(item: RGB<f32>) -> Self {
647 Self::new(item.r, item.g, item.b, 1.0)
648 }
649 }
650
651 /// Convert rust-rgb's `RGBA<f32>` type into `Color`.
652 #[cfg(feature = "rust-rgb")]
653 impl From<RGBA<f32>> for Color {
654 fn from(item: RGBA<f32>) -> Self {
655 Self::new(item.r, item.g, item.b, item.a)
656 }
657 }
658
659 /// Implement Serde serialization into HEX string
660 #[cfg(feature = "serde")]
661 impl Serialize for Color {
662 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
663 serializer.collect_str(self)
664 }
665 }
666
667 /// Implement Serde deserialization from string
668 #[cfg(feature = "serde")]
669 impl<'de> Deserialize<'de> for Color {
670 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
671 deserializer.deserialize_str(ColorVisitor)
672 }
673 }
674
675 #[cfg(feature = "serde")]
676 struct ColorVisitor;
677
678 #[cfg(feature = "serde")]
679 impl Visitor<'_> for ColorVisitor {
680 type Value = Color;
681
682 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
683 f.write_str("a valid css color")
684 }
685
686 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
687 where
688 E: serde::de::Error,
689 {
690 Color::from_str(v).map_err(serde::de::Error::custom)
691 }
692 }
693
694 #[cfg(test)]
695 mod t {
696 #[cfg(any(feature = "serde", feature = "rust-rgb"))]
697 use super::*;
698
699 #[cfg(feature = "rust-rgb")]
700 #[test]
701 fn rust_rgb() {
702 let rgb = RGB::new(0.0, 0.5, 1.0);
703 assert_eq!(Color::new(0.0, 0.5, 1.0, 1.0), Color::from(rgb));
704
705 let rgba = RGBA::new(1.0, 0.5, 0.0, 0.5);
706 assert_eq!(Color::new(1.0, 0.5, 0.0, 0.5), Color::from(rgba));
707 }
708
709 #[cfg(feature = "serde")]
710 #[test]
711 fn serde_serialize() {
712 let test_data = [
713 "#000000",
714 "#ffffff",
715 "#71fe15",
716 "#d6e3c9",
717 "#ff000000",
718 "#ffff8080",
719 "#6b9fa203",
720 "#0e5e0be6",
721 "#84f9a716",
722 ];
723 for s in test_data {
724 let color = parse(s).unwrap();
725 serde_test::assert_ser_tokens(&color, &[serde_test::Token::Str(s)]);
726 }
727 }
728
729 #[cfg(feature = "serde")]
730 #[test]
731 fn serde_deserialize() {
732 let col = Color::new(0.0, 1.0, 0.0, 1.0);
733 serde_test::assert_de_tokens(&col, &[serde_test::Token::Str("#00ff00")]);
734 serde_test::assert_de_tokens(&col, &[serde_test::Token::Str("rgb(0 255 0)")]);
735
736 #[cfg(feature = "named-colors")]
737 {
738 serde_test::assert_de_tokens(&col, &[serde_test::Token::Str("lime")]);
739
740 let col = Color::new(1.0, 0.0, 0.0, 1.0);
741 serde_test::assert_de_tokens(&col, &[serde_test::Token::Str("red")]);
742
743 let col = Color::new(1.0, 1.0, 0.0, 1.0);
744 serde_test::assert_de_tokens(&col, &[serde_test::Token::Str("yellow")]);
745 }
746 }
747 }