error handling for Image

This commit is contained in:
Max Bradbury 2020-10-18 15:24:48 +01:00
parent 0dcddb9d8e
commit 68ecc64c7b
1 changed files with 17 additions and 5 deletions

View File

@ -52,8 +52,15 @@ impl Image {
self.pixels = pixels;
}
fn from_str(str: &str) -> Result<Image, crate::Error> {
fn from_str(str: &str) -> Result<(Image, Vec<crate::Error>), crate::Error> {
let mut warnings = Vec::new();
if str.contains("NaN") {
warnings.push(crate::Error::Image);
}
let string = str.trim().replace("NaN", "0");
let lines: Vec<&str> = string.lines().collect();
let dimension = lines.len();
let mut pixels: Vec<u8> = Vec::new();
@ -61,11 +68,16 @@ 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});
}
}
Ok(Image { pixels })
if [64, 256].contains(&pixels.len()) {
Ok((Image { pixels }, warnings))
} else {
Err(crate::Error::Image)
}
}
}
@ -93,7 +105,7 @@ pub fn animation_frames_from_str(str: &str) -> Vec<Image> {
.split('>')
.collect::<Vec<&str>>()
.iter()
.map(|&frame| Image::from_str(frame).unwrap())
.map(|&frame| Image::from_str(frame).unwrap().0)
.collect()
}
@ -104,7 +116,7 @@ mod test {
#[test]
fn image_from_string() {
let output = Image::from_str(include_str!("test-resources/image")).unwrap();
let (output, _) = Image::from_str(include_str!("test-resources/image")).unwrap();
let expected = Image {
pixels: vec![
@ -144,7 +156,7 @@ mod test {
/// check that these extraneous pixels are stripped out
#[test]
fn image_out_of_bounds() {
let output = Image::from_str(include_str!("test-resources/image-oob")).unwrap();
let (output, _) = Image::from_str(include_str!("test-resources/image-oob")).unwrap();
let expected = Image {
pixels: vec![