diff --git a/src/color.rs b/src/color.rs index be52885d..e2bec5e2 100644 --- a/src/color.rs +++ b/src/color.rs @@ -314,6 +314,10 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result _ => return Err(()) }; + fn clamp(val: f32) -> f32 { + val.max(0.).min(1.) + } + let red: f32; let green: f32; let blue: f32; @@ -321,18 +325,19 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result // Either integers or percentages, but all the same type. match try!(arguments.next()) { Token::Number(ref v) if v.int_value.is_some() => { - red = v.value / 255.; + + red = clamp(v.value / 255.); try!(arguments.expect_comma()); - green = try!(arguments.expect_integer()) as f32 / 255.; + green = clamp(try!(arguments.expect_integer()) as f32 / 255.); try!(arguments.expect_comma()); - blue = try!(arguments.expect_integer()) as f32 / 255.; + blue = clamp(try!(arguments.expect_integer()) as f32 / 255.); } Token::Percentage(ref v) => { - red = v.unit_value; + red = clamp(v.unit_value); try!(arguments.expect_comma()); - green = try!(arguments.expect_percentage()); + green = clamp(try!(arguments.expect_percentage())); try!(arguments.expect_comma()); - blue = try!(arguments.expect_percentage()); + blue = clamp(try!(arguments.expect_percentage())); } _ => return Err(()) }; @@ -340,9 +345,9 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result let hue = try!(arguments.expect_number()) / 360.; let hue = hue - hue.floor(); 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 +369,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,