error handling for Image
This commit is contained in:
parent
0dcddb9d8e
commit
68ecc64c7b
22
src/image.rs
22
src/image.rs
|
@ -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![
|
||||
|
|
Loading…
Reference in New Issue