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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! An API to easily print a two dimensional array to stdout.
//! # Example
//! ```rust
//! use grid_printer::GridPrinter;
//!
//! let cars = vec![
//!     vec!["Make", "Model", "Color", "Year", "Price", ],
//!     vec!["Ford", "Pinto", "Green", "1978", "$750.00", ],
//!     vec!["Toyota", "Tacoma", "Red", "2006", "$15,475.23", ],
//!     vec!["Lamborghini", "Diablo", "Yellow", "2001", "$238,459.99", ],
//! ];
//! 
//! let rows = cars.len();
//! let cols = cars[0].len();
//! let printer = GridPrinter::builder(rows, cols)
//!     .col_spacing(4)
//!     .build();
//! printer.print(&cars);
//! ```
//!
//! # Output:
//! ```bash
//! Make           Model     Color     Year    Price
//! Ford           Pinto     Green     1978    $750.00
//! Toyota         Tacoma    Red       2006    $15,475.23
//! Lamborghini    Diablo    Yellow    2001    $238,459.99
//! ```

pub mod style;

use std::io;
use std::fmt;
use std::io::Write;
use std::fmt::Display;
use std::error::Error;
use std::cell::RefCell;

use crate::style::StyleOpt;
use crate::style::stylize;

/// An API to easily print a two dimensional array to stdout.
///
/// # Example
/// ```rust
/// use grid_printer::GridPrinter;
///
/// let cars = vec![
///     vec!["Make", "Model", "Color", "Year", "Price", ],
///     vec!["Ford", "Pinto", "Green", "1978", "$750.00", ],
///     vec!["Toyota", "Tacoma", "Red", "2006", "$15,475.23", ],
///     vec!["Lamborghini", "Diablo", "Yellow", "2001", "$238,459.99", ],
/// ];
/// 
/// let rows = cars.len();
/// let cols = cars[0].len();
/// let printer = GridPrinter::builder(rows, cols)
///     .col_spacing(4)
///     .build();
/// printer.print(&cars);
/// ```
///
/// Output:
/// ```bash
/// Make           Model     Color     Year    Price
/// Ford           Pinto     Green     1978    $750.00
/// Toyota         Tacoma    Red       2006    $15,475.23
/// Lamborghini    Diablo    Yellow    2001    $238,459.99
/// ```
// #[derive(Debug)]
pub struct GridPrinter {
    rows: usize,
    cols: usize,
    max_widths: RefCell<Vec<usize>>,
    col_spacing: usize,
    col_styles: Option<Vec<Option<StyleOpt>>>,
}

impl GridPrinter {
    pub fn new(rows: usize, cols: usize) -> Self {
        Self {
            rows,
            cols,
            ..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()
    }

    #[allow(clippy::print_with_newline)]
    pub fn print_cell(&self, cell: &str, col_idx: usize, style_opt: Option<&StyleOpt>) {

        let mut s = cell.to_string(); 
        if let Some(style_opt) = style_opt {
            s = stylize(cell, style_opt);
        }
        let col_width = self.max_widths.borrow()[col_idx];
        let pad = GridPrinter::pad(col_width - cell.len() + self.col_spacing);
        print!("{}{}", s, pad);
    }

    #[allow(clippy::print_with_newline)]
    pub fn print<F: Display>(&self, source: &[Vec<F>]) {
        let mut buff: Vec<String> = Vec::new();

        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);
                buff.push(cell);
            }
        }


        for (i, cell) in buff.iter().enumerate() {
            let col_idx = i % self.cols;
            let _row_idx = i / self.rows;

            let style_opt = match self.col_styles.as_ref() {
                None => None,
                Some(col_styles) => match col_styles.get(col_idx) {
                    None => None,
                    Some(style_opt) => style_opt.as_ref(),
                }
            };

            self.print_cell(cell, col_idx, style_opt);

            if (i + 1) % self.cols == 0 {
                print!("\n");
                io::stdout().flush().unwrap();
            }
        }


    }
}

/// A Builder to create/customize a GridPrinter instance
/// ```rust
/// use grid_printer::GridPrinter;
/// use grid_printer::GridPrinterBuilder;
/// 
/// let rows = 3;
/// let cols = 3;
/// let printer: GridPrinter = GridPrinterBuilder::new(rows, cols)
///     .col_spacing(4)
///     .build();
/// ```
#[derive(Debug)]
pub struct GridPrinterBuilder {
    rows: usize,
    cols: usize,
    col_spacing: usize,
    col_styles: Option<Vec<Option<StyleOpt>>>,
}

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

impl GridPrinterBuilder {

    pub fn new(rows: usize, cols: usize) -> Self {
        GridPrinterBuilder {
            rows,
            cols,
            ..Default::default()
        }
    }

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

        self
    }

    pub fn col_styles(mut self, col_styles: Vec<Option<StyleOpt>>) -> Result<Self, GridPrinterErr> {
        match col_styles.len() == self.cols {
            false => Err(GridPrinterErr::DimensionErr),
            true => {
                self.col_styles = Some(col_styles);

                Ok(self)
            }
        }
    }

    pub fn col_style(mut self, idx: usize, opt: StyleOpt) -> Result<Self, GridPrinterErr> {
        // Note: The size check here is somewhat redundant given the subsequent logic; however,
        // performing the check here guarantees we don't mutate the GridPrinterBuilder by adding
        // a Vec for an index that is outside the column range.
        if idx >= self.cols {
            return Err(GridPrinterErr::DimensionErr);
        }

        let col_styles = self.col_styles.get_or_insert(vec![None; self.cols]);
        let col_style = col_styles.get_mut(idx)
            .ok_or(GridPrinterErr::DimensionErr)?;
        *col_style = Some(opt);

        Ok(self)
    }

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

}

#[derive(Debug)]
pub enum GridPrinterErr {
    DimensionErr,
}

impl Display for GridPrinterErr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GridPrinterErr::DimensionErr => {
                write!(f, "DimensionErr. Caused by mismatch in dimension size between method calls.")
            },
        }
    }
}

impl Error for GridPrinterErr {}


#[cfg(test)]
mod tests {

    use super::*;

    #[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);
    }

}