From b36a1a7d24b329837a411cf3a06fab35584e809e Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Sun, 16 May 2021 11:45:53 +0100 Subject: [PATCH] to_string() for Colour --- src/colour.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/colour.rs b/src/colour.rs index a045785..58a27f4 100644 --- a/src/colour.rs +++ b/src/colour.rs @@ -1,3 +1,5 @@ +use std::fmt; + use serde_derive::{Serialize, Deserialize}; #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] @@ -24,6 +26,12 @@ impl From> 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> for Colour { fn into(self) -> Vec { 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]);