tabled 0.20.0

An easy to use library for pretty print tables of Rust `struct`s and `enum`s.
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
//! This module contains a [`Split`] setting which is used to
//! format the cells of a [`Table`] by a provided index, direction, behavior, and display preference.
//!
//! [`Table`]: crate::Table

use core::ops::Range;

use crate::grid::{
    config::Position,
    records::{ExactRecords, PeekableRecords, Records, Resizable},
};

use super::TableOption;

#[derive(Debug, Clone, Copy)]
enum Direction {
    Column,
    Row,
}

#[derive(Debug, Clone, Copy)]
enum Behavior {
    Concat,
    Zip,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum Display {
    Clean,
    Retain,
}

/// Returns a new [`Table`] formatted with several optional parameters.
///
/// The required index parameter determines how many columns/rows a table will be redistributed into.
///
/// - index
/// - direction
/// - behavior
/// - display
///
/// #### Directions
///
/// Direction functions are the entry point for the `Split` setting.
///
/// There are two directions available: `column` and `row`.
///
/// ```rust
/// use std::iter::FromIterator;
/// use tabled::{Table, settings::split::Split};
///
/// let mut table = Table::from_iter(['a'..='z']);
/// table.with(Split::column(12));
/// table.with(Split::row(2));
/// ```
///
/// ```text
/// ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
/// │ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │ m │ n │ o │ p │ q │ r │ s │ t │ u │ v │ w │ x │ y │ z │
/// └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
/// ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
/// │ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │
/// ├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┤
/// │ m │ n │ o │ p │ q │ r │ s │ t │ u │ v │ w │ x │
/// ├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┤
/// │ y │ z │   │   │   │   │   │   │   │   │   │   │<- y and z act as anchors to new empty cells
/// └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘   to conform to the new shape
/// ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
/// │ a │ y │ b │ z │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │
/// ├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┤<- Display::Clean removes empty cells that would be anchors otherwise
/// │ m │   │ n │   │ o │ p │ q │ r │ s │ t │ u │ v │ w │ x │
/// └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
///       ^anchors^
/// ```
///
///
/// #### Behaviors
///
/// Behaviors determine how cells attempt to conform to the new tables shape.
///
/// There are two behaviors available: `zip` and `concat`.
///
/// `zip` is the default behavior.
///
/// ```rust
/// use std::iter::FromIterator;
/// use tabled::{Table, settings::split::Split};
///
/// let mut table = Table::from_iter(['a'..='z']);
/// table.with(Split::column(2).concat());
/// table.with(Split::column(2).zip());
/// ```
///
/// ```text
///                                                 +---+---+
///                                                 | a | b |
///                                                 +---+---+
/// +---+---+---+---+---+                           | f | g |
/// | a | b | c | d | e | Split::column(2).concat() +---+---+
/// +---+---+---+---+---+           =>              | c | d |
/// | f | g | h | i | j |                           +---+---+
/// +---+---+---+---+---+                           | h | i |
///                                                 +---+---+
///                                                 | e |   |
///                                                 +---+---+
///                                                 | j |   |
///                                                 +---+---+
///
///                   sect 3                        +---+---+
///  sect 1   sect 2 (anchors)                      | a | b |
///   /   \   /   \   /   \                         +---+---+
/// +---+---+---+---+---+                           | c | d |
/// | a | b | c | d | e |  Split::column(2).zip()   +---+---+
/// +---+---+---+---+---+           =>              | e |   |
/// | f | g | h | i | j |                           +---+---+
/// +---+---+---+---+---+                           | f | g |
///                                                 +---+---+
///                                                 | h | i |
///                                                 +---+---+
///                                                 | j |   |
///                                                 +---+---+
/// ```
///
/// #### Displays
///
/// Display functions give the user the choice to `retain` or `clean` empty sections in a `Split` table result.
///
/// - `retain` does not filter any existing or newly added cells when conforming to a new shape.
///
/// - `clean` filters out empty columns/rows from the output and prevents empty cells from acting as anchors to newly inserted cells.
///
/// `clean` is the default `Display`.
///
/// ```rust
/// use std::iter::FromIterator;
/// use tabled::{
///     settings::{split::Split, style::Style},
///     Table,
/// };
/// let mut table = Table::from_iter(['a'..='z']);
/// table.with(Split::column(25)).with(Style::modern());
/// table.clone().with(Split::column(1).concat().retain());
/// table.clone().with(Split::column(1).concat()); // .clean() is not necessary as it is the default display property
/// ```
///
/// ```text
/// ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
/// │ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │ m │ n │ o │ p │ q │ r │ s │ t │ u │ v │ w │ x │ y │
/// ├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┤
/// │ z │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │   │<- lots of extra cells generated
/// └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
/// ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┐
/// │ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │ m │ n │ o │ p │ q │ r │ s │ t │ u │ v │ w │ x │ y │ z │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │  │
/// └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘
/// ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ ^ cells retained during concatenation
/// │ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │ m │ n │ o │ p │ q │ r │ s │ t │ u │ v │ w │ x │ y │ z │
/// └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘<- cells removed during concatenation
/// ```
///
///
/// # Example
///
/// ```rust
/// use std::iter::FromIterator;
/// use tabled::{
///     settings::split::Split,
///     Table,
/// };
///
/// let mut table = Table::from_iter(['a'..='z']);
/// let table = table.with(Split::column(4)).to_string();
///
/// assert_eq!(table, "+---+---+---+---+\n\
///                    | a | b | c | d |\n\
///                    +---+---+---+---+\n\
///                    | e | f | g | h |\n\
///                    +---+---+---+---+\n\
///                    | i | j | k | l |\n\
///                    +---+---+---+---+\n\
///                    | m | n | o | p |\n\
///                    +---+---+---+---+\n\
///                    | q | r | s | t |\n\
///                    +---+---+---+---+\n\
///                    | u | v | w | x |\n\
///                    +---+---+---+---+\n\
///                    | y | z |   |   |\n\
///                    +---+---+---+---+")
/// ```
///
/// [`Table`]: crate::Table
#[derive(Debug, Clone, Copy)]
pub struct Split {
    direction: Direction,
    behavior: Behavior,
    display: Display,
    index: usize,
}

impl Split {
    /// Returns a new [`Table`] split on the column at the provided index.
    ///
    /// The column found at that index becomes the new right-most column in the returned table.
    /// Columns found beyond the index are redistributed into the table based on other defined
    /// parameters.
    ///
    /// ```rust,no_run
    /// # use tabled::settings::split::Split;
    /// Split::column(4);
    /// ```
    ///
    /// [`Table`]: crate::Table
    pub fn column(index: usize) -> Self {
        Split {
            direction: Direction::Column,
            behavior: Behavior::Zip,
            display: Display::Clean,
            index,
        }
    }

    /// Returns a new [`Table`] split on the row at the provided index.
    ///
    /// The row found at that index becomes the new bottom row in the returned table.
    /// Rows found beyond the index are redistributed into the table based on other defined
    /// parameters.
    ///
    /// ```rust,no_run
    /// # use tabled::settings::split::Split;
    /// Split::row(4);
    /// ```
    ///
    /// [`Table`]: crate::Table
    pub fn row(index: usize) -> Self {
        Split {
            direction: Direction::Row,
            behavior: Behavior::Zip,
            display: Display::Clean,
            index,
        }
    }

    /// Returns a split [`Table`] with the redistributed cells pushed to the back of the new shape.
    ///
    /// ```text
    ///                                                 +---+---+
    ///                                                 | a | b |
    ///                                                 +---+---+
    /// +---+---+---+---+---+                           | f | g |
    /// | a | b | c | d | e | Split::column(2).concat() +---+---+
    /// +---+---+---+---+---+           =>              | c | d |
    /// | f | g | h | i | j |                           +---+---+
    /// +---+---+---+---+---+                           | h | i |
    ///                                                 +---+---+
    ///                                                 | e |   |
    ///                                                 +---+---+
    ///                                                 | j |   |
    ///                                                 +---+---+
    /// ```
    ///
    /// [`Table`]: crate::Table
    pub fn concat(self) -> Self {
        Self {
            behavior: Behavior::Concat,
            ..self
        }
    }

    /// Returns a split [`Table`] with the redistributed cells inserted behind
    /// the first correlating column/row one after another.
    ///
    /// ```text
    ///                                              +---+---+
    ///                                              | a | b |
    ///                                              +---+---+
    /// +---+---+---+---+---+                        | c | d |
    /// | a | b | c | d | e | Split::column(2).zip() +---+---+
    /// +---+---+---+---+---+           =>           | e |   |
    /// | f | g | h | i | j |                        +---+---+
    /// +---+---+---+---+---+                        | f | g |
    ///                                              +---+---+
    ///                                              | h | i |
    ///                                              +---+---+
    ///                                              | j |   |
    ///                                              +---+---+
    /// ```
    ///
    /// [`Table`]: crate::Table
    pub fn zip(self) -> Self {
        Self {
            behavior: Behavior::Zip,
            ..self
        }
    }

    /// Returns a split [`Table`] with the empty columns/rows filtered out.
    ///
    /// ```text
    ///                                                
    ///                                                
    ///                                                +---+---+---+
    /// +---+---+---+---+---+                          | a | b | c |
    /// | a | b | c | d | e | Split::column(3).clean() +---+---+---+
    /// +---+---+---+---+---+           =>             | d | e |   |
    /// | f | g | h |   |   |                          +---+---+---+
    /// +---+---+---+---+---+                          | f | g | h |
    ///               ^   ^                            +---+---+---+
    ///               these cells are filtered
    ///               from the resulting table
    /// ```
    ///
    /// ## Notes
    ///
    /// This is apart of the default configuration for Split.
    ///
    /// See [`retain`] for an alternative display option.
    ///
    /// [`Table`]: crate::Table
    /// [`retain`]: crate::settings::split::Split::retain
    pub fn clean(self) -> Self {
        Self {
            display: Display::Clean,
            ..self
        }
    }

    /// Returns a split [`Table`] with all cells retained.
    ///
    /// ```text
    ///                                                 +---+---+---+
    ///                                                 | a | b | c |
    ///                                                 +---+---+---+
    /// +---+---+---+---+---+                           | d | e |   |
    /// | a | b | c | d | e | Split::column(3).retain() +---+---+---+
    /// +---+---+---+---+---+           =>              | f | g | h |
    /// | f | g | h |   |   |                           +---+---+---+
    /// +---+---+---+---+---+             |-----------> |   |   |   |
    ///               ^   ^               |             +---+---+---+
    ///               |___|_____cells are kept!
    /// ```
    ///
    /// ## Notes
    ///
    /// See [`clean`] for an alternative display option.
    ///
    /// [`Table`]: crate::Table
    /// [`clean`]: crate::settings::split::Split::clean
    pub fn retain(self) -> Self {
        Self {
            display: Display::Retain,
            ..self
        }
    }
}

impl<R, D, C> TableOption<R, C, D> for Split
where
    R: Records + ExactRecords + Resizable + PeekableRecords,
{
    fn change(self, records: &mut R, _: &mut C, _: &mut D) {
        // variables
        let Split {
            direction,
            behavior,
            display,
            index: section_length,
        } = self;
        let mut filtered_sections = 0;

        // early return check
        if records.count_columns() == 0 || records.count_rows() == 0 || section_length == 0 {
            return;
        }

        // computed variables
        let (primary_length, secondary_length) = compute_length_arrangement(records, direction);
        let sections_per_direction = ceil_div(primary_length, section_length);
        let (outer_range, inner_range) =
            compute_range_order(secondary_length, sections_per_direction, behavior);

        // work
        for outer_index in outer_range {
            let from_secondary_index = outer_index * sections_per_direction - filtered_sections;
            for inner_index in inner_range.clone() {
                let (section_index, from_secondary_index, to_secondary_index) =
                    compute_range_variables(
                        outer_index,
                        inner_index,
                        secondary_length,
                        from_secondary_index,
                        sections_per_direction,
                        filtered_sections,
                        behavior,
                    );

                match (direction, behavior) {
                    (Direction::Column, Behavior::Concat) => records.push_row(),
                    (Direction::Column, Behavior::Zip) => records.insert_row(to_secondary_index),
                    (Direction::Row, Behavior::Concat) => records.push_column(),
                    (Direction::Row, Behavior::Zip) => records.insert_column(to_secondary_index),
                }

                let section_is_empty = copy_section(
                    records,
                    section_length,
                    section_index,
                    primary_length,
                    from_secondary_index,
                    to_secondary_index,
                    direction,
                );

                if section_is_empty && display == Display::Clean {
                    delete(records, to_secondary_index, direction);
                    filtered_sections += 1;
                }
            }
        }

        cleanup(records, section_length, primary_length, direction);
    }
}

/// Determine which direction should be considered the primary, and which the secondary based on direction
fn compute_length_arrangement<R>(records: &mut R, direction: Direction) -> (usize, usize)
where
    R: Records + ExactRecords,
{
    match direction {
        Direction::Column => (records.count_columns(), records.count_rows()),
        Direction::Row => (records.count_rows(), records.count_columns()),
    }
}

/// reduce the table size to the length of the index in the specified direction
fn cleanup<R>(records: &mut R, section_length: usize, primary_length: usize, direction: Direction)
where
    R: Resizable,
{
    for segment in (section_length..primary_length).rev() {
        match direction {
            Direction::Column => records.remove_column(segment),
            Direction::Row => records.remove_row(segment),
        }
    }
}

/// Delete target index row or column
fn delete<R>(records: &mut R, target_index: usize, direction: Direction)
where
    R: Resizable,
{
    match direction {
        Direction::Column => records.remove_row(target_index),
        Direction::Row => records.remove_column(target_index),
    }
}

/// copy cells to new location
///
/// returns if the copied section was entirely blank
fn copy_section<R>(
    records: &mut R,
    section_length: usize,
    section_index: usize,
    primary_length: usize,
    from_secondary_index: usize,
    to_secondary_index: usize,
    direction: Direction,
) -> bool
where
    R: ExactRecords + Resizable + PeekableRecords,
{
    let mut section_is_empty = true;
    for to_primary_index in 0..section_length {
        let from_primary_index = to_primary_index + section_index * section_length;

        if from_primary_index < primary_length {
            let from_position =
                format_position(direction, from_primary_index, from_secondary_index);
            if !records.get_text(from_position).is_empty() {
                section_is_empty = false;
            }
            records.swap(
                from_position,
                format_position(direction, to_primary_index, to_secondary_index),
            );
        }
    }
    section_is_empty
}

/// determine section over direction or vice versa based on behavior
fn compute_range_order(
    direction_length: usize,
    sections_per_direction: usize,
    behavior: Behavior,
) -> (Range<usize>, Range<usize>) {
    match behavior {
        Behavior::Concat => (1..sections_per_direction, 0..direction_length),
        Behavior::Zip => (0..direction_length, 1..sections_per_direction),
    }
}

/// helper function for shimming both behaviors to work within a single nested loop
fn compute_range_variables(
    outer_index: usize,
    inner_index: usize,
    direction_length: usize,
    from_secondary_index: usize,
    sections_per_direction: usize,
    filtered_sections: usize,
    behavior: Behavior,
) -> (usize, usize, usize) {
    match behavior {
        Behavior::Concat => (
            outer_index,
            inner_index,
            inner_index + outer_index * direction_length - filtered_sections,
        ),
        Behavior::Zip => (
            inner_index,
            from_secondary_index,
            outer_index * sections_per_direction + inner_index - filtered_sections,
        ),
    }
}

/// utility for arguments of a position easily
fn format_position(direction: Direction, primary_index: usize, secondary_index: usize) -> Position {
    match direction {
        Direction::Column => (secondary_index, primary_index).into(),
        Direction::Row => (primary_index, secondary_index).into(),
    }
}

/// ceil division utility because the std lib ceil_div isn't stable yet
fn ceil_div(x: usize, y: usize) -> usize {
    debug_assert!(x != 0);
    1 + ((x - 1) / y)
}