Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions color/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,13 @@ impl ToCss for ModernComponent<'_> {

// Guaratees hue in [0..360)
fn normalize_hue(hue: f32) -> f32 {
// An infinite hue normalizes to 0 degrees:
// <https://drafts.csswg.org/css-color-4/#hue-syntax>
// NaN is censored to 0:
// <https://drafts.csswg.org/css-values-4/#calc-ieee>
if !hue.is_finite() {
return 0.0;
}
// <https://drafts.csswg.org/css-values/#angles>
// Subtract an integer before rounding, to avoid some rounding errors:
hue - 360.0 * (hue / 360.0).floor()
Expand Down
46 changes: 46 additions & 0 deletions color/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,49 @@ fn serialize_modern_components() {
"calc(NaN)".to_string()
);
}

fn parse_and_serialize(css: &str) -> String {
Color::parse(&mut Parser::new(css)).unwrap().to_css_string()
}

#[test]
fn normalize_non_finite_hue() {
// <https://drafts.csswg.org/css-color-4/#hue-syntax>: an infinite hue
// normalizes to 0 degrees. 1e40 does not fit in an f32, so it parses
// as an infinity.
for (input, expected) in [
("hsl(1e40 50% 50%)", "hsl(0 50% 50%)"),
("hsl(-1e40 50% 50%)", "hsl(0 50% 50%)"),
("hsl(1e40deg 50% 50%)", "hsl(0 50% 50%)"),
("hsl(1e38turn 50% 50%)", "hsl(0 50% 50%)"),
("hwb(1e40 0% 0%)", "hwb(0 0% 0%)"),
("hwb(-1e40 0% 0%)", "hwb(0 0% 0%)"),
("lch(50% 30 1e40)", "lch(50% 30 0)"),
("oklch(50% 0.1 -1e40)", "oklch(50% 0.1 0)"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I know, the same issue exists in Firefox as well. So it would be great if you could submit a WPT test—that way, all browsers would benefit.

] {
assert_eq!(
parse_and_serialize(input),
parse_and_serialize(expected),
"{input}"
);
}
assert_eq!(parse_and_serialize("hwb(1e40 0% 0%)"), "rgb(255, 0, 0)");
assert_eq!(parse_and_serialize("lch(50% 30 1e40)"), "lch(50 30 0)");
}

#[test]
fn normalize_finite_hue() {
for (input, expected) in [
("hsl(480 50% 50%)", "hsl(120 50% 50%)"),
("hsl(-240 50% 50%)", "hsl(120 50% 50%)"),
("hsl(360 50% 50%)", "hsl(0 50% 50%)"),
("hwb(-540 10% 10%)", "hwb(180 10% 10%)"),
("lch(50% 30 400)", "lch(50% 30 40)"),
] {
assert_eq!(
parse_and_serialize(input),
parse_and_serialize(expected),
"{input}"
);
}
}