to_string() for Colour

This commit is contained in:
Max Bradbury 2021-05-16 11:45:53 +01:00
parent eb8fd556e4
commit b36a1a7d24
1 changed files with 15 additions and 0 deletions

View File

@ -1,3 +1,5 @@
use std::fmt;
use serde_derive::{Serialize, Deserialize};
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
@ -24,6 +26,12 @@ impl From<Vec<u8>> for Colour {
}
}
impl fmt::Display for Colour {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", hex::encode([self.red, self.green, self.blue]))
}
}
impl Into<Vec<u8>> for Colour {
fn into(self) -> Vec<u8> {
vec![self.red, self.green, self.blue]
@ -43,6 +51,13 @@ mod test {
assert_eq!(Colour::from("0xa0b0c0"), Colour { red: 160, green: 176, blue: 192 });
}
#[test]
fn test_colour_to_hex() {
assert_eq!(Colour { red: 255, green: 255, blue: 255 }.to_string(), "#ffffff");
assert_eq!(Colour { red: 0, green: 0, blue: 0 }.to_string(), "#000000");
assert_eq!(Colour { red: 0, green: 128, blue: 64 }.to_string(), "#008040");
}
#[test]
fn test_colour_from_intermediate() {
let output = Colour::from(vec![64, 128, 192]);