qrsimple_cli/
array.rs

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
use conv::{ConvUtil, RoundToNearest};
use qrcode::{Color, QrCode};

use crate::error::MyResult;

const FULL_BLOCK: char = '\u{2588}';
const UPPER_BLOCK: char = '\u{2580}';
const LOWER_BLOCK: char = '\u{2584}';

pub struct Array {
    colors: Vec<Color>,
    size: usize,
}

impl Array {
    pub fn new(code: QrCode) -> MyResult<Array> {
        let colors = code.to_colors();
        let size = colors.len() as f64;
        let size = size.sqrt().approx_as_by::<usize, RoundToNearest>()?;
        let array = Array { colors, size };
        return Ok(array);
    }

    pub fn print(&self) {
        for row in (0..self.size).step_by(2) {
            for col in 0..self.size {
                let upper = self.get_color(row, col);
                let lower = self.get_color(row + 1, col);
                match (upper, lower) {
                    (Color::Light, Color::Light) => print!(" "),
                    (Color::Light, Color::Dark) => print!("{}", LOWER_BLOCK),
                    (Color::Dark, Color::Light) => print!("{}", UPPER_BLOCK),
                    (Color::Dark, Color::Dark) => print!("{}", FULL_BLOCK),
                }
            }
            println!();
        }
    }

    fn get_color(&self, row: usize, col: usize) -> Color {
        let index = (row * self.size) + col;
        return if index < self.colors.len() { self.colors[index] } else { Color::Light };
    }
}