nestable 0.2.3

Unicode-aware text table rendering with support for nested tables
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
//! Rust implementation of a nested table renderer for terminals and fixed
//! font size displays

use std::cmp::{max, min};
use std::collections::HashMap;
use std::fmt;
use std::fmt::Formatter;
use unicode_width::UnicodeWidthChar;

/// The Table struct defines the tables contents, styling, attributes and
/// alignment rules.
///
/// Applications create instances of Table, populate them using the add_rows
/// and add_row method and optionally specify rendering attributes and
/// alignment rules on the table, column, row or cell level.
#[derive(Clone, Debug)]
pub struct Table<'a> {
    rows: Vec<Row>,
    style: &'a Style,
    invert_header: bool,
    border_attr: Attributes,
    table_attr: Option<Attributes>,
    col_alt_attr: [Option<Attributes>; 2],
    col_attr: HashMap<usize, Attributes>,
    row_alt_attr: [Option<Attributes>; 2],
    row_attr: HashMap<usize, Attributes>,
    cell_attr: HashMap<(usize, usize), Attributes>,
    table_align: (Horizontal, Vertical),
    col_align: HashMap<usize, (Option<Horizontal>, Option<Vertical>)>,
    row_align: HashMap<usize, (Option<Horizontal>, Option<Vertical>)>,
    cell_align: HashMap<(usize, usize), (Option<Horizontal>, Option<Vertical>)>,
}

/// A Row is struct which just holds a vector of strings, each representing the
/// content of each column.
///
/// Each individual string may contain line feeds and ansi escape sequences.
#[derive(Clone, Debug)]
struct Row {
    cells: Vec<String>,
}

/// Index offsets in style arrays
#[repr(usize)]
pub enum StyleIdx {
    Left = 0,
    Pad = 1,
    Right = 2,
    Top = 3,
    Inter = 4,
    Bot = 5,
}

impl StyleIdx {
    /// Provides the number of StyleIdx entries
    pub const COUNT: usize = 6;
}

/// A Style is defined very loosely as 4 named arrays (top, row, sep, bot), each
/// containing 6 strings, the meaning of which is indicated by their correcponding
/// StyleIdx entry.
///
/// A typical example is shown here:
///
///  pub const GLYPHS_ROUNDED: Style = Style {
///      top: ["╭", "─", "╮", "┬", "┼", "┴"],
///      row: ["│", "─", "│", "│", "│", "│"],
///      sep: ["├", "─", "┤", "┬", "┼", "┴"],
///      bot: ["╰", "─", "╯", "┬", "┼", "┴"],
///  };
#[derive(Clone, Debug)]
pub struct Style {
    pub top: [&'static str; StyleIdx::COUNT],
    pub row: [&'static str; StyleIdx::COUNT],
    pub sep: [&'static str; StyleIdx::COUNT],
    pub bot: [&'static str; StyleIdx::COUNT],
}

/// Attributes are a pair of strings which turn on and off specific ansi
/// terminal rendering options.
#[derive(Clone, Debug)]
pub struct Attributes {
    on: String,
    off: String,
}

/// A LayoutLine holds the text of a line in a cell and its display width so that
/// we only have to compute that width once
#[derive(Clone, Debug)]
struct LayoutLine {
    line: String,
    width: usize,
}

/// A LayoutCell holds 0 or more LayoutLines and the maximum display width of all
/// the individual lines
#[derive(Clone, Debug)]
struct LayoutCell {
    lines: Vec<LayoutLine>,
    width: usize,
}

/// A LayoutRow holds a cell for each column which is used on the row
#[derive(Clone, Debug)]
struct LayoutRow {
    cells: Vec<LayoutCell>,
    height: usize,
}

/// A LayoutTable holds all the LayoutRows for a table and the tables stylistic
/// configuration.
///
/// This is constructed prior to printing by converting an input Table.
#[derive(Clone, Debug)]
struct LayoutTable<'a> {
    config: &'a Table<'a>,
    rows: Vec<LayoutRow>,
    widths: Vec<usize>,
}

/// The styles modules provides various ways to control how your table's borders
/// are rendered.
///
/// It provides various implementations of the Style struct. Style implementations
/// can also be provided by the hosting application and are free to include escape
/// sequences and utf-8 characters if required.
#[rustfmt::skip]
pub mod styles {
    use super::Style;

    pub const ASCII_BORDER: Style = Style {
        top: ["+", "-", "+", "+", "+", "+"],
        row: ["|", "-", "|", "|", "|", "|"],
        sep: ["+", "-", "+", "+", "+", "+"],
        bot: ["+", "-", "+", "+", "+", "+"],
    };

    pub const ASCII_NO_BORDER: Style = Style {
        top: ["", "",  "", "",  "",  "" ],
        row: ["", " ", "", "|", "|", "|"],
        sep: ["", "-", "", "+", "+", "+"],
        bot: ["", "",  "", "",  "",  "" ],
    };

    pub const ASCII_NO_ROW_SEPARATOR: Style = Style {
        top: ["", "",  "", "",  "",  "" ],
        row: ["", " ", "", "|", "|", "|"],
        sep: ["", "",  "", "",  "",  "" ],
        bot: ["", "",  "", "",  "",  "" ],
    };

    pub const GLYPHS_SQUARE: Style = Style {
        top: ["", "", "", "", "", ""],
        row: ["", "", "", "", "", ""],
        sep: ["", "", "", "", "", ""],
        bot: ["", "", "", "", "", ""],
    };

    pub const GLYPHS_ROUNDED: Style = Style {
        top: ["", "", "", "", "", ""],
        row: ["", "", "", "", "", ""],
        sep: ["", "", "", "", "", ""],
        bot: ["", "", "", "", "", ""],
    };

    pub const GLYPHS_ROUNDED_SPACED: Style = Style {
        top: ["╭─", "", "─╮", "─┬─", "─┼─", "─┴─"],
        row: ["", "", "", "", "", ""],
        sep: ["├─", "", "─┤", "─┬─", "─┼─", "─┴─"],
        bot: ["╰─", "", "─╯", "─┬─", "─┼─", "─┴─"],
    };

    pub const GLYPHS_NO_BORDER: Style = Style {
        top: ["", "",  "", "",  "",  "" ],
        row: ["", "", "", "", "", ""],
        sep: ["", "", "", "", "", ""],
        bot: ["", "",  "", "",  "",  "" ],
    };

    pub const GLYPHS_NO_ROW_SEPARATOR: Style = Style {
        top: ["", "",  "", "",  "",  "" ],
        row: ["", " ", "", "", "", ""],
        sep: ["", "",  "", "",  "",  "" ],
        bot: ["", "",  "", "",  "",  "" ],
    };

    pub const SPACE: Style = Style {
        top: ["", "",  "", "", "",  ""],
        row: ["", " ", "", "", " ", ""],
        sep: ["", "",  "", "", "",  ""],
        bot: ["", "",  "", "", "",  ""],
    };

    pub const HEAVY: Style = Style {
        top: ["", "", "", "", "", ""],
        row: ["", "", "", "", "", ""],
        sep: ["", "", "", "", "", ""],
        bot: ["", "", "", "", "", ""],
    };

    pub const DOUBLE: Style = Style {
        top: ["", "", "", "", "", ""],
        row: ["", "", "", "", "", ""],
        sep: ["", "", "", "", "", ""],
        bot: ["", "", "", "", "", ""],
    };

    pub const HEAVY_MIXED: Style = Style {
        top: ["", "", "", "", "", ""],
        row: ["", "", "", "", "", ""],
        sep: ["", "", "", "", "", ""],
        bot: ["", "", "", "", "", ""],
    };

    pub const DOUBLE_HEAVY: Style = Style {
        top: ["", "", "", "", "", ""],
        row: ["", "", "", "", "", ""],
        sep: ["", "", "", "", "", ""],
        bot: ["", "", "", "", "", ""],
    };
}

/// Provides useful ansi escape sequences which can be used to decorate a table.
#[rustfmt::skip]
pub mod ansi {
    pub const RESET:      &str = "\x1b[0;0m";

    pub const BOLD:       &str = "\x1b[1m";
    pub const DIM:        &str = "\x1b[2m";
    pub const ITALIC:     &str = "\x1b[3m";
    pub const UNDERLINE:  &str = "\x1b[4m";
    pub const INVERT:     &str = "\x1b[7m";
    pub const INVERT_OFF: &str = "\x1b[27m";

    pub const BLACK:   &str = "\x1b[30m";
    pub const RED:     &str = "\x1b[31m";
    pub const GREEN:   &str = "\x1b[32m";
    pub const YELLOW:  &str = "\x1b[33m";
    pub const BLUE:    &str = "\x1b[34m";
    pub const MAGENTA: &str = "\x1b[35m";
    pub const CYAN:    &str = "\x1b[36m";
    pub const WHITE:   &str = "\x1b[37m";

    pub const BRIGHT_BLACK:   &str = "\x1b[90m";
    pub const BRIGHT_RED:     &str = "\x1b[91m";
    pub const BRIGHT_GREEN:   &str = "\x1b[92m";
    pub const BRIGHT_YELLOW:  &str = "\x1b[93m";
    pub const BRIGHT_BLUE:    &str = "\x1b[94m";
    pub const BRIGHT_MAGENTA: &str = "\x1b[95m";
    pub const BRIGHT_CYAN:    &str = "\x1b[96m";
    pub const BRIGHT_WHITE:   &str = "\x1b[97m";

    pub const BG_BLACK:   &str = "\x1b[40m";
    pub const BG_RED:     &str = "\x1b[41m";
    pub const BG_GREEN:   &str = "\x1b[42m";
    pub const BG_YELLOW:  &str = "\x1b[43m";
    pub const BG_BLUE:    &str = "\x1b[44m";
    pub const BG_MAGENTA: &str = "\x1b[45m";
    pub const BG_CYAN:    &str = "\x1b[46m";
    pub const BG_WHITE:   &str = "\x1b[47m";

    pub const BG_BRIGHT_BLACK:   &str = "\x1b[100m";
    pub const BG_BRIGHT_RED:     &str = "\x1b[101m";
    pub const BG_BRIGHT_GREEN:   &str = "\x1b[102m";
    pub const BG_BRIGHT_YELLOW:  &str = "\x1b[103m";
    pub const BG_BRIGHT_BLUE:    &str = "\x1b[104m";
    pub const BG_BRIGHT_MAGENTA: &str = "\x1b[105m";
    pub const BG_BRIGHT_CYAN:    &str = "\x1b[106m";
    pub const BG_BRIGHT_WHITE:   &str = "\x1b[107m";

    /// Provides the fg escape sequence for 256 colours.
    pub fn fg_256(n: u8) -> String {
        format!("\x1b[38;5;{}m", n)
    }

    /// Provides the fg escape sequence for 24 bit colours.
    pub fn fg_rgb(r: u8, g: u8, b: u8) -> String {
        format!("\x1b[38;2;{};{};{}m", r, g, b)
    }

    /// Provides the bg escape sequence for 256 colours.
    pub fn bg_256(n: u8) -> String {
        format!("\x1b[48;5;{}m", n)
    }

    /// Provides the bg escape sequence for 24 bit colours.
    pub fn bg_rgb(r: u8, g: u8, b: u8) -> String {
        format!("\x1b[48;2;{};{};{}m", r, g, b)
    }
}

/// Specifies horizontal alignment options
#[derive(Clone, Debug, Copy)]
pub enum Horizontal {
    Left,
    Centre,
    Right,
}

/// Specifies vertical alignment options
#[derive(Clone, Debug, Copy)]
pub enum Vertical {
    Top,
    Centre,
    Bottom,
}

/// Determines the display width of a given utf8 string.
fn display_width(input: &str) -> usize {
    let mut chars = input.chars().peekable();
    let mut width = 0;

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Try to parse CSI: ESC [
            if let Some('[') = chars.peek().copied() {
                chars.next(); // consume '['

                // Consume until final byte (@ to ~)
                let mut found_final = false;

                while let Some(next) = chars.next() {
                    if ('@'..='~').contains(&next) {
                        found_final = true;
                        break;
                    }
                }

                if !found_final {
                    eprintln!("Warning: unterminated ANSI escape sequence");
                }

                continue;
            } else {
                eprintln!("Warning: unsupported ANSI escape sequence");
                continue;
            }
        }

        // Normal character width
        match UnicodeWidthChar::width(c) {
            Some(w) => width += w,
            None => {
                // Fallback pictograph hack
                let double = ('\u{1F300}'..='\u{1FAFF}').contains(&c);
                width += if double { 2 } else { 1 };
            }
        }
    }

    width
}

/// Provides ctors for the Row
impl Row {
    /// Populates a Row from a list of str's
    fn new<I, S>(input: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let cells = input.into_iter().map(Into::into).collect();

        Self { cells: cells }
    }
}

/// Provides the Table implementation
impl<'a> Table<'a> {
    /// Provides an empty table
    pub fn new() -> Self {
        Self {
            rows: Vec::new(),
            invert_header: true,
            style: &styles::GLYPHS_ROUNDED,
            border_attr: Attributes::new(),
            table_attr: None,
            col_alt_attr: Default::default(),
            col_attr: HashMap::new(),
            row_alt_attr: Default::default(),
            row_attr: HashMap::new(),
            cell_attr: HashMap::new(),
            table_align: (Horizontal::Left, Vertical::Top),
            col_align: HashMap::new(),
            row_align: HashMap::new(),
            cell_align: HashMap::new(),
        }
    }

    /// Sets the border style for rendering the table
    pub fn set_table_style(mut self, style: &'a Style) -> Self {
        self.style = style;
        self
    }

    /// Sets header inversion on or off for first row
    pub fn set_invert_header(mut self, value: bool) -> Self {
        self.invert_header = value;
        self
    }

    /// Sets the border attribute
    pub fn set_border_attr(mut self, attr: Attributes) -> Self {
        self.border_attr = attr;
        self
    }

    /// Sets a default attribute for the entire table
    pub fn set_table_attr(mut self, attr: Attributes) -> Self {
        self.table_attr = Some(attr);
        self
    }

    /// Sets attributes for alternating columns
    pub fn set_column_alt_attr(mut self, even: Option<Attributes>, odd: Option<Attributes>) -> Self {
        self.col_alt_attr = [even, odd];
        self
    }

    /// Sets the attribute for a specific column
    pub fn set_column_attr(mut self, index: usize, attr: Attributes) -> Self {
        self.col_attr.insert(index, attr);
        self
    }

    /// Sets attributes for alternating rows
    pub fn set_row_alt_attr(mut self, even: Option<Attributes>, odd: Option<Attributes>) -> Self {
        self.row_alt_attr = [even, odd];
        self
    }

    /// Sets the attribute for a specific row
    pub fn set_row_attr(mut self, index: usize, attr: Attributes) -> Self {
        self.row_attr.insert(index, attr);
        self
    }

    /// Sets the attribute for a specific cell
    pub fn set_cell_attr(mut self, row: usize, col: usize, attr: Attributes) -> Self {
        self.cell_attr.insert((row, col), attr);
        self
    }

    /// Determines attribute to use for a given cell, giving priority to cell
    /// over row, over column, over table
    fn resolve_attr(&self, row: usize, col: usize) -> Option<&Attributes> {
        self.cell_attr
            .get(&(row, col))
            .or_else(|| self.row_attr.get(&row))
            .or_else(|| {
                if self.invert_header && row == 0 {
                    None
                } else {
                    let offset = self.invert_header as usize;
                    self.row_alt_attr[(row + offset) % 2].as_ref()
                }
            })
            .or_else(|| self.col_attr.get(&col))
            .or_else(|| self.col_alt_attr[col % 2].as_ref())
            .or(self.table_attr.as_ref())
    }

    /// Set default table alignment
    pub fn set_table_align(mut self, horizontal: Horizontal, vertical: Vertical) -> Self {
        self.table_align = (horizontal, vertical);
        self
    }

    /// Set column alignment
    pub fn set_col_align(mut self, col: usize, h: Option<Horizontal>, v: Option<Vertical>) -> Self {
        self.col_align.insert(col, (h, v));
        self
    }

    /// Set row alignment
    pub fn set_row_align(mut self, row: usize, h: Option<Horizontal>, v: Option<Vertical>) -> Self {
        self.row_align.insert(row, (h, v));
        self
    }

    /// Set cell alignment
    pub fn set_cell_align(mut self, r: usize, c: usize, h: Option<Horizontal>, v: Option<Vertical>) -> Self {
        self.cell_align.insert((r, c), (h, v));
        self
    }

    /// Determines horizontal and vertical alignment for a given cell
    fn resolve_align(&self, row: usize, col: usize) -> (Horizontal, Vertical) {
        let mut h = None;
        let mut v = None;

        if let Some((ch, cv)) = self.cell_align.get(&(row, col)) {
            h = *ch;
            v = *cv;
        }

        if h.is_none() || v.is_none() {
            if let Some((rh, rv)) = self.row_align.get(&row) {
                h = h.or(*rh);
                v = v.or(*rv);
            }
        }

        if h.is_none() || v.is_none() {
            if let Some((ch, cv)) = self.col_align.get(&col) {
                h = h.or(*ch);
                v = v.or(*cv);
            }
        }

        (h.unwrap_or(self.table_align.0), v.unwrap_or(self.table_align.1))
    }

    /// Add multiple rows to the table
    pub fn add_rows<I, R, S>(mut self, input: I) -> Self
    where
        I: IntoIterator<Item = R>,
        R: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.rows.extend(input.into_iter().map(Row::new));
        self
    }

    /// Add a single row to an immutable table
    pub fn add_row<I, S>(mut self, input: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.rows.push(Row::new(input));
        self
    }

    /// Push a single row to a mutable table
    pub fn push_row<I, S>(&mut self, input: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.rows.push(Row::new(input));
    }
}

impl Attributes {
    /// Constructs an empty attribute
    pub fn new() -> Self {
        Self { on: "".to_string(), off: "".to_string() }
    }

    /// Constructs Attributes from a str
    pub fn with(value: &str) -> Self {
        Self { on: value.to_string(), off: ansi::RESET.to_string() }
    }

    /// Constructs Atrributes from a list of str's
    pub fn as_styled<I, S>(input: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self { on: input.into_iter().map(|s| s.into()).collect::<String>(), off: ansi::RESET.to_string() }
    }
}

/// Convenience macro to construct Attributes via attr![str, ...]
#[macro_export]
macro_rules! attr {
    ( $( $x:expr ),* $(,)? ) => {
        Attributes::as_styled([ $( $x ),* ])
    };
}

/// Convenience macro to construct a list of (name, style) pairs.
#[macro_export]
macro_rules! styles {
    ( $( $x:ident ),* ) => {
        [ $( (stringify!($x), styles::$x) ),* ]
    };
}

impl LayoutLine {
    /// Creates a LayoutLine entry from an input string.
    fn new(line: &str) -> Self {
        let width = display_width(&line);
        Self { line: line.to_string(), width: width }
    }
}

impl LayoutCell {
    /// Creates a LayoutCell entry from an input string.
    ///
    /// This also provides the splitting by line feeds and determines the
    /// the widest entry in the cell.
    pub fn new(line: &str) -> Self {
        let mut max_width = 0;

        let lines: Vec<LayoutLine> = line
            .lines()
            .map(|l| {
                let layout_line = LayoutLine::new(&l);
                max_width = max(layout_line.width, max_width);
                layout_line
            })
            .collect();

        Self { lines: lines, width: max_width }
    }
}

impl LayoutRow {
    /// This simply splits the incoming Row (containing cells with linefeed
    /// delimited lines) into LayoutCells
    pub fn new(row: &Row) -> Self {
        let mut max_height = 0;

        let cells: Vec<LayoutCell> = row
            .cells
            .iter()
            .map(|c| {
                let cell = LayoutCell::new(&c);
                max_height = max(cell.lines.len(), max_height);
                cell
            })
            .collect();

        Self { cells: cells, height: max_height }
    }

    /// Determine the column offsets for a given row
    pub fn offsets(&self, widths: &Vec<usize>, full_width: usize) -> Vec<usize> {
        let mut result = Vec::<usize>::new();
        let mut total = 0;
        let count = self.cells.len();
        let decrease = if count == widths.len() { 0 } else { 1 };
        for index in 0..count - decrease {
            total += widths[index];
            result.push(total);
        }
        result.push(full_width);
        result
    }
}

impl<'a> LayoutTable<'a> {
    /// This constructor converts a simple table to a layout table - it ensures
    /// all column widths are correctly calculated to fit the widest cell, and
    /// it additionally ensures that rows which do not have a uniform number of
    /// columns only affect the width to the left of the last column unless their
    /// combined width overflow the current width
    fn new(table: &'a Table<'a>) -> Self {
        let mut max_cols = 0;
        let mut min_cols = usize::MAX;

        // Convert table.row to layout.rows and determine the maximum number of columns on any row
        let rows: Vec<LayoutRow> = table
            .rows
            .iter()
            .map(|r| {
                let row = LayoutRow::new(&r);
                max_cols = max(max_cols, row.cells.len());
                min_cols = min(min_cols, row.cells.len());
                row
            })
            .collect();

        // Allocate the column width vector and track rows which have spanning columns
        let mut widths = Vec::with_capacity(max_cols);
        widths.resize(max_cols, 0);

        // Allocate a vec to track largest spanning item and which column its starts on
        let mut map = Vec::with_capacity(max_cols);
        map.resize(max_cols, 0);

        // For each row which matches the number of entries in widths, populate with the maximum width
        for row in &rows {
            if row.cells.len() == max_cols {
                for cell in 0..row.cells.len() {
                    widths[cell] = max(widths[cell], row.cells[cell].width);
                }
            } else if row.cells.len() > 0 {
                for cell in 0..row.cells.len() - 1 {
                    widths[cell] = max(widths[cell], row.cells[cell].width);
                }
                let index = row.cells.len() - 1;
                map[index] = max(map[index], row.cells[index].width);
            }
        }

        // Extend all columns to the right of each overflowing spanning entry
        let mut total = widths.iter().sum();
        for index in 0..map.len() {
            let span = map[index];
            if span != 0 {
                let width: usize = widths[0..index].iter().sum();
                let required = width + span;
                if required > total {
                    let delta = required - total;
                    let cols = max_cols - index;
                    let extra_per_col = delta / cols;
                    let remainder = delta % cols;
                    for i in index..max_cols {
                        widths[i] += extra_per_col;
                    }
                    for i in index..index + remainder {
                        widths[i] += 1;
                    }
                    total = required;
                }
            }
        }

        Self { config: table, rows: rows, widths: widths }
    }

    /// Determine the column offsets for a given row index
    fn offsets(&self, index: usize, widths: &Vec<usize>, full_width: usize) -> Vec<usize> {
        self.rows.get(index).map(|r| r.offsets(widths, full_width)).unwrap_or_else(|| vec![full_width])
    }
}

impl fmt::Display for Table<'_> {
    /// This displays a Table by first converting to a LayoutTable and then
    /// iterating through each row to render all the individual cells and
    /// ensuring the broader style is applied
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let table = LayoutTable::new(self);
        if table.rows.len() > 0 && table.widths.len() > 0 {
            // The draw lambda is responsible from drawing the borders and inter row separators.
            // it's a no-op if all of the entries are empty strings
            let draw =
                |f: &mut Formatter<'_>, style: &[&str; 6], cols: usize, ante: &Vec<usize>, post: &Vec<usize>| -> fmt::Result {
                    if style[0].len() + style[1].len() + style[2].len() + style[3].len() > 0 {
                        let mut off = 0;
                        let mut ain = 0;
                        let mut pin = 0;
                        let mut cols = cols;
                        let end = *ante.last().unwrap();
                        write!(f, "{}{}", self.border_attr.on, style[StyleIdx::Left as usize])?;
                        while off < end {
                            let width;
                            let glyph;
                            if ante[ain] == post[pin] {
                                width = post[pin] - off;
                                glyph = style[StyleIdx::Inter as usize];
                                ain += 1;
                                pin += 1;
                            } else if ante[ain] < post[pin] {
                                width = ante[ain] - off;
                                glyph = style[StyleIdx::Bot as usize];
                                ain += 1;
                            } else {
                                width = post[pin] - off;
                                glyph = style[StyleIdx::Top as usize];
                                pin += 1;
                            }

                            off += width;
                            cols -= 1;

                            if off < end {
                                write!(f, "{}", style[StyleIdx::Pad as usize].repeat(width))?;
                                write!(f, "{}", glyph)?;
                            } else {
                                let width = width + cols * display_width(glyph);
                                write!(f, "{}", style[StyleIdx::Pad as usize].repeat(width))?;
                            }
                        }
                        writeln!(f, "{}{}", style[StyleIdx::Right as usize], self.border_attr.off)?;
                    }
                    Ok(())
                };

            // Lambda for turning on invert
            let invert_on = |row: usize| -> &str {
                let active = row == 0 && table.config.invert_header;
                if active { ansi::INVERT } else { "" }
            };

            let invert_off = |row: usize| -> &str {
                let active = row == 0 && table.config.invert_header;
                if active { ansi::INVERT_OFF } else { "" }
            };

            // Lambda for turning cell attributes on
            let attr_on =
                |row: usize, col: usize| -> &str { table.config.resolve_attr(row, col).map_or("", |attr| attr.on.as_str()) };

            // Lambda for turning cell attributes off
            let attr_off =
                |row: usize, col: usize| -> &str { table.config.resolve_attr(row, col).map_or("", |attr| attr.off.as_str()) };

            // This calculates the full width of every row
            let full_width: usize = table.widths.iter().sum();

            // This indicates the current style and sizes the column separator
            let mut style = &table.config.style.top;
            let csw = display_width(table.config.style.row[StyleIdx::Inter as usize]);

            // Detemine column widths of previous and current rows
            let mut ante = vec![full_width];
            let mut post = table.offsets(0, &table.widths, full_width);

            // Obtain ansi sequences requested for the border
            let on = &table.config.border_attr.on;
            let off = &table.config.border_attr.off;

            // This loop renders the entire table
            for (index, row) in table.rows.iter().enumerate() {
                draw(f, style, table.widths.len(), &ante, &post)?;
                style = &table.config.style.sep;
                for i in 0..row.height {
                    let mut remaining = full_width;
                    write!(f, "{}{}{}", on, table.config.style.row[StyleIdx::Left as usize], off)?;
                    for (col, cell) in row.cells.iter().enumerate() {
                        // Determine alignment for this cell
                        let align = table.config.resolve_align(index, col);
                        let horizontal = align.0;
                        let vertical = align.1;

                        // Handle vertical alignment
                        let oob = cell.lines.len();
                        let offset = match vertical {
                            Vertical::Top => 0,
                            Vertical::Centre => row.height / 2 - oob / 2,
                            Vertical::Bottom => row.height - oob,
                        };
                        let i = (i >= offset).then(|| i - offset).unwrap_or(oob);

                        // Determine line and width of line
                        let line: (&str, usize) =
                            if i < cell.lines.len() { (&cell.lines[i].line, cell.lines[i].width) } else { ("", 0) };

                        // Determine the padding required
                        let line_width = line.1;
                        let is_last = col == row.cells.len() - 1;
                        let span = table.widths.len() - row.cells.len();
                        let is_spanning = span > 0 && is_last;

                        let padding = if !is_spanning {
                            let pad = table.widths[col] - line_width;
                            remaining -= line_width + pad;
                            pad
                        } else {
                            remaining - line_width + csw * span
                        };

                        // Horizontal alignment
                        let left = padding / 2;
                        let lr = match horizontal {
                            Horizontal::Left => (0, padding),
                            Horizontal::Centre => (left, padding - left),
                            Horizontal::Right => (padding, 0),
                        };

                        // Render line in cell
                        write!(f, "{}", invert_on(index))?;
                        write!(f, "{}", attr_on(index, col))?;
                        write!(f, "{:width$}", "", width = lr.0)?;
                        write!(f, "{}", line.0)?;
                        write!(f, "{:width$}", "", width = lr.1)?;
                        write!(f, "{}", attr_off(index, col))?;
                        write!(f, "{}", invert_off(index))?;

                        // Handle inner and right hand borders
                        if col < row.cells.len() - 1 {
                            write!(f, "{}{}{}", on, table.config.style.row[StyleIdx::Inter as usize], off)?;
                        } else {
                            writeln!(f, "{}{}{}", on, table.config.style.row[StyleIdx::Right as usize], off)?;
                        }
                    }
                }

                // Derive ante and post for following row
                ante = post;
                post = table.offsets(index + 1, &table.widths, full_width);
            }

            // Draw the outer lower border
            draw(f, &table.config.style.bot, table.widths.len(), &ante, &post)?;
        }
        Ok(())
    }
}