From 8f558a908faefe1430a3f6651d3f76f1f56565e1 Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Sun, 18 Oct 2020 16:05:53 +0100 Subject: [PATCH] better error handling for Sprite --- src/sprite.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/sprite.rs b/src/sprite.rs index a14702a..af1b0e9 100644 --- a/src/sprite.rs +++ b/src/sprite.rs @@ -1,6 +1,8 @@ use crate::{optional_data_line, AnimationFrames, Image, Position}; use crate::image::animation_frames_from_str; +use std::fmt; + #[derive(Clone, Debug, Eq, PartialEq)] pub struct Sprite { pub id: String, @@ -51,14 +53,14 @@ impl Sprite { } } -#[derive(Debug)] -pub struct SpriteMissingRoomPosition; -// todo "malformed sprite ID" or something - impl Sprite { - pub(crate) fn from(string: String) -> Result { + pub fn from(string: String) -> Result { let mut lines: Vec<&str> = string.lines().collect(); + if lines.is_empty() || !lines[0].starts_with("SPR ") { + return Err(crate::Error::Sprite); + } + let id = lines[0].replace("SPR ", ""); let mut name = None; let mut dialogue_id: Option = None; @@ -80,13 +82,13 @@ impl Sprite { room_id = Some(room_position[0].to_string()); if room_position.len() < 2 { - return Err(SpriteMissingRoomPosition); + return Err(crate::Error::Sprite); } if let Ok(pos) = Position::from_str(room_position[1]) { position = Some(pos); } else { - return Err(SpriteMissingRoomPosition); + return Err(crate::Error::Sprite); } } else if last_line.starts_with("COL") { colour_id = Some(last_line.replace("COL ", "").parse().unwrap()); @@ -117,9 +119,10 @@ impl Sprite { } } -impl ToString for Sprite { - fn to_string(&self) -> String { - format!( +impl fmt::Display for Sprite { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, "SPR {}\n{}{}{}{}{}{}", self.id, self.animation_frames.to_string(),