Refactor how color repr is created

This commit is contained in:
ConnorSkees 2020-02-09 10:56:45 -05:00
parent 2b3d8fcce7
commit e282220f8c

View File

@ -62,13 +62,7 @@ impl Color {
.to_integer() .to_integer()
.to_u16() .to_u16()
.unwrap(); .unwrap();
let repr = if alpha < Number::from(1) { let repr = repr(val, val, val, &alpha);
format!("rgba({}, {}, {}, {})", val, val, val, alpha)
} else if let Ok(c) = ColorName::try_from([val, val, val]) {
format!("{}", c)
} else {
format!("#{:0>2x}{:0>2x}{:0>2x}", val, val, val)
};
return Color { return Color {
red: val, red: val,
green: val, green: val,
@ -128,13 +122,7 @@ impl Color {
channel!(green, temporary_g, temporary_1, temporary_2); channel!(green, temporary_g, temporary_1, temporary_2);
channel!(blue, temporary_b, temporary_1, temporary_2); channel!(blue, temporary_b, temporary_1, temporary_2);
let repr = if alpha < Number::from(1) { let repr = repr(red, green, blue, &alpha);
format!("rgba({}, {}, {}, {})", red, green, blue, alpha)
} else if let Ok(c) = ColorName::try_from([red, green, blue]) {
format!("{}", c)
} else {
format!("#{:0>2x}{:0>2x}{:0>2x}", red, green, blue)
};
Color { Color {
red, red,
green, green,
@ -161,13 +149,7 @@ impl Color {
clamp!(green); clamp!(green);
clamp!(blue); clamp!(blue);
let repr = if alpha < Number::from(1) { let repr = repr(red, green, blue, &alpha);
format!("rgba({}, {}, {}, {})", red, green, blue, alpha)
} else if let Ok(c) = ColorName::try_from([red, green, blue]) {
format!("{}", c)
} else {
format!("#{:0>2x}{:0>2x}{:0>2x}", red, green, blue)
};
Color { Color {
red, red,
green, green,
@ -178,6 +160,17 @@ impl Color {
} }
} }
/// Get the proper representation from RGBA values
fn repr(red: u16, green: u16, blue: u16, alpha: &Number) -> String {
if alpha < &Number::from(1) {
format!("rgba({}, {}, {}, {})", red, green, blue, alpha)
} else if let Ok(c) = ColorName::try_from([red, green, blue]) {
format!("{}", c)
} else {
format!("#{:0>2x}{:0>2x}{:0>2x}", red, green, blue)
}
}
impl Display for Color { impl Display for Color {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.repr) write!(f, "{}", self.repr)