verynicetable 0.2.0

Number one table.
Documentation
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Number one table.
//!
//! Very basic and lightweight table builder to print tabular data.
//!
//!
//! # Examples
//!
//! ```
//! use std::fmt::Alignment::{Left, Right};
//! use verynicetable::Table;
//!
//! let ports = vec![
//!     vec!["rapportd", "449", "Quentin", "*:61165"],
//!     vec!["Python", "22396", "Quentin", "*:8000"],
//!     vec!["rustrover", "30928", "Quentin", "127.0.0.1:63342"],
//!     vec!["Transmiss", "94671", "Quentin", "*:51413"],
//!     vec!["Transmiss", "94671", "Quentin", "*:51413"],
//! ];
//!
//! let table = Table::new()
//!     .headers(&["COMMAND", "PID", "USER", "HOST:PORTS"])
//!     .alignments(&[Left, Right, Left, Right])
//!     .data(&ports)
//!     .to_string();
//!
//! assert_eq!(
//!     table,
//!     "\
//! COMMAND      PID  USER          HOST:PORTS
//! rapportd     449  Quentin          *:61165
//! Python     22396  Quentin           *:8000
//! rustrover  30928  Quentin  127.0.0.1:63342
//! Transmiss  94671  Quentin          *:51413
//! Transmiss  94671  Quentin          *:51413
//! "
//! );
//! ```

use std::{fmt, fmt::Write, iter};

const TABLE_COLUMN_SEPARATOR: &str = "  ";

/// Ready-to-render `Table` blueprint with checks and conversions made.
///
/// `Table` can hold "invalid" state during the build process; you can't
/// possibly set everything at once. And also `alignments`, while being
/// required during rendering, can be omitted in the builder as they
/// have defaults we can use.
///
/// `TableBlueprint` on the other hand, is ready-to-render. All required
/// fields are ensured to be set, and it holds additional context for
/// drawing (e.g., `columns_width`).
struct TableBlueprint<'a> {
    headers: Vec<&'a str>,
    alignments: Vec<fmt::Alignment>,
    data: Vec<Vec<&'a str>>,
    columns_width: Vec<usize>,
}

/// `Table` builder.
///
/// The methods of interest are [`new()`](Self::new),
/// [`headers()`](Self::headers), [`alignments()`](Self::alignments),
/// and [`data()`](Self::data).
///
/// This can possibly hold intermediary "invalid" state. Which is
/// perfectly normal for a builder.
///
/// # Implementation Details
///
/// During rendering, a `TableBuilder` (private) is first created
/// through `make_table_blueprint()`. `TableBuilder` then drives the
/// printing of the table to the terminal.
///
/// Contrary to `Table`, `TableBuilder` can only hold valid
/// ready-to-render state.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Table<'a> {
    headers: Option<Vec<&'a str>>,
    alignments: Option<&'a [fmt::Alignment]>,
    data: Option<Vec<Vec<&'a str>>>,
}

impl<'a> Default for Table<'a> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> Table<'a> {
    #[must_use]
    pub fn new() -> Self {
        Self {
            headers: None,
            alignments: None,
            data: None,
        }
    }

    pub fn headers(&mut self, headers: &'a [impl AsRef<str>]) -> &mut Self {
        let headers: Vec<&str> = headers.iter().map(AsRef::as_ref).collect();
        self.headers = Some(headers);
        self
    }

    pub fn alignments(&mut self, alignments: &'a [fmt::Alignment]) -> &mut Self {
        self.alignments = Some(alignments);
        self
    }

    pub fn data(&mut self, data: &'a [Vec<impl AsRef<str>>]) -> &mut Self {
        let data: Vec<Vec<&str>> = data
            .iter()
            .map(|row| row.iter().map(AsRef::as_ref).collect())
            .collect();
        self.data = Some(data);
        self
    }

    fn render(&self) -> String {
        let table = self.make_table_blueprint();

        if table.data.is_empty() {
            return format!("{}\n", table.headers.join("  "));
        }

        let mut output = String::new();

        let mut render_row = |row: &Vec<&str>| {
            for (i, cell) in row.iter().enumerate() {
                let width = table.columns_width[i];
                let alignment = table.alignments[i];

                let is_last_column = i == table.headers.len() - 1;

                let _ = match alignment {
                    fmt::Alignment::Left if is_last_column => write!(output, "{cell}"),
                    fmt::Alignment::Left => write!(output, "{cell:<width$}"),
                    fmt::Alignment::Right => write!(output, "{cell:>width$}"),
                    fmt::Alignment::Center => write!(output, "{cell:^width$}"),
                };

                if is_last_column {
                    output.push('\n');
                } else {
                    output.push_str(TABLE_COLUMN_SEPARATOR);
                }
            }
        };

        if !table.headers.iter().all(|header| header.is_empty()) {
            render_row(&table.headers);
        }

        for row in table.data {
            render_row(&row);
        }

        output
    }

    fn make_table_blueprint(&self) -> TableBlueprint {
        let nb_cols = self.determine_nb_columns();

        let headers = self.get_headers_or_default(nb_cols);
        let alignments = self.get_alignments_or_default(nb_cols);
        let data = self.data.as_ref().expect("data is required");

        Self::ensure_data_consistency(&headers, &alignments, data);

        let columns_width = Self::determine_columns_width(&headers, data);

        TableBlueprint {
            headers,
            alignments,
            data: data.to_owned(),
            columns_width,
        }
    }

    #[cfg(not(tarpaulin_include))] // Wrongly marked uncovered.
    fn determine_nb_columns(&self) -> usize {
        if let Some(headers) = self.headers.as_ref() {
            return headers.len();
        }
        if let Some(data) = self.data.as_ref() {
            if !data.is_empty() {
                return data[0].len();
            }
        }
        panic!("headers and data cannot both be empty");
    }

    fn get_headers_or_default(&self, nb_cols: usize) -> Vec<&str> {
        match self.headers.as_ref() {
            Some(headers) => headers.to_owned(),
            // This may look a bit hacky (it is), but it plays nicely
            // with the overall logic (`Option` would make the code too
            // convoluted). Moreover, it has the added benefit of
            // handling the special case where the user does it himself.
            None => [""].repeat(nb_cols),
        }
    }

    fn get_alignments_or_default(&self, nb_cols: usize) -> Vec<fmt::Alignment> {
        match self.alignments {
            Some(alignments) => alignments.to_vec(),
            None => [fmt::Alignment::Left].repeat(nb_cols),
        }
    }

    /// Ensure data is consistent.
    ///
    /// "Consistent" essentially means the number of headers matches
    /// the number of alignment properties, and the number of columns
    /// in the data.
    fn ensure_data_consistency(
        headers: &[&str],
        alignments: &[fmt::Alignment],
        data: &[Vec<&str>],
    ) {
        assert_eq!(
            headers.len(),
            alignments.len(),
            "number of headers must match alignments"
        );
        assert!(
            data.iter().all(|row| row.len() == headers.len()),
            "number of headers must match columns in data"
        );
    }

    /// Determine the width of each column.
    ///
    /// The width of a column is the number of characters in the longest
    /// value held in the column (including header).
    fn determine_columns_width(headers: &[&str], data: &[Vec<&str>]) -> Vec<usize> {
        let mut cols_width = vec![0; headers.len()];
        for i in 0..headers.len() {
            let column_values: Vec<&str> = data.iter().map(|x| x[i]).collect();
            let max_width = Self::width_of_longest_value_in_column(headers[i], &column_values);
            cols_width[i] = max_width;
        }
        cols_width
    }

    fn width_of_longest_value_in_column(header: &str, column_values: &[&str]) -> usize {
        let header = iter::once(&header);
        let column_values = column_values.iter();

        header
            .chain(column_values)
            .map(|x| x.chars().count())
            .max()
            .expect("iterator cannot be empty because header is required")
    }
}

impl fmt::Display for Table<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let output = self.render();
        write!(f, "{output}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn table_default_builder() {
        assert_eq!(Table::new(), Table::default());
    }

    #[test]
    fn table_regular() {
        let table = Table::new()
            .headers(&["SHORT", "WITH SPACE", "LAST COLUMN"])
            .alignments(&[
                fmt::Alignment::Left,
                fmt::Alignment::Left,
                fmt::Alignment::Left,
            ])
            .data(&[
                vec![
                    "Value larger than header",
                    "Column name has space",
                    "No trailing whitespace",
                ],
                vec!["---", "---", "---"],
            ])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
SHORT                     WITH SPACE             LAST COLUMN
Value larger than header  Column name has space  No trailing whitespace
---                       ---                    ---
"
        );
    }

    #[test]
    fn table_all_empty_headers_not_rendered() {
        let table = Table::new()
            .headers(&["", ""])
            .data(&[vec!["---", "----------------"]])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
---  ----------------
"
        );
    }

    #[test]
    fn table_some_empty_headers_all_rendered() {
        let table = Table::new()
            .headers(&["", "-"])
            .data(&[vec!["---", "----------------"]])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            r"     -
---  ----------------
"
        );
    }

    #[test]
    fn table_default_headers() {
        let table = Table::new()
            .data(&[vec!["---", "----------------"]])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
---  ----------------
"
        );
    }

    #[test]
    fn table_headers_alignment() {
        let table = Table::new()
            .headers(&["ALIGN-LEFT", "ALIGN-CENTER", "ALIGN-RIGHT"])
            .alignments(&[
                fmt::Alignment::Left,
                fmt::Alignment::Center,
                fmt::Alignment::Right,
            ])
            .data(&[
                vec![
                    "Header is aligned Left",
                    "Header is aligned Center",
                    "Header is aligned Right",
                ],
                vec!["---", "---", "---"],
            ])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
ALIGN-LEFT                    ALIGN-CENTER                    ALIGN-RIGHT
Header is aligned Left  Header is aligned Center  Header is aligned Right
---                               ---                                 ---
"
        );
    }

    #[test]
    fn table_values_alignment() {
        let table = Table::new()
            .headers(&["ALIGN-LEFT", "ALIGN-CENTER", "ALIGN-RIGHT"])
            .alignments(&[
                fmt::Alignment::Left,
                fmt::Alignment::Center,
                fmt::Alignment::Right,
            ])
            .data(&[vec!["Left", "Center", "Right"], vec!["---", "---", "---"]])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
ALIGN-LEFT  ALIGN-CENTER  ALIGN-RIGHT
Left           Center           Right
---             ---               ---
"
        );
    }

    #[test]
    fn table_default_alignments() {
        let table = Table::new()
            .headers(&["VALUE LEFT", "COLUMN LEFT"])
            .data(&[vec!["---", "----------------"]])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
VALUE LEFT  COLUMN LEFT
---         ----------------
"
        );
    }

    #[test]
    fn table_default_headers_and_alignments() {
        let table = Table::new()
            .data(&[
                vec!["---", "----------------"],
                vec!["----------------", "---"],
            ])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
---               ----------------
----------------  ---
"
        );
    }

    #[test]
    fn table_with_empty_data() {
        let table = Table::new()
            .headers(&["SHORT", "WITH SPACE", "LAST COLUMN"])
            .alignments(&[
                fmt::Alignment::Left,
                fmt::Alignment::Left,
                fmt::Alignment::Left,
            ])
            .data(&[] as &[Vec<&str>; 0])
            .to_string();

        println!("{table}");
        assert_eq!(
            table,
            "\
SHORT  WITH SPACE  LAST COLUMN
"
        );
    }

    #[test]
    fn table_completely_empty() {
        let table = Table::new()
            .headers(&[] as &[&str; 0])
            .alignments(&[])
            .data(&[] as &[Vec<&str>; 0])
            .to_string();

        println!("{table}");
        assert_eq!(table, "\n");
    }

    #[test]
    #[should_panic(expected = "headers and data cannot both be empty")]
    fn table_error_completely_empty_with_default_headers() {
        let table = Table::new()
            .alignments(&[])
            .data(&[] as &[Vec<&str>; 0])
            .to_string();

        println!("{table}");
        assert_eq!(table, "\n");
    }

    #[test]
    fn table_completely_empty_with_default_alignments() {
        let table = Table::new()
            .headers(&[] as &[&str; 0])
            .data(&[] as &[Vec<&str>; 0])
            .to_string();

        println!("{table}");
        assert_eq!(table, "\n");
    }

    #[test]
    #[should_panic(expected = "headers and data cannot both be empty")]
    fn table_error_completely_empty_with_default_headers_and_alignments() {
        let table = Table::new().data(&[] as &[Vec<&str>; 0]).to_string();

        println!("{table}");
        assert_eq!(table, "\n");
    }

    #[test]
    #[should_panic(expected = "number of headers must match alignments")]
    fn table_error_nb_headers_neq_nb_alignments() {
        Table::new()
            .headers(&["COLUMN 1", "COLUMN 2"])
            .alignments(&[
                fmt::Alignment::Left,
                fmt::Alignment::Left,
                fmt::Alignment::Left,
            ])
            .data(&[vec!["---", "---"]])
            .to_string();
    }

    #[test]
    #[should_panic(expected = "number of headers must match columns in data")]
    fn table_error_nb_headers_neq_nb_columns_in_data() {
        Table::new()
            .headers(&["COLUMN 1", "COLUMN 2"])
            .alignments(&[fmt::Alignment::Left, fmt::Alignment::Left])
            .data(&[
                vec!["---", "---"],
                vec!["---", "---", "---"],
                vec!["---", "---"],
            ])
            .to_string();
    }

    #[test]
    fn table_render_multiple_times() {
        let alignments = [fmt::Alignment::Left];
        let data = [vec!["---"]];
        let table = Table::new()
            .headers(&["HEADER"])
            .alignments(&alignments)
            .data(&data)
            .to_owned();

        let render_1 = table.to_string();
        let render_2 = table.to_string();

        println!("{table}");

        assert_eq!(render_1, "HEADER\n---\n");
        assert_eq!(render_1, render_2);
    }
}