2020-04-12 11:48:07 +00:00
|
|
|
#[derive(Debug, Eq, PartialEq)]
|
|
|
|
pub struct Image {
|
2020-04-12 16:13:08 +00:00
|
|
|
pub pixels: Vec<u32>, // 64 for SD, 256 for HD
|
2020-04-12 11:48:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl From<String> for Image {
|
|
|
|
#[inline]
|
|
|
|
fn from(string: String) -> Image {
|
|
|
|
let string = string.replace("\n", "");
|
2020-04-28 17:12:56 +00:00
|
|
|
let string = string.replace("NaN", "0");
|
2020-04-12 11:48:07 +00:00
|
|
|
let pixels: Vec<&str> = string.split("").collect();
|
|
|
|
// the above seems to add an extra "" at the start and end of the vec, so strip them below
|
|
|
|
let pixels = &pixels[1..(pixels.len() - 1)];
|
2020-04-18 15:58:30 +00:00
|
|
|
let pixels: Vec<u32> = pixels
|
|
|
|
.iter()
|
2020-04-25 13:18:09 +00:00
|
|
|
.map(|&pixel|
|
|
|
|
pixel.parse::<u32>().expect(&format!("Bad pixel in image: {}\n", pixel))
|
|
|
|
)
|
2020-04-18 15:58:30 +00:00
|
|
|
.collect();
|
2020-04-12 11:48:07 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-19 07:13:55 +00:00
|
|
|
#[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,
|
|
|
|
],
|
|
|
|
};
|
2020-04-12 11:48:07 +00:00
|
|
|
|
2020-04-19 07:13:55 +00:00
|
|
|
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);
|
|
|
|
}
|
2020-04-12 11:48:07 +00:00
|
|
|
}
|