diff --git a/src/color.rs b/src/color.rs index be52885d..31debed9 100644 --- a/src/color.rs +++ b/src/color.rs @@ -314,9 +314,13 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result _ => return Err(()) }; - let red: f32; - let green: f32; - let blue: f32; + fn clamp(val: f32) -> f32 { + val.max(0.).min(1.) + } + + let mut red: f32; + let mut green: f32; + let mut blue: f32; if is_rgb { // Either integers or percentages, but all the same type. match try!(arguments.next()) { @@ -336,13 +340,23 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result } _ => return Err(()) }; + // The spec says to clamp to the device gamut which may be wider than 0% ... 100%, + // but moz2d doesn’t seem to have any support for this, so let’s not bother. + // https://drafts.csswg.org/css-color/#rgb-functions + // https://github.com/servo/rust-cssparser/issues/76 + red = clamp(red); + green = clamp(green); + blue = clamp(blue); } else { let hue = try!(arguments.expect_number()) / 360.; let hue = hue - hue.floor(); + // Saturation and lightness are clamped to 0% ... 100% + // regardless of device gamut: + // https://drafts.csswg.org/css-color/#the-hsl-notation try!(arguments.expect_comma()); - let saturation = (try!(arguments.expect_percentage())).max(0.).min(1.); + let saturation = clamp(try!(arguments.expect_percentage())); try!(arguments.expect_comma()); - let lightness = (try!(arguments.expect_percentage())).max(0.).min(1.); + let lightness = clamp(try!(arguments.expect_percentage())); // https://drafts.csswg.org/css-color/#hsl-color fn hue_to_rgb(m1: f32, m2: f32, mut h: f32) -> f32 { @@ -364,7 +378,7 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result let alpha = if has_alpha { try!(arguments.expect_comma()); - (try!(arguments.expect_number())).max(0.).min(1.) + clamp(try!(arguments.expect_number())) } else { 1. }; diff --git a/src/css-parsing-tests/color3.json b/src/css-parsing-tests/color3.json index bbc05a4e..52ec27b6 100644 --- a/src/css-parsing-tests/color3.json +++ b/src/css-parsing-tests/color3.json @@ -46,7 +46,7 @@ "rgb(0,51,255)", [0, 0.2, 1, 1], "rgb(0\t, 51 ,255)", [0, 0.2, 1, 1], "rgb(/* R */0, /* G */51, /* B */255)", [0, 0.2, 1, 1], -"rgb(-51, 306, 0)", [-0.2, 1.2, 0, 1], +"rgb(-51, 306, 0)", [0, 1, 0, 1], "rgb(42%, 3%, 50%)", [0.42, 0.03, 0.5, 1], "RGB(100%, 100%, 100%)", [1, 1, 1, 1], @@ -55,7 +55,7 @@ "rgb(10%,20%,30%)", [0.1, 0.2, 0.3, 1], "rgb(10%\t, 20% ,30%)", [0.1, 0.2, 0.3, 1], "rgb(/* R */ 10%, /* G */ 20%, /* B */ 30%)", [0.1, 0.2, 0.3, 1], -"rgb(-12%, 110%, 1400%)", [-0.12, 1.1, 14, 1], +"rgb(-12%, 110%, 1400%)", [0, 1, 1, 1], "rgb(10%, 50%, 0)", null, "rgb(255, 50%, 0%)", null,