#[derive(Debug, Eq, PartialEq)] pub struct Image { pub pixels: Vec, // 64 for SD, 256 for HD } impl From for Image { #[inline] fn from(string: String) -> Image { print!("image: \n{}", string); let string = string.replace("NaN", "0"); let string = string.trim(); let lines: Vec<&str> = string.lines().collect(); let dimension = lines.len(); let mut pixels: Vec = Vec::new(); for line in lines { let line = &line[..dimension]; println!("line: {}", line); for char in line.chars().into_iter() { println!("Char: {} value: {}", char, match char {'1' => 1, _ => 0}); pixels.push(match char {'1' => 1, _ => 0}); } } Image { pixels } } } impl ToString for Image { #[inline] fn to_string(&self) -> String { let mut string = String::new(); let sqrt = (self.pixels.len() as f64).sqrt() as usize; // 8 for SD, 16 for HD for line in self.pixels.chunks(sqrt) { for pixel in line { string.push_str(&format!("{}", *pixel)); } string.push('\n'); } string.pop(); // remove trailing newline string } } #[cfg(test)] mod test { use crate::image::Image; #[test] fn test_image_from_string() { let output = Image::from(include_str!("test-resources/image").to_string()); let expected = Image { pixels: vec![ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], }; assert_eq!(output, expected); } #[test] fn test_image_to_string() { let output = crate::mock::image::chequers_1().to_string(); let expected = include_str!("test-resources/image-chequers-1").to_string(); assert_eq!(output, expected); } }