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
use std::marker::PhantomData;

use crate::{CellsFormatter, RawCell};

/// 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, [`CellsSchema`] must be used. See [`cells_schema`] for details.
pub trait Cells {
    /// Define columns. see [`CellsFormatter`] for details.
    fn fmt(f: &mut CellsFormatter<Self>);
}
impl Cells for () {
    fn fmt(_: &mut CellsFormatter<Self>) {}
}
impl<T: ?Sized + Cells> Cells for &T {
    fn fmt(f: &mut CellsFormatter<Self>) {
        T::fmt(&mut f.unref());
    }
}
impl<T: ?Sized + Cells> Cells for &mut T {
    fn fmt(f: &mut CellsFormatter<Self>) {
        T::fmt(&mut f.unref());
    }
}
impl<T: Cells, const N: usize> Cells for [T; N] {
    fn fmt(f: &mut CellsFormatter<Self>) {
        for i in 0..N {
            f.column(i, |x| &x[i]);
        }
    }
}
impl<T: Cells> Cells for Option<T> {
    fn fmt(f: &mut CellsFormatter<Self>) {
        f.filter_map(|x| x.as_ref()).content(|x| x)
    }
}
impl<T: Cells, E: RawCell> Cells for std::result::Result<T, E> {
    fn fmt(f: &mut CellsFormatter<Self>) {
        f.try_map_with(|x| x.as_ref(), |f| T::fmt(&mut f.unref()));
    }
}

/// Column definitions.
///
/// Define columns using [`CellsFormatter`].
///
/// To dynamically create a `CellsSchema`, use [`cells_schema`].
///
/// # Examples
/// ```
/// use text_grid::*;
///
/// struct MyCellsSchema {
///     len: usize,
/// }
///
/// impl CellsSchema for MyCellsSchema {
///     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::with_schema(MyCellsSchema { 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 CellsSchema {
    type Source: ?Sized;

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

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

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

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

/// Create [`CellsSchema`] 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 = cells_schema::<Vec<u32>>(move |f| {
///     for i in 0..max_colunm_count {
///         f.column(i, |x| x.get(i));
///     }
/// });
/// let mut g = Grid::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 cells_schema<T: ?Sized>(
    fmt: impl Fn(&mut CellsFormatter<T>),
) -> impl CellsSchema<Source = T> {
    struct FnCellsSchema<T: ?Sized, F> {
        fmt: F,
        _phantom: PhantomData<fn(&mut CellsFormatter<T>)>,
    }

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

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

        impl<$($ty),*> CellsSchema for ($($ty,)*)
        where
            $($ty: CellsSchema, $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,
);