Skip to main content

mln_style/
color.rs

1// Color stores a *premultiplied* color, all four channels 0..1. `parse` premultiplies; `to_array` /
2// `stringify` un-premultiply back to 0..255 channels (with alpha rounded to
3// two decimals). A color outside sRGB is clipped to it channel by channel, and
4// keeps its unclipped red, green and blue for interpolation, as the style
5// spec's Color does; so does a transparent color, whose premultiplied channels
6// are all 0.
7
8use std::f64::consts::{PI, TAU};
9
10use crate::feature::Value;
11use crate::interpolate::Interpolate;
12use crate::string::to_string_double;
13
14mod css;
15
16/// The space a color interpolation runs in: RGB, LAB and HCL blend the
17/// straight color, OKLCH the premultiplied lightness
18/// and chroma, and OKLAB the premultiplied lightness, a and b.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, mln_wire::Wire)]
20pub enum ColorSpace {
21    Rgb,
22    Lab,
23    Hcl,
24    Oklch,
25    Oklab,
26}
27
28/// Stores a premultiplied color, with all four channels ranging from 0..1.
29#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
30pub struct Color {
31    pub r: f32,
32    pub g: f32,
33    pub b: f32,
34    pub a: f32,
35    /// The straight red, green and blue, which interpolation reads, when `r`,
36    /// `g` and `b` can't give them back: a color outside sRGB's before they
37    /// were clipped to 0..1 (the style spec's `unclippedRgb`), and a
38    /// transparent color's. `None` otherwise.
39    pub straight: Option<[f32; 3]>,
40}
41
42// Below these chromas a hue is missing: GL JS's for HCL, which rounds the
43// chroma to four decimals, and CSS Color 4's for OKLCH
44// (https://drafts.csswg.org/css-color-4/#powerless). The conversions give
45// grays a tiny chroma and some hue.
46const HCL_POWERLESS_CHROMA: f64 = 0.000_05;
47const OKLCH_POWERLESS_CHROMA: f64 = 0.000_004;
48
49// Conversions between sRGB, Oklab and Display P3, as the style spec's
50// color_spaces.ts makes them: CSS Color 4's matrices
51// (https://drafts.csswg.org/css-color-4/#color-conversion-code) in f64, and
52// sRGB's transfer function odd about 0, so a color outside sRGB converts
53// with its channels outside 0..1, and back.
54
55type Vector3 = [f64; 3];
56type Matrix3 = [Vector3; 3];
57
58const LINEAR_SRGB_TO_XYZ: Matrix3 = [
59    [506_752.0 / 1_228_815.0, 87_881.0 / 245_763.0, 12_673.0 / 70_218.0],
60    [87_098.0 / 409_605.0, 175_762.0 / 245_763.0, 12_673.0 / 175_545.0],
61    [7_918.0 / 409_605.0, 87_881.0 / 737_289.0, 1_001_167.0 / 1_053_270.0],
62];
63const XYZ_TO_LINEAR_SRGB: Matrix3 = [
64    [12_831.0 / 3_959.0, -329.0 / 214.0, -1_974.0 / 3_959.0],
65    [-851_781.0 / 878_810.0, 1_648_619.0 / 878_810.0, 36_519.0 / 878_810.0],
66    [705.0 / 12_673.0, -2_585.0 / 12_673.0, 705.0 / 667.0],
67];
68const XYZ_TO_LMS: Matrix3 = [
69    [0.819_022_437_996_703, 0.361_906_260_052_890_4, -0.128_873_781_520_987_9],
70    [0.032_983_653_932_388_5, 0.929_286_861_586_343_4, 0.036_144_666_350_642_4],
71    [0.048_177_189_359_624_2, 0.264_239_531_752_730_8, 0.633_547_828_469_430_9],
72];
73const LMS_TO_OKLAB: Matrix3 = [
74    [0.210_454_268_309_314, 0.793_617_774_702_305_4, -0.004_072_043_011_619_3],
75    [1.977_998_532_431_168_4, -2.428_592_242_048_58, 0.450_593_709_617_411],
76    [0.025_904_042_465_547_8, 0.782_771_712_457_529_6, -0.808_675_754_923_077_4],
77];
78const OKLAB_TO_LMS: Matrix3 = [
79    [1.0, 0.396_337_777_376_174_9, 0.215_803_757_309_913_6],
80    [1.0, -0.105_561_345_815_658_6, -0.063_854_172_825_813_3],
81    [1.0, -0.089_484_177_529_811_9, -1.291_485_548_019_409_2],
82];
83const LMS_TO_XYZ: Matrix3 = [
84    [1.226_879_875_845_924_3, -0.557_814_994_460_217_1, 0.281_391_045_665_964_7],
85    [-0.040_575_745_214_800_8, 1.112_286_803_280_317, -0.071_711_058_065_516_4],
86    [-0.076_372_936_674_660_1, -0.421_493_332_402_243_2, 1.586_924_019_836_781_6],
87];
88const LINEAR_DISPLAY_P3_TO_XYZ: Matrix3 = [
89    [608_311.0 / 1_250_200.0, 189_793.0 / 714_400.0, 198_249.0 / 1_000_160.0],
90    [35_783.0 / 156_275.0, 247_089.0 / 357_200.0, 198_249.0 / 2_500_400.0],
91    [0.0, 32_229.0 / 714_400.0, 5_220_557.0 / 5_000_800.0],
92];
93
94/// Past this chroma an Oklch color clips to the same sRGB color: the style
95/// spec's bound, which keeps the conversion finite.
96const MAX_CHROMA: f64 = 1e6;
97/// The same bound on a Display P3 component.
98const MAX_DISPLAY_P3_COMPONENT: f64 = 1e6;
99
100fn multiply(m: &Matrix3, [x, y, z]: Vector3) -> Vector3 {
101    [
102        m[0][0] * x + m[0][1] * y + m[0][2] * z,
103        m[1][0] * x + m[1][1] * y + m[1][2] * z,
104        m[2][0] * x + m[2][1] * y + m[2][2] * z,
105    ]
106}
107
108/// sRGB's (and Display P3's) transfer function, to linear light.
109fn srgb_to_linear(x: f64) -> f64 {
110    let abs = x.abs();
111    if abs <= 0.040_45 { x / 12.92 } else { ((abs + 0.055) / 1.055).powf(2.4).copysign(x) }
112}
113
114fn linear_to_srgb(x: f64) -> f64 {
115    let abs = x.abs();
116    if abs > 0.003_130_8 { (1.055 * abs.powf(1.0 / 2.4) - 0.055).copysign(x) } else { 12.92 * x }
117}
118
119fn srgb_to_oklab(rgb: Vector3) -> Vector3 {
120    let [l, m, s] = multiply(&XYZ_TO_LMS, multiply(&LINEAR_SRGB_TO_XYZ, rgb.map(srgb_to_linear)));
121    multiply(&LMS_TO_OKLAB, [l.cbrt(), m.cbrt(), s.cbrt()])
122}
123
124fn oklab_to_srgb(lab: Vector3) -> Vector3 {
125    let [l, m, s] = multiply(&OKLAB_TO_LMS, lab);
126    multiply(&XYZ_TO_LINEAR_SRGB, multiply(&LMS_TO_XYZ, [l * l * l, m * m * m, s * s * s])).map(linear_to_srgb)
127}
128
129/// Oklch with its hue in radians, a missing (NaN) hue converting as 0.
130fn oklch_to_srgb(l: f64, c: f64, h: f64) -> Vector3 {
131    let hue = if h.is_nan() { 0.0 } else { h };
132    let chroma = c.min(MAX_CHROMA);
133    oklab_to_srgb([l, chroma * hue.cos(), chroma * hue.sin()])
134}
135
136/// Oklab through its polar form, as the style spec converts it, which bounds
137/// the chroma.
138fn oklab_via_oklch_to_srgb(l: f64, a: f64, b: f64) -> Vector3 {
139    oklch_to_srgb(l, a.hypot(b), b.atan2(a))
140}
141
142fn display_p3_to_srgb(rgb: Vector3) -> Vector3 {
143    let linear = rgb.map(|c| srgb_to_linear(c.clamp(-MAX_DISPLAY_P3_COMPONENT, MAX_DISPLAY_P3_COMPONENT)));
144    multiply(&XYZ_TO_LINEAR_SRGB, multiply(&LINEAR_DISPLAY_P3_TO_XYZ, linear)).map(linear_to_srgb)
145}
146
147// CIE Lab (D50) and its polar form, HCL, as the style spec converts them
148// (https://observablehq.com/@mbostock/lab-and-rgb), with sRGB's transfer
149// function odd about 0 both ways.
150const LAB_XN: f64 = 0.964_22;
151const LAB_YN: f64 = 1.0;
152const LAB_ZN: f64 = 0.825_21;
153const LAB_T0: f64 = 4.0 / 29.0;
154const LAB_T1: f64 = 6.0 / 29.0;
155const LAB_T2: f64 = 3.0 * LAB_T1 * LAB_T1;
156const LAB_T3: f64 = LAB_T1 * LAB_T1 * LAB_T1;
157
158fn xyz_to_lab(t: f64) -> f64 {
159    if t > LAB_T3 { t.powf(1.0 / 3.0) } else { t / LAB_T2 + LAB_T0 }
160}
161
162fn lab_to_xyz(t: f64) -> f64 {
163    if t > LAB_T1 { t * t * t } else { LAB_T2 * (t - LAB_T0) }
164}
165
166/// The style spec's own encoding back to sRGB, whose linear part ends at
167/// 0.00304.
168fn xyz_to_srgb(x: f64) -> f64 {
169    let abs = x.abs();
170    if abs <= 0.003_04 { 12.92 * x } else { (1.055 * abs.powf(1.0 / 2.4) - 0.055).copysign(x) }
171}
172
173fn srgb_to_lab(rgb: Vector3) -> Vector3 {
174    let [r, g, b] = rgb.map(srgb_to_linear);
175    let y = xyz_to_lab((0.222_504_5 * r + 0.716_878_6 * g + 0.060_616_9 * b) / LAB_YN);
176    let (x, z) = if r == g && g == b {
177        (y, y)
178    } else {
179        (
180            xyz_to_lab((0.436_074_7 * r + 0.385_064_9 * g + 0.143_080_4 * b) / LAB_XN),
181            xyz_to_lab((0.013_932_2 * r + 0.097_104_5 * g + 0.714_173_3 * b) / LAB_ZN),
182        )
183    };
184    [116.0 * y - 16.0, 500.0 * (x - y), 200.0 * (y - z)]
185}
186
187fn lab_to_srgb([l, a, b]: Vector3) -> Vector3 {
188    let y = (l + 16.0) / 116.0;
189    let x = if a.is_nan() { y } else { y + a / 500.0 };
190    let z = if b.is_nan() { y } else { y - b / 200.0 };
191    let (x, y, z) = (LAB_XN * lab_to_xyz(x), LAB_YN * lab_to_xyz(y), LAB_ZN * lab_to_xyz(z));
192    [
193        xyz_to_srgb(3.133_856_1 * x - 1.616_866_7 * y - 0.490_614_6 * z),
194        xyz_to_srgb(-0.978_768_4 * x + 1.916_141_5 * y + 0.033_454 * z),
195        xyz_to_srgb(0.071_945_3 * x - 0.228_991_4 * y + 1.405_242_7 * z),
196    ]
197}
198
199/// HCL with its hue in radians, a missing (NaN) hue converting as 0.
200fn hcl_to_srgb(l: f64, c: f64, h: f64) -> Vector3 {
201    let hue = if h.is_nan() { 0.0 } else { h };
202    lab_to_srgb([l, hue.cos() * c, hue.sin() * c])
203}
204
205fn lerp(a: f64, b: f64, t: f64) -> f64 {
206    a * (1.0 - t) + b * t
207}
208
209/// How far `to` is from `from` the shorter way around, in radians.
210fn hue_difference(from: f64, to: f64) -> f64 {
211    let difference = to - from;
212    if difference > PI {
213        difference - TAU
214    } else if difference < -PI {
215        difference + TAU
216    } else {
217        difference
218    }
219}
220
221/// `[l, c, h, alpha]` in the polar form of CIE Lab, the hue in radians, NaN
222/// when it's missing. A color darker than black keeps its lightness below 0.
223fn to_hcl(color: &Color) -> [f64; 4] {
224    let [r, g, b, alpha] = color.straight_rgba().map(f64::from);
225    let [l, a, b] = srgb_to_lab([r, g, b]);
226    let c = (a * a + b * b).sqrt();
227    [l, c, if c < HCL_POWERLESS_CHROMA { f64::NAN } else { b.atan2(a) }, alpha]
228}
229
230/// The style spec's LAB interpolation: lightness, a, b and alpha, straight.
231fn interpolate_lab(from: &Color, to: &Color, t: f64) -> Color {
232    let [r1, g1, b1, alpha1] = from.straight_rgba().map(f64::from);
233    let [r2, g2, b2, alpha2] = to.straight_rgba().map(f64::from);
234    let (lab1, lab2) = (srgb_to_lab([r1, g1, b1]), srgb_to_lab([r2, g2, b2]));
235    let mix = |a: f64, b: f64| a + t * (b - a);
236    let rgb = lab_to_srgb([mix(lab1[0], lab2[0]), mix(lab1[1], lab2[1]), mix(lab1[2], lab2[2])]);
237    Color::from_straight(rgb, mix(alpha1, alpha2))
238}
239
240/// `[l, a, b, alpha]` in Oklab.
241fn to_oklab(color: &Color) -> [f64; 4] {
242    let [r, g, b, alpha] = color.straight_rgba().map(f64::from);
243    let [l, a, b] = srgb_to_oklab([r, g, b]);
244    [l, a, b, alpha]
245}
246
247/// `[l, c, h, alpha]` in Oklch, the hue in radians: NaN, with no chroma, when
248/// it's missing.
249fn to_oklch(color: &Color) -> [f64; 4] {
250    let [r, g, b, alpha] = color.straight_rgba().map(f64::from);
251    let [l, a, b] = srgb_to_oklab([r, g, b]);
252    let c = (a * a + b * b).sqrt();
253    if c <= OKLCH_POWERLESS_CHROMA { [l, 0.0, f64::NAN, alpha] } else { [l, c, b.atan2(a), alpha] }
254}
255
256// GL JS's interpolateHcl: a missing hue takes the other's, and so does the
257// chroma when the other is black or white.
258fn interpolate_hcl(from: &Color, to: &Color, t: f64) -> Color {
259    let [l1, c1, h1, alpha1] = to_hcl(from);
260    let [l2, c2, h2, alpha2] = to_hcl(to);
261    let mut chroma = lerp(c1, c2, t);
262    let hue = match (h1.is_nan(), h2.is_nan()) {
263        (false, false) => h1 + t * hue_difference(h1, h2),
264        (false, true) => {
265            if l2 == 1.0 || l2 == 0.0 {
266                chroma = c1;
267            }
268            h1
269        }
270        (true, false) => {
271            if l1 == 1.0 || l1 == 0.0 {
272                chroma = c2;
273            }
274            h2
275        }
276        (true, true) => f64::NAN,
277    };
278    let rgb = hcl_to_srgb(lerp(l1, l2, t), chroma, hue);
279    Color::from_straight(rgb, lerp(alpha1, alpha2, t))
280}
281
282// https://drafts.csswg.org/css-color-4/#interpolation: a missing hue takes the
283// other's, and lightness and chroma are premultiplied.
284fn interpolate_oklch(from: &Color, to: &Color, t: f64) -> Color {
285    let [l1, c1, h1, alpha1] = to_oklch(from);
286    let [l2, c2, h2, alpha2] = to_oklch(to);
287    let (h1, h2) = (if h1.is_nan() { h2 } else { h1 }, if h2.is_nan() { h1 } else { h2 });
288    let alpha = lerp(alpha1, alpha2, t);
289    let divisor = if alpha == 0.0 { 1.0 } else { alpha };
290    let rgb = oklch_to_srgb(
291        lerp(l1 * alpha1, l2 * alpha2, t) / divisor,
292        lerp(c1 * alpha1, c2 * alpha2, t) / divisor,
293        h1 + t * hue_difference(h1, h2),
294    );
295    Color::from_straight(rgb, alpha)
296}
297
298// https://drafts.csswg.org/css-color-4/#interpolation: lightness, a and b
299// are premultiplied, and there is no hue to fix up.
300fn interpolate_oklab(from: &Color, to: &Color, t: f64) -> Color {
301    let [l1, a1, b1, alpha1] = to_oklab(from);
302    let [l2, a2, b2, alpha2] = to_oklab(to);
303    let alpha = lerp(alpha1, alpha2, t);
304    let divisor = if alpha == 0.0 { 1.0 } else { alpha };
305    let rgb = oklab_via_oklch_to_srgb(
306        lerp(l1 * alpha1, l2 * alpha2, t) / divisor,
307        lerp(a1 * alpha1, a2 * alpha2, t) / divisor,
308        lerp(b1 * alpha1, b2 * alpha2, t) / divisor,
309    );
310    Color::from_straight(rgb, alpha)
311}
312
313/// The style spec's RGB interpolation: red, green, blue and alpha, straight.
314fn interpolate_rgb(from: &Color, to: &Color, t: f64) -> Color {
315    let from = from.straight_rgba().map(f64::from);
316    let to = to.straight_rgba().map(f64::from);
317    let [r, g, b, alpha] = from.interpolate(&to, t);
318    Color::from_straight([r, g, b], alpha)
319}
320
321impl Color {
322    #[must_use]
323    pub fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
324        debug_assert!((0.0..=1.0).contains(&r));
325        debug_assert!((0.0..=1.0).contains(&g));
326        debug_assert!((0.0..=1.0).contains(&b));
327        debug_assert!((0.0..=1.0).contains(&a));
328        Color { r, g, b, a, straight: None }
329    }
330
331    /// Internal constructor without range asserts (interpolation can
332    /// transiently leave 0..1).
333    #[must_use]
334    pub const fn new_unchecked(r: f32, g: f32, b: f32, a: f32) -> Self {
335        Color { r, g, b, a, straight: None }
336    }
337
338    /// A straight color, its channels clipped to 0..1 and premultiplied, and
339    /// kept unclipped when any is outside or it's transparent: the style
340    /// spec's `new Color(r, g, b, alpha, false)`.
341    fn from_straight(rgb: [f64; 3], alpha: f64) -> Color {
342        let a = alpha as f32;
343        let [r, g, b] = rgb.map(|c| c.clamp(0.0, 1.0) as f32);
344        let mut color = Color::new(r * a, g * a, b * a, a);
345        if a == 0.0 || rgb.iter().any(|c| !(0.0..=1.0).contains(c)) {
346            color.straight = Some(rgb.map(|c| c as f32));
347        }
348        color
349    }
350
351    /// The straight color, unclipped (the style spec's `unclippedRgb`).
352    fn straight_rgba(&self) -> [f32; 4] {
353        match self.straight {
354            Some([r, g, b]) => [r, g, b, self.a],
355            None if self.a == 0.0 => [0.0; 4],
356            None => [self.r / self.a, self.g / self.a, self.b / self.a, self.a],
357        }
358    }
359
360    #[must_use]
361    pub const fn black() -> Self {
362        Color::new_unchecked(0.0, 0.0, 0.0, 1.0)
363    }
364    #[must_use]
365    pub const fn white() -> Self {
366        Color::new_unchecked(1.0, 1.0, 1.0, 1.0)
367    }
368    #[must_use]
369    pub const fn red() -> Self {
370        Color::new_unchecked(1.0, 0.0, 0.0, 1.0)
371    }
372    #[must_use]
373    pub const fn green() -> Self {
374        Color::new_unchecked(0.0, 1.0, 0.0, 1.0)
375    }
376    #[must_use]
377    pub const fn blue() -> Self {
378        Color::new_unchecked(0.0, 0.0, 1.0, 1.0)
379    }
380
381    /// Parse a CSS color string as the style spec does, returning a
382    /// premultiplied Color. It keeps the channels' precision rather than
383    /// rounding them to 8 bits.
384    #[must_use]
385    pub fn parse(s: &str) -> Option<Color> {
386        let (rgb, alpha) = css::parse(s)?;
387        Some(Color::from_straight(rgb, alpha))
388    }
389
390    /// The straight `[r, g, b, a]` of a CSS color string, as the style spec
391    /// parses it: red, green and blue are 0..1 inside sRGB and unclipped
392    /// outside it.
393    #[must_use]
394    pub fn parse_straight(s: &str) -> Option<[f64; 4]> {
395        let ([r, g, b], alpha) = css::parse(s)?;
396        Some([r, g, b, alpha])
397    }
398
399    #[must_use]
400    pub fn interpolate(from: &Color, to: &Color, t: f64, space: ColorSpace) -> Color {
401        match space {
402            ColorSpace::Rgb => interpolate_rgb(from, to, t),
403            ColorSpace::Lab => interpolate_lab(from, to, t),
404            ColorSpace::Hcl => interpolate_hcl(from, to, t),
405            ColorSpace::Oklch => interpolate_oklch(from, to, t),
406            ColorSpace::Oklab => interpolate_oklab(from, to, t),
407        }
408    }
409
410    /// Un-premultiplied `[r*255, g*255, b*255, a]`, clipped to sRGB.
411    #[must_use]
412    pub fn to_array(&self) -> [f64; 4] {
413        if self.a == 0.0 {
414            let [r, g, b] = self.straight.unwrap_or_default().map(|c| f64::from(c.clamp(0.0, 1.0)) * 255.0);
415            [r, g, b, 0.0]
416        } else {
417            let a = f64::from(self.a);
418            let channel = |c: f32| f64::from(c) * 255.0 / a;
419            [channel(self.r), channel(self.g), channel(self.b), a]
420        }
421    }
422
423    /// `to_array` dividing in the other order, and clamped to 0..255.
424    fn exact_array(&self) -> [f64; 4] {
425        let a = f64::from(self.a);
426        let channel = |c: f32| (f64::from(c) / a * 255.0).clamp(0.0, 255.0);
427        [channel(self.r), channel(self.g), channel(self.b), a]
428    }
429
430    /// Whether the "rgba" expression of these values makes this color: the
431    /// premultiplication of `mln_style`'s `rgba` expression.
432    fn is_made_by(&self, [r, g, b, a]: [f64; 4]) -> bool {
433        let premultiplied = |c: f64| (c / 255.0 * a) as f32;
434        premultiplied(r) == self.r && premultiplied(g) == self.g && premultiplied(b) == self.b && a as f32 == self.a
435    }
436
437    #[must_use]
438    pub fn to_float_array(&self) -> [f32; 4] {
439        [self.r, self.g, self.b, self.a]
440    }
441
442    #[must_use]
443    pub fn stringify(&self) -> String {
444        // Match GL JS's Color.toString: whole channels, alpha as is.
445        let array = self.to_array();
446        let channel = |value: f64| to_string_double((value + 0.5).floor());
447        format!(
448            "rgba({},{},{},{})",
449            channel(array[0]),
450            channel(array[1]),
451            channel(array[2]),
452            to_string_double(array[3])
453        )
454    }
455
456    /// Emit as an rgba expression array for expression serialization (avoids
457    /// "Bare objects invalid" parse errors in expression round trips).
458    ///
459    /// It writes the `to_array` values when they make this color again (the
460    /// "rgba" expression premultiplies them back), and otherwise values that
461    /// do, so that a serialized layer parses back to the same colors: a tile
462    /// worker in another wasm instance gets its layers that way, and writes
463    /// their colors into its buckets.
464    #[must_use]
465    pub fn serialize(&self) -> Value {
466        let mut array = self.to_array();
467        if !self.is_made_by(array) {
468            let exact = self.exact_array();
469            if self.is_made_by(exact) {
470                array = exact;
471            }
472        }
473        Value::Array(vec![
474            Value::String("rgba".to_owned()),
475            Value::Double(array[0]),
476            Value::Double(array[1]),
477            Value::Double(array[2]),
478            Value::Double(array[3]),
479        ])
480    }
481}
482
483impl std::ops::Mul<f32> for Color {
484    type Output = Color;
485    fn mul(self, alpha: f32) -> Color {
486        debug_assert!((0.0..=1.0).contains(&alpha));
487        // The straight color, and so its unclipped channels, stay as they are.
488        Color { r: self.r * alpha, g: self.g * alpha, b: self.b * alpha, a: self.a * alpha, ..self }
489    }
490}
491
492#[cfg(test)]
493mod tests {
494    // Ports (a subset of) test/util/color.test.cpp — extend when porting the
495    // full file.
496    use approx::assert_abs_diff_eq;
497
498    use super::*;
499
500    #[test]
501    fn parse_named() {
502        assert_eq!(Color::parse("red"), Some(Color::red()));
503        assert_eq!(Color::parse("white"), Some(Color::white()));
504        assert_eq!(Color::parse("not-a-color"), None);
505    }
506
507    #[test]
508    fn parse_premultiplies() {
509        let c = Color::parse("rgba(255, 0, 0, 0.5)").unwrap();
510        assert_abs_diff_eq!(c.r, 0.5, epsilon = 1e-6);
511        assert_eq!(c.g, 0.0);
512        assert_eq!(c.b, 0.0);
513        assert_abs_diff_eq!(c.a, 0.5, epsilon = 1e-6);
514    }
515
516    #[test]
517    fn roundtrip_array() {
518        let c = Color::parse("rgba(255, 51, 0, 1)").unwrap();
519        let a = c.to_array();
520        assert_abs_diff_eq!(a[0], 255.0, epsilon = 1e-3);
521        assert_abs_diff_eq!(a[1], 51.0, epsilon = 1e-3);
522        assert_abs_diff_eq!(a[2], 0.0, epsilon = 1e-3);
523        assert_eq!(a[3], 1.0);
524    }
525
526    #[test]
527    fn interpolate_rgb_midpoint() {
528        let c = Color::interpolate(&Color::black(), &Color::white(), 0.5, ColorSpace::Rgb);
529        assert_abs_diff_eq!(c.r, 0.5, epsilon = 1e-6);
530        assert_abs_diff_eq!(c.a, 1.0, epsilon = 1e-6);
531    }
532
533    fn serialized(c: &Color) -> [f64; 4] {
534        let Value::Array(a) = c.serialize() else { panic!("not an array") };
535        let n = |v: &Value| match v {
536            Value::Double(d) => *d,
537            _ => panic!("not a number"),
538        };
539        [n(&a[1]), n(&a[2]), n(&a[3]), n(&a[4])]
540    }
541
542    /// What `serialize` writes makes the same color again, premultiplied as
543    /// the "rgba" expression does; and it is `to_array` when that does.
544    #[test]
545    fn serialize_makes_the_same_color() {
546        for css in ["red", "rgba(255, 0, 0, 0.5)", "rgba(170, 255, 0, 0.6)", "rgba(1, 2, 3, 0.678)", "#123456"] {
547            let c = Color::parse(css).unwrap();
548            let [r, g, b, a] = serialized(&c);
549            let premultiplied = |v: f64| (v / 255.0 * a) as f32;
550            assert_eq!((premultiplied(r), premultiplied(g), premultiplied(b), a as f32), (c.r, c.g, c.b, c.a), "{css}");
551        }
552        assert_eq!(serialized(&Color::parse("rgba(255, 0, 0, 0.5)").unwrap()), [255.0, 0.0, 0.0, 0.5]);
553        assert_eq!(serialized(&Color::parse("rgba(1, 2, 3, 0.678)").unwrap())[3], f64::from(0.678f32));
554    }
555}