better error handling for Sprite

This commit is contained in:
Max Bradbury 2020-10-18 16:05:53 +01:00
parent fb290f07f4
commit 8f558a908f
1 changed files with 13 additions and 10 deletions

View File

@ -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<Sprite, SpriteMissingRoomPosition> {
pub fn from(string: String) -> Result<Sprite, crate::Error> {
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<String> = 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(),