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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
use self::HorizontalAlignment::*;
use crate::cell::*;
use std::cmp::*;
use std::fmt::*;
use std::marker::PhantomData;
use std::ops::Deref;
use unicode_width::UnicodeWidthStr;

/// A data structure that can be formatted into cells.
///
/// The number of columns must be statically determined from the type.
///
/// If the number of columns is dynamically determined, [`GridSchema`] must be used. See [`grid_schema`] for details.
pub trait CellsSource {
    /// Define columns. see [`CellsFormatter`] for details.
    fn fmt(f: &mut CellsFormatter<&Self>);
}
impl CellsSource for () {
    fn fmt(_: &mut CellsFormatter<&Self>) {}
}
impl<T: ?Sized + CellsSource> CellsSource for &T {
    fn fmt(f: &mut CellsFormatter<&Self>) {
        T::fmt(&mut f.map(|x| **x));
    }
}
impl<T: ?Sized + CellsSource> CellsSource for &mut T {
    fn fmt(f: &mut CellsFormatter<&Self>) {
        T::fmt(&mut f.map(|x| **x as &T));
    }
}
impl<T: CellsSource, const N: usize> CellsSource for [T; N] {
    fn fmt(f: &mut CellsFormatter<&Self>) {
        for i in 0..N {
            f.column(i, |x| &x[i]);
        }
    }
}
impl<T: CellsSource> CellsSource for Option<T> {
    fn fmt(f: &mut CellsFormatter<&Self>) {
        f.filter_map(|x| x.as_ref()).content(|x| *x)
    }
}
impl<T: CellsSource, E: CellSource> CellsSource for std::result::Result<T, E> {
    fn fmt(f: &mut CellsFormatter<&Self>) {
        f.ok_with(|f| f.content(|&x| x))
    }
}

/// Column definitions.
///
/// Define columns using [`CellsFormatter`].
///
/// To dynamically create a `GridSchema`, use [`grid_schema`].
///
/// # Examples
/// ```
/// use text_grid::*;
///
/// struct MyGridSchema {
///     len: usize,
/// }
///
/// impl GridSchema for MyGridSchema {
///     type Source = [u32];
///     fn fmt(&self, f: &mut CellsFormatter<&[u32]>) {
///         for i in 0..self.len {
///             f.column(i, |s| s[i]);
///         }
///     }
/// }
///
/// let mut g = Grid::new_with_schema(MyGridSchema { len: 3 });
/// g.push(&[1, 2, 3]);
/// g.push(&[4, 5, 6]);
///
/// assert_eq!(format!("\n{g}"), r#"
///  0 | 1 | 2 |
/// ---|---|---|
///  1 | 2 | 3 |
///  4 | 5 | 6 |
/// "#);
/// ```
pub trait GridSchema {
    type Source: ?Sized;

    /// Define column information. see [`CellsFormatter`] for details.
    fn fmt(&self, f: &mut CellsFormatter<&Self::Source>);
}

impl<T: GridSchema> GridSchema for Vec<T> {
    type Source = T::Source;
    fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
        for s in self {
            s.fmt(f);
        }
    }
}
impl<T: GridSchema> GridSchema for [T] {
    type Source = T::Source;
    fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
        for s in self {
            s.fmt(f);
        }
    }
}
impl<T: ?Sized + GridSchema> GridSchema for &T {
    type Source = T::Source;
    fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
        T::fmt(self, f)
    }
}

/// [`GridSchema`] implementation that use [`CellsSource`].
#[derive(Clone, Copy, Debug)]
pub struct DefaultGridSchema<T: ?Sized>(PhantomData<T>);

impl<T: CellsSource + ?Sized> Default for DefaultGridSchema<T> {
    fn default() -> Self {
        Self(PhantomData)
    }
}
impl<T: CellsSource + ?Sized> GridSchema for DefaultGridSchema<T> {
    type Source = T;
    fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
        T::fmt(f);
    }
}

/// Create [`GridSchema`] from closure.
///
/// # Examples
///
/// By calculating the number of columns at runtime and creating a schema,
/// it is possible to create tables where the number of columns cannot be obtained statically.
///
/// ```rust
/// use text_grid::*;
/// let rows = vec![vec![1, 2, 3], vec![1, 2], vec![1, 2, 3, 4]];
/// let max_colunm_count = rows.iter().map(|r| r.len()).max().unwrap_or(0);
/// let schema = grid_schema::<Vec<u32>>(move |f| {
///     for i in 0..max_colunm_count {
///         f.column(i, |x| x.get(i));
///     }
/// });
/// let mut g = Grid::new_with_schema(schema);
/// g.extend(rows);
/// assert_eq!(format!("\n{g}"), OUTPUT);
///
/// const OUTPUT: &str = r"
///  0 | 1 | 2 | 3 |
/// ---|---|---|---|
///  1 | 2 | 3 |   |
///  1 | 2 |   |   |
///  1 | 2 | 3 | 4 |
/// ";
/// ```
pub fn grid_schema<T: ?Sized>(
    fmt: impl Fn(&mut CellsFormatter<&T>),
) -> impl GridSchema<Source = T> {
    struct FnGridSchema<T: ?Sized, F> {
        fmt: F,
        _phantom: PhantomData<fn(&mut CellsFormatter<&T>)>,
    }

    impl<T: ?Sized, F: Fn(&mut CellsFormatter<&T>)> GridSchema for FnGridSchema<T, F> {
        type Source = T;
        fn fmt(&self, f: &mut CellsFormatter<&T>) {
            (self.fmt)(f)
        }
    }
    FnGridSchema {
        fmt,
        _phantom: PhantomData,
    }
}

/// Used to define columns.
///
/// - Use [`column`](Self::column) to create column.
/// - Use [`column_with`](Self::column_with) to create multi level header.
/// - Use [`content`](Self::content) to create shared header columns.
pub struct CellsFormatter<'a, T> {
    w: &'a mut dyn CellsWrite,
    d: Option<T>,
}

impl<'a, T> CellsFormatter<'a, T> {
    /// Define column group. Used to create multi row header.
    ///
    /// - header : Column group header's cell. If horizontal alignment is not specified, it is set to the center.
    /// - f : A function to define columns in the group.
    ///
    /// # Examples
    ///
    /// ```
    /// use text_grid::*;
    /// struct RowData {
    ///     a: u32,
    ///     b_1: u32,
    ///     b_2: u32,
    /// }
    /// impl CellsSource for RowData {
    ///     fn fmt(f: &mut CellsFormatter<&Self>) {
    ///         f.column("a", |s| s.a);
    ///         f.column_with("b", |f| {
    ///             f.column("1", |s| s.b_1);
    ///             f.column("2", |s| s.b_2);
    ///         });
    ///     }
    /// }
    ///
    /// let mut g = Grid::new();
    /// g.push(&RowData {
    ///     a: 300,
    ///     b_1: 10,
    ///     b_2: 20,
    /// });
    /// g.push(&RowData {
    ///     a: 300,
    ///     b_1: 1,
    ///     b_2: 500,
    /// });
    /// assert_eq!(format!("\n{g}"), r#"
    ///   a  |    b     |
    /// -----|----------|
    ///      | 1  |  2  |
    /// -----|----|-----|
    ///  300 | 10 |  20 |
    ///  300 |  1 | 500 |
    /// "#);
    /// ```
    pub fn column_with(&mut self, header: impl CellSource, f: impl FnOnce(&mut CellsFormatter<T>)) {
        self.w.column_start();
        f(self);
        self.w.column_end(&header);
    }

    /// Define column content. Used to create shared header column.
    ///
    /// - f : A function to obtain cells.
    ///
    /// # Examples
    ///
    /// ```
    /// use text_grid::*;
    /// struct RowData {
    ///     a: u32,
    ///     b_1: u32,
    ///     b_2: u32,
    /// }
    /// impl CellsSource for RowData {
    ///     fn fmt(f: &mut CellsFormatter<&Self>) {
    ///         f.column("a", |s| s.a);
    ///         f.column_with("b", |f| {
    ///             f.content(|s| s.b_1);
    ///             f.content(|_| " ");
    ///             f.content(|s| s.b_2);
    ///         });
    ///     }
    /// }
    ///
    /// let mut g = Grid::new();
    /// g.push(&RowData {
    ///     a: 300,
    ///     b_1: 10,
    ///     b_2: 20,
    /// });
    /// g.push(&RowData {
    ///     a: 300,
    ///     b_1: 1,
    ///     b_2: 500,
    /// });
    /// assert_eq!(format!("\n{g}"), r#"
    ///   a  |   b    |
    /// -----|--------|
    ///  300 | 10  20 |
    ///  300 |  1 500 |
    /// "#);
    /// ```
    pub fn content<U: CellsSource>(&mut self, f: impl FnOnce(&T) -> U) {
        U::fmt(&mut self.map(f).as_ref())
    }

    /// Define column content.
    ///
    /// - f : A function to obtain cell.
    pub(crate) fn content_cell<U: CellSource>(&mut self, f: impl FnOnce(&T) -> U) {
        self.w.content(
            self.d
                .as_ref()
                .map(f)
                .as_ref()
                .map(|x| x as &dyn CellSource),
        );
    }

    /// Define column.
    ///
    /// - header : Column header's cell. If horizontal alignment is not specified, it is set to the center.
    /// - f : A function to obtain cell.
    ///
    /// # Examples
    ///
    /// ```
    /// use text_grid::*;
    /// struct RowData {
    ///     a: u32,
    ///     b: u32,
    /// }
    /// impl CellsSource for RowData {
    ///     fn fmt(f: &mut CellsFormatter<&Self>) {
    ///         f.column("a", |s| s.a);
    ///         f.column("b", |s| s.b);
    ///     }
    /// }
    ///
    /// let mut g = Grid::new();
    /// g.push(&RowData { a: 300, b: 1 });
    /// g.push(&RowData { a: 2, b: 200 });
    /// assert_eq!(format!("\n{g}"), r#"
    ///   a  |  b  |
    /// -----|-----|
    ///  300 |   1 |
    ///    2 | 200 |
    /// "#);
    /// ```
    pub fn column<U: CellsSource>(&mut self, header: impl CellSource, f: impl FnOnce(&T) -> U) {
        self.column_with(header, |cf| cf.content(f));
    }

    /// Creates a [`CellsFormatter`] whose source value was converted.
    pub fn map<'x, U: 'x>(&'x mut self, f: impl FnOnce(&T) -> U) -> CellsFormatter<'x, U> {
        CellsFormatter {
            w: self.w,
            d: self.d.as_ref().map(f),
        }
    }

    /// Creates a [`CellsFormatter`] whose source value was converted to reference.
    pub fn as_ref(&mut self) -> CellsFormatter<&T> {
        CellsFormatter {
            w: self.w,
            d: self.d.as_ref(),
        }
    }

    /// Creates a [`CellsFormatter`] that outputs the body cell only when the source value satisfies the condition.
    pub fn filter(&mut self, f: impl FnOnce(&T) -> bool) -> CellsFormatter<&T> {
        CellsFormatter {
            w: self.w,
            d: self.d.as_ref().filter(|data| f(data)),
        }
    }

    /// Creates a [`CellsFormatter`] that both filters and maps.
    pub fn filter_map<'x, U: 'x>(
        &'x mut self,
        f: impl FnOnce(&T) -> Option<U>,
    ) -> CellsFormatter<'x, U> {
        CellsFormatter {
            w: self.w,
            d: self.d.as_ref().and_then(f),
        }
    }

    /// Apply `f` to self.
    pub fn with(&mut self, f: impl Fn(&mut Self)) {
        f(self);
    }
}
impl<T, E: CellSource> CellsFormatter<'_, std::result::Result<T, E>> {
    /// If `Ok`, output the cells defined by `f`. If `Err`, output the cell by the error value using the colspan of the cells output by `f`.
    pub fn ok_with(&mut self, f: impl FnOnce(&mut CellsFormatter<&T>)) {
        if let Some(Err(_)) = &self.d {
            self.w.content_start();
        }
        f(&mut self.as_ref().filter_map(|&x| x.as_ref().ok()));
        if let Some(Err(e)) = &self.d {
            self.w.content_end(e);
        }
    }
}
impl<T, E: CellSource> CellsFormatter<'_, &'_ std::result::Result<T, E>> {
    /// If `Ok`, output the cells defined by `f`. If `Err`, output the cell by the error value using the colspan of the cells output by `f`.
    pub fn ok_with(&mut self, f: impl FnOnce(&mut CellsFormatter<&T>)) {
        if let Some(Err(_)) = &self.d {
            self.w.content_start();
        }
        f(&mut self.as_ref().filter_map(|&x| x.as_ref().ok()));
        if let Some(Err(e)) = &self.d {
            self.w.content_end(e);
        }
    }
}

trait CellsWrite {
    fn content(&mut self, cell: Option<&dyn CellSource>);
    fn content_start(&mut self);
    fn content_end(&mut self, cell: &dyn CellSource);
    fn column_start(&mut self);
    fn column_end(&mut self, header: &dyn CellSource);
}

pub(crate) struct GridLayout {
    pub depth: usize,
    pub depth_max: usize,
    pub separators: Vec<bool>,
}
impl GridLayout {
    pub fn from_schema<T: ?Sized>(schema: &dyn GridSchema<Source = T>) -> Self {
        let mut this = GridLayout::new();
        schema.fmt(&mut CellsFormatter {
            w: &mut this,
            d: None,
        });
        this.separators.pop();
        this
    }
    fn new() -> Self {
        Self {
            depth: 0,
            depth_max: 0,
            separators: Vec::new(),
        }
    }
    fn set_separator(&mut self) {
        if let Some(last) = self.separators.last_mut() {
            *last = true;
        }
    }
}
impl CellsWrite for GridLayout {
    fn content(&mut self, _cell: Option<&dyn CellSource>) {
        self.separators.push(false);
    }
    fn content_start(&mut self) {}
    fn content_end(&mut self, _cell: &dyn CellSource) {}
    fn column_start(&mut self) {
        self.set_separator();
        self.depth += 1;
        self.depth_max = max(self.depth_max, self.depth);
    }

    fn column_end(&mut self, _header: &dyn CellSource) {
        self.depth -= 1;
        self.set_separator()
    }
}

struct HeaderWriter<'a, 'b> {
    b: &'a mut RowBuilder<'b>,
    depth: usize,
    target: usize,
    column: usize,
    column_last: usize,
}
impl<'a, 'b> HeaderWriter<'a, 'b> {
    fn new(b: &'a mut RowBuilder<'b>, target: usize) -> Self {
        Self {
            b,
            depth: 0,
            target,
            column: 0,
            column_last: 0,
        }
    }

    fn push_cell(&mut self, cell: impl CellSource) {
        let colspan = self.column - self.column_last;
        self.b.push_with_colspan(cell, colspan);
        self.column_last = self.column;
    }
}
impl CellsWrite for HeaderWriter<'_, '_> {
    fn content(&mut self, _cell: Option<&dyn CellSource>) {
        self.column += 1;
    }
    fn content_start(&mut self) {}
    fn content_end(&mut self, _cell: &dyn CellSource) {}
    fn column_start(&mut self) {
        if self.depth <= self.target {
            self.push_cell(Cell::empty());
        }
        self.depth += 1;
    }
    fn column_end(&mut self, header: &dyn CellSource) {
        self.depth -= 1;
        if self.depth == self.target {
            let style = CellStyle {
                align_h: Some(HorizontalAlignment::Center),
            };
            let header = Cell::new(header).with_base_style(style);
            self.push_cell(header);
        }
    }
}
impl Drop for HeaderWriter<'_, '_> {
    fn drop(&mut self) {
        self.push_cell("");
    }
}
struct BodyWriter<'a, 'b> {
    b: &'a mut RowBuilder<'b>,
    colspan: Option<usize>,
}

impl<'a, 'b> BodyWriter<'a, 'b> {
    fn new(b: &'a mut RowBuilder<'b>) -> Self {
        Self { b, colspan: None }
    }
}

impl CellsWrite for BodyWriter<'_, '_> {
    fn content(&mut self, cell: Option<&dyn CellSource>) {
        if let Some(colspan) = &mut self.colspan {
            *colspan += 1;
        } else {
            self.b.push(cell);
        }
    }
    fn content_start(&mut self) {
        assert!(self.colspan.is_none());
        self.colspan = Some(0);
    }
    fn content_end(&mut self, cell: &dyn CellSource) {
        let colspan = self.colspan.take().unwrap();
        self.b.push_with_colspan(cell, colspan);
    }

    fn column_start(&mut self) {}
    fn column_end(&mut self, _header: &dyn CellSource) {}
}

/// A builder used to create plain-text table.
///
/// # Examples
/// ```rust
/// use text_grid::*;
/// let mut g = GridBuilder::new();
/// g.push(|b| {
///     b.push(cell("name").right());
///     b.push("type");
///     b.push("value");
/// });
/// g.push_separator();
/// g.push(|b| {
///     b.push(cell(String::from("X")).right());
///     b.push("A");
///     b.push(10);
/// });
/// g.push(|b| {
///     b.push(cell("Y").right());
///     b.push_with_colspan(cell("BBB").center(), 2);
/// });
/// assert_eq!(format!("\n{g}"), r#"
///  name | type | value |
/// ------|------|-------|
///     X | A    |    10 |
///     Y |     BBB      |
/// "#);
/// ```
#[derive(Default)]
pub struct GridBuilder {
    s: String,
    cells: Vec<CellEntry>,
    rows: Vec<RowEntry>,
    columns: usize,
    column_separators: Vec<bool>,
}

struct CellEntry {
    s_idx: usize,
    width: usize,
    colspan: usize,
    style: CellStyle,
}
struct RowEntry {
    cells_idx: usize,
    has_separator: bool,
}

impl GridBuilder {
    /// Create a new `GridBuilder`.
    pub fn new() -> Self {
        GridBuilder {
            s: String::new(),
            cells: Vec::new(),
            rows: Vec::new(),
            columns: 0,
            column_separators: Vec::new(),
        }
    }

    pub(crate) fn new_with_header<T: ?Sized>(schema: &dyn GridSchema<Source = T>) -> Self {
        let mut this = Self::new();
        let layout = GridLayout::from_schema(schema);
        this.set_column_separators(layout.separators);
        for target in 0..layout.depth_max {
            this.push(|b| {
                schema.fmt(&mut CellsFormatter {
                    w: &mut HeaderWriter::new(b, target),
                    d: None,
                })
            });
            this.push_separator();
        }
        this
    }

    /// Set column separator's visibility.
    ///
    /// `separators[0]` indicate visibility of the right side of the leftmost column.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use text_grid::*;
    /// let mut g = GridBuilder::new();
    /// g.push(|b| {
    ///     b.push("A");
    ///     b.push("B");
    ///     b.push("C");
    /// });
    /// g.push(|b| {
    ///     b.push("AAA");
    ///     b.push("BBB");
    ///     b.push("CCC");
    /// });
    /// g.set_column_separators(vec![true, true]);
    /// assert_eq!(format!("\n{g}"), r#"
    ///  A   | B   | C   |
    ///  AAA | BBB | CCC |
    /// "#);
    ///
    /// g.set_column_separators(vec![false, true]);
    /// assert_eq!(format!("\n{g}"), r#"
    ///  A  B   | C   |
    ///  AAABBB | CCC |
    /// "#);
    pub fn set_column_separators(&mut self, separators: Vec<bool>) {
        self.column_separators = separators;
    }

    /// Append a row to the bottom of the grid.
    pub fn push(&mut self, f: impl FnOnce(&mut RowBuilder)) {
        let cells_idx = self.cells.len();
        f(&mut RowBuilder {
            grid: self,
            cells_idx,
        })
    }

    /// Append a row separator to the bottom of the grid.
    pub fn push_separator(&mut self) {
        if let Some(row) = self.rows.last_mut() {
            row.has_separator = true;
        }
    }

    fn push_cell<S: CellSource>(&mut self, cell: S, colspan: usize) {
        let s_idx = self.s.len();
        cell.fmt(&mut self.s);
        self.cells.push(CellEntry {
            s_idx,
            width: self.s[s_idx..].width(),
            colspan,
            style: cell.style().or(cell.style_for_body()),
        });
    }
    fn get_width(&self, widths: &[usize], column: usize, colspan: usize) -> usize {
        assert!(colspan >= 1);
        let mut result = widths[column];
        for i in 1..colspan {
            if self.has_border(column + i) {
                result += 3;
            }
            result += widths[column + i];
        }
        result
    }
    fn has_border(&self, n: usize) -> bool {
        if n == 0 {
            false
        } else if n == self.columns {
            true
        } else if let Some(&value) = self.column_separators.get(n - 1) {
            value
        } else {
            true
        }
    }
    fn has_left_padding(&self, n: usize) -> bool {
        if n == 0 {
            true
        } else {
            self.has_border(n)
        }
    }
    fn has_right_padding(&self, n: usize) -> bool {
        if n == self.columns {
            true
        } else {
            self.has_border(n + 1)
        }
    }

    fn get_widths(&self) -> Vec<usize> {
        let mut widths = vec![0; self.columns];
        for row in 0..self.rows.len() {
            for c in self.row(row) {
                if c.colspan == 1 {
                    widths[c.column] = max(widths[c.column], c.width);
                }
            }
        }
        let mut smalls = Vec::new();
        for row in 0..self.rows.len() {
            for c in self.row(row) {
                if c.colspan > 1 {
                    let mut width_sum = self.get_width(&widths, c.column, c.colspan);
                    while width_sum < c.width {
                        smalls.clear();
                        smalls.push(0);
                        let mut min_width = widths[c.column];
                        let mut next_width = usize::max_value();
                        for i in 1..c.colspan {
                            let width = widths[c.column + i];
                            if width < min_width {
                                smalls.clear();
                                next_width = min_width;
                                min_width = width;
                            }
                            if width == min_width {
                                smalls.push(i);
                            }
                        }
                        for i in 0..smalls.len() {
                            let count = smalls.len() - i;
                            let expand_width_all = c.width - width_sum;
                            let expand_width = (expand_width_all + count - 1) / count;
                            let expand_width = min(expand_width, next_width - min_width);
                            width_sum += expand_width;
                            widths[c.column + smalls[i]] += expand_width;
                        }
                    }
                }
            }
        }
        widths
    }
    fn row(&self, row: usize) -> Cursor {
        Cursor {
            grid: self,
            column: 0,
            idx: self.cells_idx(row),
            end: self.cells_idx(row + 1),
        }
    }
    fn cells_idx(&self, row: usize) -> usize {
        if let Some(row) = self.rows.get(row) {
            row.cells_idx
        } else {
            self.cells.len()
        }
    }
    fn s_idx(&self, cells_idx: usize) -> usize {
        if let Some(cell) = self.cells.get(cells_idx) {
            cell.s_idx
        } else {
            self.s.len()
        }
    }
}

impl Display for GridBuilder {
    fn fmt(&self, f: &mut Formatter) -> Result {
        let widths = self.get_widths();
        for row in 0..self.rows.len() {
            if self.has_border(0) {
                write!(f, "|")?;
            }
            for c in self.row(row) {
                let width = self.get_width(&widths, c.column, c.colspan);
                if self.has_left_padding(c.column) {
                    write!(f, " ")?;
                }
                let p = width - c.width;
                match c.style.align_h.unwrap_or(Left) {
                    Left => write!(f, "{0}{1:<p$}", c.s, "", p = p),
                    Right => write!(f, "{1:<p$}{0}", c.s, "", p = p),
                    Center => {
                        let lp = p / 2;
                        let rp = p - lp;
                        write!(f, "{1:<lp$}{0}{1:<rp$}", c.s, "", lp = lp, rp = rp)
                    }
                }?;
                if self.has_right_padding(c.column + c.colspan - 1) {
                    write!(f, " ")?;
                }
                if self.has_border(c.column + c.colspan) {
                    write!(f, "|")?;
                }
            }
            writeln!(f)?;
            if self.rows[row].has_separator {
                let mut cs = [self.row(row), self.row(row + 1)];
                for (column, _) in widths.iter().enumerate() {
                    if self.has_left_padding(column) {
                        write!(f, "-")?;
                    }
                    write!(f, "{:-<f$}", "", f = widths[column])?;
                    if self.has_right_padding(column) {
                        write!(f, "-")?;
                    }
                    for c in cs.iter_mut() {
                        while c.column <= column && c.next().is_some() {}
                    }
                    if self.has_border(column + 1) {
                        if cs.iter().all(|x| x.column == column + 1) {
                            write!(f, "|")?;
                        } else {
                            write!(f, "-")?;
                        }
                    }
                }
                writeln!(f)?;
            }
        }
        Ok(())
    }
}
impl Debug for GridBuilder {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Display::fmt(self, f)
    }
}

/// A builder used to create row of [`GridBuilder`].
///
/// This structure is created by [`GridBuilder::push`].
pub struct RowBuilder<'a> {
    grid: &'a mut GridBuilder,
    cells_idx: usize,
}

impl RowBuilder<'_> {
    /// Append a cell to the right of row.
    pub fn push(&mut self, cell: impl CellSource) {
        self.grid.push_cell(cell, 1);
    }

    /// Append a multi-column cell to the right of row.
    ///
    /// - `cell` : Contents of cell to be appended.
    /// - `colspan` : Number of columns used by the cell to be appended.
    ///
    /// if `colspan == 0`, this method will do nothing.
    pub fn push_with_colspan(&mut self, cell: impl CellSource, colspan: usize) {
        if colspan != 0 {
            self.grid.push_cell(cell, colspan);
        }
    }

    pub fn extend<T: ?Sized + CellsSource>(&mut self, source: &T) {
        T::fmt(&mut CellsFormatter {
            w: &mut BodyWriter::new(self),
            d: Some(source),
        })
    }
    pub fn extend_with_schema<T: ?Sized>(
        &mut self,
        source: &T,
        schema: &dyn GridSchema<Source = T>,
    ) {
        schema.fmt(&mut CellsFormatter {
            w: &mut BodyWriter::new(self),
            d: Some(source),
        })
    }
}
impl Drop for RowBuilder<'_> {
    fn drop(&mut self) {
        self.grid.columns = max(self.grid.columns, self.grid.cells.len() - self.cells_idx);
        self.grid.rows.push(RowEntry {
            cells_idx: self.cells_idx,
            has_separator: false,
        });
    }
}

struct Cursor<'a> {
    grid: &'a GridBuilder,
    column: usize,
    idx: usize,
    end: usize,
}
impl<'a> Iterator for Cursor<'a> {
    type Item = CellRef<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.idx == self.end {
            None
        } else {
            let g = self.grid;
            let r = CellRef {
                cell: &g.cells[self.idx],
                s: &g.s[g.s_idx(self.idx)..g.s_idx(self.idx + 1)],
                column: self.column,
            };
            self.column += r.colspan;
            self.idx += 1;
            Some(r)
        }
    }
}

struct CellRef<'a> {
    cell: &'a CellEntry,
    s: &'a str,
    column: usize,
}
impl<'a> Deref for CellRef<'a> {
    type Target = &'a CellEntry;
    fn deref(&self) -> &Self::Target {
        &self.cell
    }
}

macro_rules! impl_for_tuple {
    ($($idx:tt : $ty:ident,)*) => {
        impl<$($ty),*> CellsSource for ($($ty,)*) where $($ty: CellsSource),* {
            fn fmt(f: &mut CellsFormatter<&Self>) {
                $(
                    $ty::fmt(&mut f.map(|x| &x.$idx));
                )*
            }
        }

        impl<$($ty),*> GridSchema for ($($ty,)*)
        where
            $($ty: GridSchema, $ty::Source: Sized,)*
        {
            type Source = ($($ty::Source,)*);
            fn fmt(&self, f: &mut CellsFormatter<&Self::Source>) {
                $(self.$idx.fmt(&mut f.map(|&x| &x.$idx));)*
            }
        }
    };
}
impl_for_tuple!(0: T0,);
impl_for_tuple!(0: T0, 1: T1,);
impl_for_tuple!(0: T0, 1: T1, 2: T2,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5, 6: T6,);
impl_for_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5, 6: T6, 7: T7,);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
    9: T9,
);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
    9: T9,
    10: T10,
);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
    9: T9,
    10: T10,
    11: T11,
);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
    9: T9,
    10: T10,
    11: T11,
    12: T12,
);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
    9: T9,
    10: T10,
    11: T11,
    12: T12,
    13: T13,
);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
    9: T9,
    10: T10,
    11: T11,
    12: T12,
    13: T13,
    14: T14,
);
impl_for_tuple!(
    0: T0,
    1: T1,
    2: T2,
    3: T3,
    4: T4,
    5: T5,
    6: T6,
    7: T7,
    8: T8,
    9: T9,
    10: T10,
    11: T11,
    12: T12,
    13: T13,
    14: T14,
    15: T15,
);