ascii_table 5.0.0

Print ASCII tables to the terminal
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
//! Print ASCII tables to the terminal.
//!
//! # Example
//!
//! ```
//! use ::ascii_table::AsciiTable;
//!
//! let ascii_table = AsciiTable::new();
//! let data = &[&["1", "2", "3"], &["4", "5", "6"], &["7", "8", "9"]];
//! ascii_table.println(data);
//! // ┌───┬───┬───┐
//! // │ 1 │ 2 │ 3 │
//! // │ 4 │ 5 │ 6 │
//! // │ 7 │ 8 │ 9 │
//! // └───┴───┴───┘
//! ```
//!
//! # Example
//!
//! ```
//! use ::ascii_table::{Align, AsciiTable, Width};
//!
//! let mut ascii_table = AsciiTable::new();
//! ascii_table.set_max_width(Width::Fixed(26));
//! ascii_table
//!     .column(0)
//!     .set_header("H1")
//!     .set_align(Align::Left);
//! ascii_table
//!     .column(1)
//!     .set_header("H2")
//!     .set_align(Align::Center);
//! ascii_table
//!     .column(2)
//!     .set_header("H3")
//!     .set_align(Align::Right);
//!
//! let data: &[&[&str]] = &[&["v", "v", "v"], &["123", "456", "789", "abcdef"]];
//! ascii_table.println(data);
//! // ┌─────┬─────┬─────┬──────┐
//! // │ H1  │ H2  │ H3  │      │
//! // ├─────┼─────┼─────┼──────┤
//! // │ v   │  v  │   v │      │
//! // │ 123 │ 456 │ 789 │ abc+ │
//! // └─────┴─────┴─────┴──────┘
//! ```
//!
//! ## Features
//!
//! - `auto_table_width`: Sets the default max width of the Ascii Table to the width of the terminal.
//! - `color_codes`: Correctly calculates the width of a string when terminal color codes are present
//!   (like those from the `colorful` crate).
//! - `wide_characters`: Correctly calculates the width of a string when wide characters are present
//!   (like emoji's).

#[cfg(test)]
mod tests;

use ::std::collections::BTreeMap;
use ::std::io::Write;

const DEFAULT_TABLE_WIDTH: usize = 100;
const NEWS: &str = "";
const NEW: &str = "";
const NES: &str = "";
const NWS: &str = "";
const EWS: &str = "";
const NE: &str = "";
const NW: &str = "";
const NS: &str = "";
const EW: &str = "";
const ES: &str = "";
const WS: &str = "";

#[cfg(feature = "color_codes")]
static COLOR_CODE_PARESR: ::std::sync::LazyLock<::regex::Regex> =
    ::std::sync::LazyLock::new(|| {
        ::regex::Regex::new("\u{1b}\\[([0-9]+;)*[0-9]+m").expect("Regex compilation error")
    });

#[derive(Clone, Debug, Default)]
pub struct AsciiTable {
    max_width: Width,
    columns: BTreeMap<usize, Column>,
}

impl AsciiTable {
    pub fn new() -> Self {
        Default::default()
    }

    /// Sets the maximum width of the table.
    ///
    /// - `Default`: Sets the width to 100.
    /// - `Fixed`: Sets the width to a value of your choosing.
    /// - `Auto`: Ascii Table will set the max width to the width of your terminal. Should `Auto` fail
    ///   to determine the terminal width it will fallback to `Default`. For feature `auto_table_width`
    ///   only.
    ///
    /// # Default value
    ///
    /// The default value for max width is dependent on the features you have enabled. When `auto_table_width`
    /// is enabled the default value is `Auto`. Otherwise the default value is `Default`. Note that
    /// "default value" is not to be confused with the enum variant `Default`.
    pub fn set_max_width(&mut self, max_width: Width) -> &mut Self {
        self.max_width = max_width;
        self
    }

    pub fn max_width(&self) -> Width {
        self.max_width
    }

    pub fn column(&mut self, index: usize) -> &mut Column {
        self.columns.entry(index).or_default()
    }
}

/// See [`set_max_width`](AsciiTable::set_max_width).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum Width {
    Default,
    Fixed(usize),
    #[cfg(feature = "auto_table_width")]
    Auto,
}

impl Default for Width {
    fn default() -> Self {
        #[cfg(not(feature = "auto_table_width"))]
        {
            Self::Default
        }
        #[cfg(feature = "auto_table_width")]
        {
            Self::Auto
        }
    }
}

#[derive(Clone, Debug)]
pub struct Column {
    header: String,
    align: Align,
    max_width: usize,
}

impl Column {
    /// Sets the value for the header row. When none of the table's columns has a header value then
    /// the header row wont be rendered.
    pub fn set_header<T>(&mut self, header: T) -> &mut Self
    where
        T: Into<String>,
    {
        self.header = header.into();
        self
    }

    pub fn header(&self) -> &str {
        &self.header
    }

    pub fn set_align(&mut self, align: Align) -> &mut Self {
        self.align = align;
        self
    }

    pub fn align(&self) -> Align {
        self.align
    }

    /// Sets the maximum width of the content (rendered text) for this column.
    ///
    /// The maximum width of the table takes precedence over the maximum width of its columns. So you
    /// can't use the columns maximum width to extends the table beyond its maximum width.
    pub fn set_max_width(&mut self, max_width: usize) -> &mut Self {
        self.max_width = max_width;
        self
    }

    pub fn max_width(&self) -> usize {
        self.max_width
    }
}

impl Default for Column {
    fn default() -> Self {
        Self {
            header: Default::default(),
            align: Default::default(),
            max_width: usize::MAX,
        }
    }
}

/// Alignment of text in a cell.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum Align {
    #[default]
    Left,
    Center,
    Right,
}

impl AsciiTable {
    pub fn println<T1, T2, T3>(&self, data: T1)
    where
        T1: AsRef<[T2]>,
        T2: AsRef<[T3]>,
        T3: AsRef<str>,
    {
        let _ = self.writeln(::std::io::stdout().lock(), data);
    }

    pub fn writeln<T1, T2, T3, W>(&self, mut writer: W, data: T1) -> Result<(), ::std::io::Error>
    where
        T1: AsRef<[T2]>,
        T2: AsRef<[T3]>,
        T3: AsRef<str>,
        W: Write,
    {
        let context = self.context(&data);
        self.write_top(&mut writer, &context)?;
        self.write_header(&mut writer, &context)?;
        self.write_data(&mut writer, &context, data)?;
        self.write_bottom(&mut writer, &context)?;
        writer.flush()?;

        Ok(())
    }

    fn context<T1, T2, T3>(&self, data: T1) -> Context
    where
        T1: AsRef<[T2]>,
        T2: AsRef<[T3]>,
        T3: AsRef<str>,
    {
        let last_visible_header = self
            .columns
            .iter()
            .filter(|(_, header)| !header.header.is_empty())
            .last()
            .map(|(&n, _)| n);

        let header_count = last_visible_header.map(|n| n + 1).unwrap_or(0);
        let mut column_widths = Vec::with_capacity(header_count.max(20));
        // Ensure that we always have atleast 1 column. Even for empty input.
        column_widths.resize(header_count.max(1), 0);
        for row in data.as_ref() {
            let row = row.as_ref();

            if row.len() > column_widths.len() {
                column_widths.resize(row.len(), 0);
            }

            for column in 0..row.len() {
                let column_max_width = self
                    .columns
                    .get(&column)
                    .map(|column| column.max_width)
                    .unwrap_or(usize::MAX);
                let cell_width = row
                    .get(column)
                    .map(|cell| Self::string_width(cell.as_ref()))
                    .unwrap_or(0);
                column_widths[column] = cell_width.min(column_max_width).max(column_widths[column]);
            }
        }
        for (&column, header) in &self.columns {
            if column < column_widths.len() {
                let column_max_width = header.max_width;
                let cell_width = Self::string_width(&header.header);
                column_widths[column] = cell_width.min(column_max_width).max(column_widths[column]);
            }
        }

        let table_max_width = match self.max_width {
            Width::Default => DEFAULT_TABLE_WIDTH,
            Width::Fixed(width) => width,
            #[cfg(feature = "auto_table_width")]
            Width::Auto => ::termize::dimensions()
                .map(|(width, _)| width)
                .unwrap_or(DEFAULT_TABLE_WIDTH),
        };
        let mut table_width =
            column_widths.iter().sum::<usize>() + 2 + ((column_widths.len() - 1) * 3) + 2;
        while table_width > table_max_width {
            let mut max = 0;
            let mut index = 0;
            for (n, &value) in column_widths.iter().enumerate() {
                if value > max {
                    max = value;
                    index = n;
                }
            }

            column_widths[index] -= 1;
            table_width -= 1;
        }

        Context {
            column_widths,
            has_header: last_visible_header.is_some(),
        }
    }

    fn write_top<W>(&self, mut writer: W, context: &Context) -> Result<(), ::std::io::Error>
    where
        W: Write,
    {
        write!(writer, "{ES}")?;
        for column in 0..context.columns() {
            if column < context.columns() - 1 {
                for _ in 0..context.column_widths[column] + 2 {
                    write!(writer, "{EW}")?;
                }
                write!(writer, "{EWS}")?;
            } else {
                for _ in 0..context.column_widths[column] + 2 {
                    write!(writer, "{EW}")?;
                }
            }
        }
        write!(writer, "{WS}\n")?;
        Ok(())
    }

    fn write_header<W>(&self, mut writer: W, context: &Context) -> Result<(), ::std::io::Error>
    where
        W: Write,
    {
        if context.has_header {
            write!(writer, "{NS} ")?;
            for column in 0..context.columns() {
                let value = self
                    .columns
                    .get(&column)
                    .map(|column| column.header.as_str())
                    .unwrap_or("");
                self.write_cell(
                    &mut writer,
                    value,
                    context.column_widths[column],
                    Align::default(),
                )?;
                if column < context.columns() - 1 {
                    write!(writer, " {NS} ")?;
                }
            }
            write!(writer, " {NS}\n")?;

            write!(writer, "{NES}")?;
            for column in 0..context.columns() {
                if column < context.columns() - 1 {
                    for _ in 0..context.column_widths[column] + 2 {
                        write!(writer, "{EW}")?;
                    }
                    write!(writer, "{NEWS}")?;
                } else {
                    for _ in 0..context.column_widths[column] + 2 {
                        write!(writer, "{EW}")?;
                    }
                }
            }
            write!(writer, "{NWS}\n")?;
        }
        Ok(())
    }

    fn write_data<T1, T2, T3, W>(
        &self,
        mut writer: W,
        context: &Context,
        data: T1,
    ) -> Result<(), ::std::io::Error>
    where
        T1: AsRef<[T2]>,
        T2: AsRef<[T3]>,
        T3: AsRef<str>,
        W: Write,
    {
        for row in data.as_ref() {
            let row = row.as_ref();

            write!(writer, "{NS} ")?;
            for column in 0..context.columns() {
                let value = row.get(column).map(|cell| cell.as_ref()).unwrap_or("");
                let align = self
                    .columns
                    .get(&column)
                    .map(|column| column.align)
                    .unwrap_or_default();
                self.write_cell(&mut writer, value, context.column_widths[column], align)?;
                if column < context.columns() - 1 {
                    write!(writer, " {NS} ")?;
                }
            }
            write!(writer, " {NS}\n")?;
        }
        Ok(())
    }

    fn write_bottom<W>(&self, mut writer: W, context: &Context) -> Result<(), ::std::io::Error>
    where
        W: Write,
    {
        write!(writer, "{NE}")?;
        for column in 0..context.columns() {
            if column < context.columns() - 1 {
                for _ in 0..context.column_widths[column] + 2 {
                    write!(writer, "{EW}")?;
                }
                write!(writer, "{NEW}")?;
            } else {
                for _ in 0..context.column_widths[column] + 2 {
                    write!(writer, "{EW}")?;
                }
            }
        }
        write!(writer, "{NW}\n")?;
        Ok(())
    }

    fn write_cell<W>(
        &self,
        mut writer: W,
        cell: &str,
        width: usize,
        align: Align,
    ) -> Result<(), ::std::io::Error>
    where
        W: Write,
    {
        if width == 0 {
            return Ok(());
        }

        let cell_width = Self::string_width(cell);
        if cell_width <= width {
            let [prepad, postpad] = match align {
                Align::Left => [0, width - cell_width],
                Align::Center => [
                    (width - cell_width) / 2,
                    ((width - cell_width) / 2) + ((width - cell_width) % 2),
                ],
                Align::Right => [width - cell_width, 0],
            };

            for _ in 0..prepad {
                write!(writer, " ")?;
            }
            write!(writer, "{cell}")?;
            for _ in 0..postpad {
                write!(writer, " ")?;
            }
        } else {
            let (cell, taken_width) = Self::string_take(cell, width - 1);
            write!(writer, "{cell}+")?;
            for _ in 0..width - 1 - taken_width {
                write!(writer, " ")?;
            }
        }
        Ok(())
    }

    fn string_width(value: &str) -> usize {
        #[cfg(not(feature = "color_codes"))]
        {
            Self::string_width_lv2(value)
        }

        #[cfg(feature = "color_codes")]
        {
            let mut width = 0;

            let mut last_end = 0;
            for r#match in COLOR_CODE_PARESR.find_iter(value) {
                let start = r#match.start();
                let end = r#match.end();

                if last_end < start {
                    width += Self::string_width_lv2(&value[last_end..start]);
                }

                last_end = end;
            }

            if last_end < value.len() {
                width += Self::string_width_lv2(&value[last_end..]);
            }

            width
        }
    }

    fn string_width_lv2(value: &str) -> usize {
        #[cfg(not(feature = "wide_characters"))]
        {
            value.chars().count()
        }

        #[cfg(feature = "wide_characters")]
        {
            ::unicode_width::UnicodeWidthStr::width(value)
        }
    }

    #[cfg(not(feature = "color_codes"))]
    fn string_take(value: &str, amount: usize) -> (&str, usize) {
        Self::string_take_lv2(value, amount)
    }

    #[cfg(feature = "color_codes")]
    fn string_take(value: &str, amount: usize) -> (String, usize) {
        if amount == 0 {
            return (String::new(), 0);
        }

        let mut result = String::with_capacity(value.len());

        let mut last_end = 0;
        let mut fill_to_end = false;
        let mut width = 0;
        for r#match in COLOR_CODE_PARESR.find_iter(value) {
            let start = r#match.start();
            let end = r#match.end();

            if fill_to_end {
                result.push_str(&value[start..end]);
            } else if last_end < start {
                let leading_segment = &value[last_end..start];
                let leading_width = Self::string_width_lv2(leading_segment);

                if width + leading_width <= amount {
                    result.push_str(leading_segment);
                    width += leading_width;
                    result.push_str(&value[start..end]);
                } else {
                    let (taken_cell, taken_width) =
                        Self::string_take_lv2(leading_segment, amount - width);
                    result.push_str(taken_cell);
                    width += taken_width;
                    result.push_str(&value[start..end]);
                    fill_to_end = true;
                }
            } else {
                result.push_str(&value[start..end]);
            }

            last_end = end;
        }

        if last_end < value.len() && !fill_to_end {
            let (taken_cell, taken_width) =
                Self::string_take_lv2(&value[last_end..], amount - width);
            result.push_str(taken_cell);
            width += taken_width;
        }

        (result, width)
    }

    fn string_take_lv2(value: &str, amount: usize) -> (&str, usize) {
        if amount == 0 {
            return ("", 0);
        }

        #[cfg(not(feature = "wide_characters"))]
        {
            let end = value
                .char_indices()
                .nth(amount)
                .map(|(n, _)| n)
                .expect("string_take exhausted its input");
            (&value[..end], amount)
        }

        #[cfg(feature = "wide_characters")]
        {
            let mut width = 0;
            for (n, c) in value.char_indices() {
                let char_width = ::unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
                if width + char_width == amount {
                    return (&value[..n + c.len_utf8()], amount);
                } else if width + char_width > amount {
                    // Because wide characters can be wider that 1 it is possible to overshoot the requested
                    // amount. In this scenario we take the largest substring which has a width less
                    // than the amount. This is why the "taken amount" is not always the same as the
                    // "requested amount".
                    return (&value[..n], width);
                } else {
                    width += char_width;
                }
            }
            panic!("string_take exhausted its input")
        }
    }
}

#[derive(Default, Debug)]
struct Context {
    column_widths: Vec<usize>, // Excludes padding
    has_header: bool,
}

impl Context {
    fn columns(&self) -> usize {
        self.column_widths.len()
    }
}