From a58b0ae87765a897b91609fcccab5b237106c204 Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Sun, 12 Apr 2020 10:15:51 +0100 Subject: [PATCH] implement ToString for Palette --- src/main.rs | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/main.rs b/src/main.rs index 4b11c55..492bce1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -666,24 +666,28 @@ fn test_palette_from_string_no_name() { assert_eq!(output, expected); } -fn palette_to_string(palette: Palette) -> String { - let name = if palette.name.is_some() { - format!("NAME {}\n", palette.name.unwrap()) - } else { - "".to_string() - }; +impl ToString for Palette { + #[inline] + fn to_string(&self) -> String { + let name = if self.name.as_ref().is_some() { + format!("NAME {}\n", self.name.as_ref().unwrap()) + } else { + "".to_string() + }; - let colours: Vec = palette.colours.into_iter().map(|colour| - colour.to_string() - ).collect(); - let colours = colours.join("\n"); + let mut colours = String::new(); + for colour in &self.colours { + colours.push_str(&format!("{}\n", colour.to_string())); + } + colours.pop(); - format!("PAL {}\n{}{}", palette.id, name, colours) + format!("PAL {}\n{}{}", self.id, name, colours) + } } #[test] fn test_palette_to_string() { - let output = palette_to_string(Palette { + let output = Palette { id: "g".to_string(), name: Some("moss".to_string()), colours: vec![ @@ -691,7 +695,7 @@ fn test_palette_to_string() { Colour {red: 255, green: 254, blue: 253}, Colour {red: 126, green: 127, blue: 128}, ] - }); + }.to_string(); let expected = "PAL g\nNAME moss\n1,2,3\n255,254,253\n126,127,128".to_string(); assert_eq!(output, expected); } @@ -1258,7 +1262,7 @@ fn game_to_string(game: Game) -> String { // todo refactor for palette in game.palettes { - segments.push(palette_to_string(palette)); + segments.push(palette.to_string()); } for room in game.rooms {