1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use crate::mock;

#[derive(Debug, Eq, PartialEq)]
pub struct Image {
    pub(crate) pixels: Vec<u8>, // 64 for SD, 256 for HD
}

impl From<String> for Image {
    #[inline]
    fn from(string: String) -> Image {
        let string = string.replace("\n", "");
        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)];
        let pixels: Vec<u8> = pixels.iter().map(|&pixel| {
            pixel.parse::<u8>().unwrap()
        }).collect();

        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
    }
}

#[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 = mock::image::chequers_1().to_string();
    let expected = include_str!("../test/resources/image-chequers-1").to_string();
    assert_eq!(output, expected);
}