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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use std::io;
use std::io::Write;
use std::fmt::Display;
use std::cell::RefCell;

// #[derive(Debug)]
pub struct GridPrinter {
    rows: usize,
    cols: usize,
    buff: RefCell<Vec<String>>,
    max_widths: RefCell<Vec<usize>>,
    col_spacing: usize,
}

impl GridPrinter {
    pub fn new(rows: usize, cols: usize) -> Self {
        Self {
            cols,
            rows,
            ..GridPrinterBuilder::new(rows, cols).build()
        }
    }

    pub fn builder(rows: usize, cols: usize) -> GridPrinterBuilder {
        GridPrinterBuilder::new(rows, cols)
    }

    fn pad(n: usize) -> String {
        vec![' '; n].into_iter().collect()
    }

    pub fn print<F: Display>(&self, source: &Vec<Vec<F>>) {

        for i in 0..self.rows {
            let row = source.get(i);
            for j in 0..self.cols {
                let cell = match row {
                    None => "".to_string(),
                    Some(row) => match row.get(j) {
                        None => "".to_string(),
                        Some(el) => format!("{}", el),
                    } 
                };
                let len = cell.len();
                if len > self.max_widths.borrow()[j] {
                    self.max_widths.borrow_mut()[j] = len;
                }
                self.buff.borrow_mut().push(cell);
            }
        }


        let buff = self.buff.borrow();
        for (i, cell) in buff.iter().enumerate() {
            let col_width = self.max_widths.borrow()[i % self.cols];
            let pad = GridPrinter::pad(col_width - cell.len() + self.col_spacing);
            print!("{}{}", cell, pad);
            if (i + 1) % self.cols == 0 {
                print!("\n");
                io::stdout().flush().unwrap();
            }
        }


    }
}

#[derive(Debug)]
pub struct GridPrinterBuilder {
    rows: usize,
    cols: usize,
    col_spacing: usize,
}

impl Default for GridPrinterBuilder {
     fn default() -> Self {
        Self {
            rows: 1,
            cols: 1,
            col_spacing: 2,
        }
    }
}

impl GridPrinterBuilder {

    pub fn new(rows: usize, cols: usize) -> Self {
        let mut builder = GridPrinterBuilder::default(); 
        builder.rows = rows;
        builder.cols = cols;

        builder
    }

    pub fn col_spacing(mut self, col_spacing: usize) -> Self {
        self.col_spacing = col_spacing;

        self
    }


    pub fn build(self) -> GridPrinter {
        GridPrinter {
            rows: self.rows,
            cols: self.cols,
            buff: RefCell::new(Vec::with_capacity(self.rows * self.cols)),
            max_widths: RefCell::new(vec![0; self.cols]),
            col_spacing: self.col_spacing,
        }
    }

}


#[cfg(test)]
mod tests {

    use super::*;
    use rand::random;
    use std::time::Instant;


    #[test]
    fn test_2d_arr() {
        let v = vec![
            vec![1, 20, 3, ],
            vec![40, 5, 6, ],
            vec![7, 800, 9, ],
        ];

        let rows = v.len();
        let cols = v[0].len();
        let printer = GridPrinterBuilder::new(rows, cols)
            .col_spacing(20)
            .build();
        printer.print(&v);
    }

    fn create_test_grid(rows: usize, cols: usize) -> Vec<Vec<u8>> {
        let mut grid: Vec<Vec<u8>> = Vec::with_capacity(rows);
        for i in 0..rows {
            grid.push(Vec::with_capacity(cols));
            let row = grid.get_mut(i).unwrap();
            for _j in 0..cols {
                row.push(random::<u8>());
            }
        }

        grid
    }

    // #[bench]
    #[test]
    fn bench_vs_vec() {
        let rows = 100;
        let cols = 100;
        let grid = create_test_grid(rows, cols);
        let printer = GridPrinterBuilder::new(rows, cols)
            .col_spacing(4)
            .build();
        
        let start = Instant::now();
        printer.print(&grid);
        let fin = Instant::now();
        let time_printer = fin.duration_since(start);
        println!("time = {:?}", time_printer);

        let start = Instant::now();
        for row in grid.iter() {
            for cell in row.iter() {
                print!("{}  ", cell);
            }
            print!("\n");
        }
        let fin = Instant::now();
        let time_printer = fin.duration_since(start);
        println!("time = {:?}", time_printer);

    }

}