use crate::{AnimationFrames, Image, mock, from_base36, ToBase36, optional_data_line}; #[derive(Debug, Eq, PartialEq)] pub struct Item { pub id: u64, pub animation_frames: Vec, pub name: Option, pub dialogue_id: Option, pub colour_id: Option, } impl Item { fn name_line(&self) -> String { optional_data_line("NAME", self.name.as_ref()) } fn dialogue_line(&self) -> String { optional_data_line("DLG", self.dialogue_id.as_ref()) } fn colour_line(&self) -> String { optional_data_line("COL", self.colour_id.as_ref()) } } impl From for Item { fn from(string: String) -> Item { let mut lines: Vec<&str> = string.lines().collect(); let id = from_base36(&lines[0].replace("ITM ", "")); let mut name = None; let mut dialogue_id = None; let mut colour_id: Option = None; loop { let last_line = lines.pop().unwrap(); if last_line.starts_with("NAME") { name = Some(last_line.replace("NAME ", "").to_string()); } else if last_line.starts_with("DLG") { dialogue_id = Some(last_line.replace("DLG ", "").to_string()); } else if last_line.starts_with("COL") { colour_id = Some(last_line.replace("COL ", "").parse().unwrap()); } else { lines.push(last_line); break; } } // todo dedupe let animation_frames = lines[1..].join(""); let animation_frames: Vec<&str> = animation_frames.split(">").collect(); let animation_frames: Vec = animation_frames.iter().map(|&frame| { Image::from(frame.to_string()) }).collect(); Item { id, name, animation_frames, dialogue_id, colour_id } } } impl ToString for Item { #[inline] fn to_string(&self) -> String { format!( "ITM {}\n{}{}{}{}", self.id.to_base36(), self.animation_frames.to_string(), self.name_line(), self.dialogue_line(), self.colour_line(), ) } } #[test] fn test_item_from_string() { let output = Item::from(include_str!("test-resources/item").to_string()); let expected = mock::item(); assert_eq!(output, expected); } #[test] fn test_item_to_string() { let output = mock::item().to_string(); let expected = include_str!("test-resources/item").to_string(); assert_eq!(output, expected); }