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
use std::fmt::{Display, Formatter, Result as FmtResult};

use numfmt::{Numeric, Precision};

pub struct DisplayTable {
    column_names: Vec<String>,
    column_widths: Vec<usize>,
    row_names: Vec<String>,
    data: Vec<Vec<String>>,
    max_print: usize,
    over_max: bool,
}

impl DisplayTable {
    pub fn new<D: ToString + Numeric>(
        column_names: Vec<String>,
        row_names: Vec<String>,
        data: Vec<Vec<D>>,
        max_print: Option<usize>,
    ) -> Self {
        let mut number_formatter = numfmt::Formatter::new().precision(Precision::Significance(5));

        let max_print = max_print.unwrap_or(10);
        let mut over_max = false;

        let data = data
            .into_iter()
            .map(|d| {
                d.into_iter()
                    .map(|v| number_formatter.fmt2(v).to_string())
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();

        let data = if data.len() > max_print {
            over_max = true;
            data.iter()
                .take((max_print as f64 / 2.0).ceil() as usize)
                .chain(
                    data.iter()
                        .rev()
                        .take((max_print as f64 / 2.0).floor() as usize)
                        .rev(),
                )
                .cloned()
                .collect()
        } else {
            data.clone()
        };
        let row_names = if row_names.len() > max_print {
            row_names
                .iter()
                .take((max_print as f64 / 2.0).ceil() as usize)
                .chain(
                    row_names
                        .iter()
                        .rev()
                        .take((max_print as f64 / 2.0).floor() as usize)
                        .rev(),
                )
                .cloned()
                .collect()
        } else {
            row_names.clone()
        };

        let mut column_widths = column_names.iter().map(|c| c.len()).collect::<Vec<_>>();

        for row in &data {
            for (column, width) in row.iter().zip(column_widths.iter_mut()) {
                *width = (*width).max(column.len());
            }
        }

        if !row_names.is_empty() {
            column_widths.insert(0, row_names.iter().map(|n| n.len()).max().unwrap());
        };

        Self {
            column_names,
            column_widths,
            row_names,
            data,
            max_print,
            over_max,
        }
    }

    fn write_table_bars(
        &self,
        formatter: &mut Formatter,
        left_bar: &str,
        middle_blank: &str,
        middle_bar: &str,
        right_bar: &str,
    ) -> FmtResult {
        write!(formatter, "{left_bar}")?;
        for (index, &len) in self.column_widths.iter().enumerate() {
            if len > 0 {
                for _ in 0..len + 2 {
                    write!(formatter, "{middle_blank}")?;
                }
                if index != self.column_widths.len() - 1 {
                    write!(formatter, "{middle_bar}")?;
                }
            }
        }
        writeln!(formatter, "{right_bar}")?;

        Ok(())
    }

    fn write_data(&self, formatter: &mut Formatter, bar: &str) -> FmtResult {
        for (row_index, row) in self.data.iter().enumerate() {
            if self.over_max && row_index == (self.max_print as f64 / 2.0).floor() as usize {
                for column_index in 0..self.column_widths.len() {
                    write!(formatter, "│ …")?;
                    for _ in 0..self.column_widths[column_index] - 1 {
                        write!(formatter, " ")?;
                    }
                    write!(formatter, " ")?;
                }
                writeln!(formatter, "│")?;
            }
            for (column_index, value) in row.iter().enumerate() {
                write!(formatter, "{bar} ")?;
                let column_index = if !self.row_names.is_empty() && column_index == 0 {
                    self.row_names[row_index].fmt(formatter)?;
                    for _ in 0..self.column_widths[column_index] - self.row_names[row_index].len() {
                        write!(formatter, " ")?;
                    }
                    write!(formatter, " {bar} ")?;
                    value.fmt(formatter)?;
                    column_index + 1
                } else {
                    value.fmt(formatter)?;
                    if !self.row_names.is_empty() {
                        column_index + 1
                    } else {
                        column_index
                    }
                };
                if self.column_widths[column_index] > value.to_string().len() {
                    for _ in 0..self.column_widths[column_index] - value.to_string().len() {
                        write!(formatter, " ")?;
                    }
                }
                write!(formatter, " ")?;
            }
            writeln!(formatter, "{bar}")?;
        }

        Ok(())
    }
}

impl Display for DisplayTable {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        // Print top of the table
        self.write_table_bars(f, "┌", "─", "┬", "┐")?;

        // Print column headers
        let mut column_names = self.column_names.clone();
        if !self.row_names.is_empty() {
            column_names.insert(0, "".to_string());
        }
        for (column_index, name) in column_names.iter().enumerate() {
            write!(f, "│ ")?;
            name.fmt(f)?;
            if self.column_widths[column_index] > name.len() {
                for _ in 0..self.column_widths[column_index] - name.len() {
                    write!(f, " ")?;
                }
            }
            write!(f, " ")?;
        }
        writeln!(f, "│")?;

        // Print divider
        self.write_table_bars(f, "╞", "═", "╪", "╡")?;

        // Print data
        self.write_data(f, "│")?;

        // Print bottom of the table
        self.write_table_bars(f, "└", "─", "┴", "┘")?;

        Ok(())
    }
}