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;
|
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 string = str.trim().replace("NaN", "0");
|
||||||
|
|
||||||
let lines: Vec<&str> = string.lines().collect();
|
let lines: Vec<&str> = string.lines().collect();
|
||||||
let dimension = lines.len();
|
let dimension = lines.len();
|
||||||
let mut pixels: Vec<u8> = Vec::new();
|
let mut pixels: Vec<u8> = Vec::new();
|
||||||
|
@ -61,11 +68,16 @@ 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 {'1' => 1, _ => 0});
|
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('>')
|
.split('>')
|
||||||
.collect::<Vec<&str>>()
|
.collect::<Vec<&str>>()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&frame| Image::from_str(frame).unwrap())
|
.map(|&frame| Image::from_str(frame).unwrap().0)
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -104,7 +116,7 @@ mod test {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn image_from_string() {
|
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 {
|
let expected = Image {
|
||||||
pixels: vec![
|
pixels: vec![
|
||||||
|
@ -144,7 +156,7 @@ mod test {
|
||||||
/// check that these extraneous pixels are stripped out
|
/// check that these extraneous pixels are stripped out
|
||||||
#[test]
|
#[test]
|
||||||
fn image_out_of_bounds() {
|
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 {
|
let expected = Image {
|
||||||
pixels: vec![
|
pixels: vec![
|
||||||
|
|
Loading…
Reference in New Issue