Skip to content

Implement color value serialization. #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 1, 2014
Merged
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
16 changes: 15 additions & 1 deletion src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ pub struct RGBA {

impl fmt::Show for RGBA {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(r={} g={} b={} a={})", self.red, self.green, self.blue, self.alpha)
if self.alpha == 1f32 {
write!(f, "rgb({}, {}, {})", (self.red * 255.).round(), (self.green * 255.).round(),
(self.blue * 255.).round())
} else {
write!(f, "rgba({}, {}, {}, {})", (self.red * 255.).round(), (self.green * 255.).round(),
(self.blue * 255.).round(), self.alpha)
}
}
}

Expand All @@ -30,6 +36,14 @@ pub enum Color {
RGBAColor(RGBA),
}

impl fmt::Show for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&CurrentColor => write!(f, "currentColor"),
&RGBAColor(c) => write!(f, "{}", c),
}
}
}

/// Return `Err(())` on invalid or unsupported value (not a color).
impl Color {
Expand Down
21 changes: 21 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,27 @@ fn serializer() {
}


#[test]
fn serialize_current_color() {
let c = CurrentColor;
assert!(format!("{}", c).as_slice() == "currentColor");
}


#[test]
fn serialize_rgb_full_alpha() {
let c = RGBAColor(RGBA { red: 1.0, green: 0.9, blue: 0.8, alpha: 1.0 });
assert!(format!("{}", c).as_slice() == "rgb(255, 230, 204)");
}


#[test]
fn serialize_rgba() {
let c = RGBAColor(RGBA { red: 0.1, green: 0.2, blue: 0.3, alpha: 0.5 });
assert!(format!("{}", c).as_slice() == "rgba(26, 51, 77, 0.5)");
}


impl ToJson for Result<Rule, SyntaxError> {
fn to_json(&self) -> json::Json {
match *self {
Expand Down