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
use crate::cell::*;
use crate::grid_buf::*;
use crate::row_write::*;
use std::cmp::max;
use std::fmt::*;
use std::marker::PhantomData;

/// A data structure that can be formatted into row.
pub trait RowSource {
    /// Define column informations. see [`RowWrite`] for details.
    fn fmt_row<'a>(w: &mut impl RowWrite<Source = &'a Self>)
    where
        Self: 'a;
}

/// Columns definition.
///
/// # Examples
/// ```
/// use text_grid::*;
///
/// struct MyGridSchema {
///     len: usize,
/// }
///
/// impl GridSchema<[u32]> for MyGridSchema {
///     fn fmt_row<'a>(&self, w: &mut impl RowWrite<Source = &'a [u32]>) {
///         for i in 0..self.len {
///             w.column(i, |s| s[i]);
///         }
///     }
/// }
///
/// let mut g = Grid::new_with_schema(MyGridSchema { len: 3 });
/// g.push_row(&[1, 2, 3]);
/// g.push_row(&[4, 5, 6]);
///
/// print!("{}", g);
/// ```
/// Output:
/// ```text
///  0 | 1 | 2 |
/// ---|---|---|
///  1 | 2 | 3 |
///  4 | 5 | 6 |
/// ```
pub trait GridSchema<R: ?Sized> {
    /// Define column informations. see [`RowWrite`] for details.
    fn fmt_row<'a>(&self, w: &mut impl RowWrite<Source = &'a R>)
    where
        R: 'a;
}

/// [`GridSchema`] implementation that use [`RowSource`].
pub struct RowSourceGridSchema;
impl<R: RowSource + ?Sized> GridSchema<R> for RowSourceGridSchema {
    fn fmt_row<'a>(&self, w: &mut impl RowWrite<Source = &'a R>)
    where
        R: 'a,
    {
        R::fmt_row(w);
    }
}

/// A builder used to create plain-text table from values.
///
/// # Examples
///
/// ```
/// use text_grid::*;
/// struct RowData {
///     a: u32,
///     b: u32,
/// }
/// impl RowSource for RowData {
///     fn fmt_row<'a>(w: &mut impl RowWrite<Source=&'a Self>) {
///         w.column("a", |s| s.a);
///         w.column("b", |s| s.b);
///     }
/// }
///
/// let mut g = Grid::new();
/// g.push_row(&RowData { a: 300, b: 1 });
/// g.push_row(&RowData { a: 2, b: 200 });
///
/// print!("{}", g);
/// ```
///
/// Output:
/// ```text
///   a  |  b  |
/// -----|-----|
///  300 |   1 |
///    2 | 200 |
/// ```
pub struct Grid<R: ?Sized, S> {
    buf: GridBuf,
    schema: S,
    _phantom: PhantomData<Fn(&R)>,
}

impl<R: RowSource + ?Sized> Grid<R, RowSourceGridSchema> {
    /// Create a new `Grid` with [`RowSourceGridSchema`] and prepare header rows.
    pub fn new() -> Self {
        Self::new_with_schema(RowSourceGridSchema)
    }
}

impl<R: ?Sized, S: GridSchema<R>> Grid<R, S> {
    /// Create a new `Grid` with specified schema and prepare header rows.
    pub fn new_with_schema(schema: S) -> Self {
        let mut layout = LayoutWriter::new();
        schema.fmt_row(&mut layout);
        layout.separators.pop();

        let mut buf = GridBuf::new();
        buf.set_column_separators(layout.separators);

        for target in 0..layout.depth_max {
            schema.fmt_row(&mut HeaderWriter::new(buf.push_row(), target));
            buf.push_separator();
        }
        Grid {
            buf,
            schema,
            _phantom: PhantomData::default(),
        }
    }
}
impl<R: ?Sized, S: GridSchema<R>> Grid<R, S> {
    /// Append a row to the bottom of the grid.
    pub fn push_row(&mut self, source: &R) {
        let mut writer = RowWriter {
            source,
            row: self.buf.push_row(),
        };
        self.schema.fmt_row(&mut writer);
    }

    /// Append a row separator to the bottom of the grid.
    pub fn push_separator(&mut self) {
        self.buf.push_separator();
    }
}
impl<R: ?Sized, S> Display for Grid<R, S> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Display::fmt(&self.buf, f)
    }
}
impl<R: ?Sized, S> Debug for Grid<R, S> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(&self.buf, f)
    }
}

struct LayoutWriter<S> {
    depth: usize,
    depth_max: usize,
    separators: Vec<bool>,
    _phantom: PhantomData<Fn(S)>,
}
impl<S> LayoutWriter<S> {
    fn new() -> Self {
        LayoutWriter {
            depth: 0,
            depth_max: 0,
            separators: Vec::new(),
            _phantom: PhantomData::default(),
        }
    }
    fn set_separator(&mut self) {
        if let Some(last) = self.separators.last_mut() {
            *last = true;
        }
    }
}
impl<S> RowWrite for LayoutWriter<S> {
    type Source = S;
    fn content<T: CellSource>(&mut self, _f: impl FnOnce(S) -> T) {
        assert!(self.depth != 0);
        self.separators.push(false);
    }
}
impl<S> RowWriteCore for LayoutWriter<S> {
    fn group_start(&mut self) {
        self.set_separator();
        self.depth += 1;
        self.depth_max = max(self.depth_max, self.depth);
    }
    fn group_end(&mut self, _header: impl CellSource) {
        self.depth -= 1;
        self.set_separator()
    }
}

struct HeaderWriter<'a, S: ?Sized> {
    row: RowBuf<'a>,
    depth: usize,
    target: usize,
    column: usize,
    column_last: usize,
    _phantom: PhantomData<Fn(S)>,
}
impl<'a, S: ?Sized> HeaderWriter<'a, S> {
    fn new(row: RowBuf<'a>, target: usize) -> Self {
        HeaderWriter {
            row,
            depth: 0,
            target,
            column: 0,
            column_last: 0,
            _phantom: PhantomData::default(),
        }
    }
    fn push_cell(&mut self, cell: impl CellSource) {
        let colspan = self.column - self.column_last;
        self.row.push_with_colspan(cell, colspan);
        self.column_last = self.column;
    }
}
impl<'a, S: ?Sized> Drop for HeaderWriter<'a, S> {
    fn drop(&mut self) {
        self.push_cell("");
    }
}

impl<'a, S: 'a + ?Sized> RowWrite for HeaderWriter<'a, S> {
    type Source = &'a S;
    fn content<T: CellSource>(&mut self, _f: impl FnOnce(Self::Source) -> T) {
        assert!(self.depth != 0);
        self.column += 1;
    }
}
impl<'a, S: 'a + ?Sized> RowWriteCore for HeaderWriter<'a, S> {
    fn group_start(&mut self) {
        if self.depth <= self.target {
            self.push_cell(Cell::empty());
        }
        self.depth += 1;
    }
    fn group_end(&mut self, header: impl CellSource) {
        self.depth -= 1;
        if self.depth == self.target {
            let mut style = CellStyle::default();
            style.align_h = Some(HorizontalAlignment::Center);

            let header = Cell::new(header).with_base_style(style);
            self.push_cell(header);
        }
    }
}

struct RowWriter<'a, R: ?Sized> {
    source: &'a R,
    row: RowBuf<'a>,
}
impl<'a, R: ?Sized> RowWrite for RowWriter<'a, R> {
    type Source = &'a R;
    fn content<T: CellSource>(&mut self, f: impl FnOnce(Self::Source) -> T) {
        self.row.push(f(self.source));
    }
}
impl<'a, R: ?Sized> RowWriteCore for RowWriter<'a, R> {
    fn group_start(&mut self) {}
    fn group_end(&mut self, _header: impl CellSource) {}
}