better error handling for image

This commit is contained in:
Max Bradbury 2021-12-11 17:44:17 +00:00
parent 4182079a73
commit b50bde1f64
2 changed files with 23 additions and 5 deletions

View File

@ -21,6 +21,12 @@ impl fmt::Display for NotFound {
} }
} }
#[derive(Debug)]
pub enum ImageError {
MalformedPixel,
WrongSize,
}
#[derive(Debug)] #[derive(Debug)]
pub enum Error { pub enum Error {
Colour, Colour,
@ -31,7 +37,9 @@ pub enum Error {
Game { Game {
missing: NotFound, missing: NotFound,
}, },
Image, Image {
err: ImageError,
},
Item, Item,
Palette, Palette,
Position, Position,

View File

@ -1,4 +1,5 @@
use std::fmt; use std::fmt;
use crate::error::ImageError;
#[derive(Clone, Debug, Eq, PartialEq)] #[derive(Clone, Debug, Eq, PartialEq)]
pub struct Image { pub struct Image {
@ -56,7 +57,7 @@ impl Image {
let mut warnings = Vec::new(); let mut warnings = Vec::new();
if str.contains("NaN") { if str.contains("NaN") {
warnings.push(crate::Error::Image); warnings.push(crate::Error::Image { err: ImageError::MalformedPixel });
} }
let string = str.trim().replace("NaN", "0"); let string = str.trim().replace("NaN", "0");
@ -68,15 +69,24 @@ impl Image {
for line in lines { for line in lines {
let line = &line[..dimension]; let line = &line[..dimension];
for char in line.chars().into_iter() { for char in line.chars().into_iter() {
// todo push warning on integers other than 0/1 pixels.push(match char {
pixels.push(match char {'1' => 1, _ => 0}); '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()) { if [64, 256].contains(&pixels.len()) {
Ok((Image { pixels }, warnings)) Ok((Image { pixels }, warnings))
} else { } else {
Err(crate::Error::Image) Err(crate::Error::Image { err: ImageError::WrongSize })
} }
} }
} }