Skip to content

Commit 173ef5f

Browse files
committed
color: Serialize floating point alpha two two decimal positions if it roundtrips instead of three.
1 parent 35ea558 commit 173ef5f

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/color.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,17 @@ impl ToCss for RGBA {
9696
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
9797
where W: fmt::Write,
9898
{
99+
// Try first with two decimal places, then with three.
100+
let mut rounded_alpha = (self.alpha_f32() * 100.).round() / 100.;
101+
if clamp_f32(rounded_alpha) != self.alpha {
102+
rounded_alpha = (self.alpha_f32() * 1000.).round() / 1000.;
103+
}
104+
99105
if self.alpha == 255 {
100106
write!(dest, "rgb({}, {}, {})", self.red, self.green, self.blue)
101107
} else {
102-
write!(dest, "rgba({}, {}, {}, {:.3})",
103-
self.red, self.green, self.blue, self.alpha_f32())
108+
write!(dest, "rgba({}, {}, {}, {})",
109+
self.red, self.green, self.blue, rounded_alpha)
104110
}
105111
}
106112
}

src/tests.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ fn assert_json_eq(results: json::Json, mut expected: json::Json, message: String
100100
}
101101
}
102102

103-
104103
fn run_raw_json_tests<F: Fn(Json, Json) -> ()>(json_data: &str, run: F) {
105104
let items = match Json::from_str(json_data) {
106105
Ok(Json::Array(items)) => items,
@@ -380,27 +379,30 @@ fn serializer(preserve_comments: bool) {
380379
});
381380
}
382381

383-
384382
#[test]
385383
fn serialize_current_color() {
386384
let c = Color::CurrentColor;
387385
assert!(c.to_css_string() == "currentColor");
388386
}
389387

390-
391388
#[test]
392389
fn serialize_rgb_full_alpha() {
393390
let c = Color::RGBA(RGBA::new(255, 230, 204, 255));
394391
assert_eq!(c.to_css_string(), "rgb(255, 230, 204)");
395392
}
396393

397-
398394
#[test]
399395
fn serialize_rgba() {
400396
let c = Color::RGBA(RGBA::new(26, 51, 77, 32));
401397
assert_eq!(c.to_css_string(), "rgba(26, 51, 77, 0.125)");
402398
}
403399

400+
#[test]
401+
fn serialize_rgba_two_digit_float_if_roundtrips() {
402+
let c = Color::RGBA(RGBA::from_floats(0., 0., 0., 0.5));
403+
assert_eq!(c.to_css_string(), "rgba(0, 0, 0, 0.5)");
404+
}
405+
404406
#[test]
405407
fn line_numbers() {
406408
let mut input = Parser::new("foo bar\nbaz\r\n\n\"a\\\r\nb\"");

0 commit comments

Comments
 (0)