From b50bde1f6489ecf90600e56d14e79f302736f9b6 Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Sat, 11 Dec 2021 17:44:17 +0000 Subject: [PATCH] better error handling for image --- src/error.rs | 10 +++++++++- src/image.rs | 18 ++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/error.rs b/src/error.rs index 1adaa8e..4637b08 100644 --- a/src/error.rs +++ b/src/error.rs @@ -21,6 +21,12 @@ impl fmt::Display for NotFound { } } +#[derive(Debug)] +pub enum ImageError { + MalformedPixel, + WrongSize, +} + #[derive(Debug)] pub enum Error { Colour, @@ -31,7 +37,9 @@ pub enum Error { Game { missing: NotFound, }, - Image, + Image { + err: ImageError, + }, Item, Palette, Position, diff --git a/src/image.rs b/src/image.rs index d202f37..4585842 100644 --- a/src/image.rs +++ b/src/image.rs @@ -1,4 +1,5 @@ use std::fmt; +use crate::error::ImageError; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Image { @@ -56,7 +57,7 @@ impl Image { let mut warnings = Vec::new(); if str.contains("NaN") { - warnings.push(crate::Error::Image); + warnings.push(crate::Error::Image { err: ImageError::MalformedPixel }); } let string = str.trim().replace("NaN", "0"); @@ -68,15 +69,24 @@ impl Image { for line in lines { let line = &line[..dimension]; for char in line.chars().into_iter() { - // todo push warning on integers other than 0/1 - pixels.push(match char {'1' => 1, _ => 0}); + pixels.push(match char { + '0' => 0, + '1' => 1, + _ => { + warnings.push( + crate::Error::Image { err: ImageError::MalformedPixel } + ); + 0 + } + }); } } + // 8×8 (normal) or 16×16 (Bitsy HD) if [64, 256].contains(&pixels.len()) { Ok((Image { pixels }, warnings)) } else { - Err(crate::Error::Image) + Err(crate::Error::Image { err: ImageError::WrongSize }) } } }