From 1221df26342158b244c2c4108ffb2d22dff8227e Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Sun, 12 Apr 2020 10:06:08 +0100 Subject: [PATCH] implement ToString for colour; test for palette to string --- src/main.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2791b2d..4b11c55 100644 --- a/src/main.rs +++ b/src/main.rs @@ -594,14 +594,17 @@ fn test_colour_from_string() { ); } -fn colour_to_string(colour: Colour) -> String { - format!("{},{},{}", colour.red, colour.green, colour.blue) +impl ToString for Colour { + #[inline] + fn to_string(&self) -> String { + format!("{},{},{}", self.red, self.green, self.blue) + } } #[test] fn test_colour_to_string() { assert_eq!( - colour_to_string(Colour { red: 22, green: 33, blue: 44 }), + Colour { red: 22, green: 33, blue: 44 }.to_string(), "22,33,44".to_string() ); } @@ -670,14 +673,29 @@ fn palette_to_string(palette: Palette) -> String { "".to_string() }; - let colours: Vec = palette.colours.into_iter().map(|colour| { - colour_to_string(colour) - }).collect(); + let colours: Vec = palette.colours.into_iter().map(|colour| + colour.to_string() + ).collect(); let colours = colours.join("\n"); format!("PAL {}\n{}{}", palette.id, name, colours) } +#[test] +fn test_palette_to_string() { + let output = palette_to_string(Palette { + id: "g".to_string(), + name: Some("moss".to_string()), + colours: vec![ + Colour {red: 1, green: 2, blue: 3 }, + Colour {red: 255, green: 254, blue: 253}, + Colour {red: 126, green: 127, blue: 128}, + ] + }); + let expected = "PAL g\nNAME moss\n1,2,3\n255,254,253\n126,127,128".to_string(); + assert_eq!(output, expected); +} + fn position_from_string(string: String) -> Position { // e.g. "2,5" let xy: Vec<&str> = string.split(',').collect();