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//! ASCII table renderer with Unicode box-drawing borders for CLI output.
//!
//! Supports column alignment, auto-width, header styling, and optional colored
//! output via the `colored` crate.
use colored::Colorize;
/// Column alignment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
Left,
Right,
Center,
}
/// A table builder that collects headers and rows, then renders to a
/// Unicode box-drawing string.
pub struct Table {
headers: Vec<String>,
alignments: Vec<Align>,
rows: Vec<Vec<String>>,
}
impl Table {
/// Create a new table with the given column headers.
/// All columns default to left-alignment.
pub fn new(headers: &[&str]) -> Self {
let headers: Vec<String> = headers.iter().map(|h| h.to_string()).collect();
let alignments = vec![Align::Left; headers.len()];
Self {
headers,
alignments,
rows: Vec::new(),
}
}
/// Override the alignment for a specific column (0-indexed).
/// Out-of-range indices are silently ignored.
pub fn align(mut self, col: usize, alignment: Align) -> Self {
if col < self.alignments.len() {
self.alignments[col] = alignment;
}
self
}
/// Add a row. Extra cells are truncated; missing cells are filled with "".
pub fn add_row(&mut self, cells: &[&str]) {
let row: Vec<String> = (0..self.headers.len())
.map(|i| cells.get(i).unwrap_or(&"").to_string())
.collect();
self.rows.push(row);
}
/// Compute the display width of each column (max of header and all cells).
fn column_widths(&self) -> Vec<usize> {
let mut widths: Vec<usize> = self.headers.iter().map(|h| h.len()).collect();
for row in &self.rows {
for (i, cell) in row.iter().enumerate() {
if i < widths.len() {
widths[i] = widths[i].max(cell.len());
}
}
}
widths
}
/// Pad a string to the given width according to alignment.
fn pad(text: &str, width: usize, alignment: Align) -> String {
let len = text.len();
if len >= width {
return text.to_string();
}
let diff = width - len;
match alignment {
Align::Left => format!("{text}{}", " ".repeat(diff)),
Align::Right => format!("{}{text}", " ".repeat(diff)),
Align::Center => {
let left = diff / 2;
let right = diff - left;
format!("{}{text}{}", " ".repeat(left), " ".repeat(right))
}
}
}
/// Build a horizontal border line.
/// `left`, `mid`, `right` are the corner/junction characters.
fn border(widths: &[usize], left: &str, mid: &str, right: &str) -> String {
let segments: Vec<String> = widths.iter().map(|w| "\u{2500}".repeat(w + 2)).collect();
format!("{left}{}{right}", segments.join(mid))
}
/// Render the table to a string with Unicode box-drawing borders.
///
/// Layout:
/// ```text
/// โโโโโโโโฌโโโโโโโโ
/// โ Name โ Value โ
/// โโโโโโโโผโโโโโโโโค
/// โ foo โ bar โ
/// โโโโโโโโดโโโโโโโโ
/// ```
pub fn render(&self) -> String {
let widths = self.column_widths();
let top = Self::border(&widths, "\u{250c}", "\u{252c}", "\u{2510}");
let sep = Self::border(&widths, "\u{251c}", "\u{253c}", "\u{2524}");
let bot = Self::border(&widths, "\u{2514}", "\u{2534}", "\u{2518}");
let mut lines = Vec::new();
// Top border
lines.push(top);
// Header row (bold)
let header_cells: Vec<String> = self
.headers
.iter()
.enumerate()
.map(|(i, h)| format!(" {} ", Self::pad(h, widths[i], self.alignments[i]).bold()))
.collect();
lines.push(format!("\u{2502}{}\u{2502}", header_cells.join("\u{2502}")));
// Separator
lines.push(sep);
// Data rows
for row in &self.rows {
let cells: Vec<String> = row
.iter()
.enumerate()
.map(|(i, cell)| format!(" {} ", Self::pad(cell, widths[i], self.alignments[i])))
.collect();
lines.push(format!("\u{2502}{}\u{2502}", cells.join("\u{2502}")));
}
// Bottom border
lines.push(bot);
lines.join("\n")
}
/// Render the table and print it to stdout.
pub fn print(&self) {
println!("{}", self.render());
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_table() {
let mut t = Table::new(&["Name", "Age", "City"]);
t.add_row(&["Alice", "30", "London"]);
t.add_row(&["Bob", "25", "Paris"]);
let rendered = t.render();
let lines: Vec<&str> = rendered.lines().collect();
// 5 lines: top, header, sep, 2 rows, bottom = 6
assert_eq!(lines.len(), 6);
// Top border uses box-drawing
assert!(lines[0].starts_with('\u{250c}'));
assert!(lines[0].ends_with('\u{2510}'));
// Bottom border
assert!(lines[5].starts_with('\u{2514}'));
assert!(lines[5].ends_with('\u{2518}'));
// Header line contains column names (ignore ANSI codes for bold)
assert!(lines[1].contains("Name"));
assert!(lines[1].contains("Age"));
assert!(lines[1].contains("City"));
// Data rows contain cell values
assert!(lines[3].contains("Alice"));
assert!(lines[3].contains("30"));
assert!(lines[3].contains("London"));
assert!(lines[4].contains("Bob"));
assert!(lines[4].contains("25"));
assert!(lines[4].contains("Paris"));
}
#[test]
fn right_alignment() {
let mut t = Table::new(&["Item", "Count"]);
t = t.align(1, Align::Right);
t.add_row(&["apples", "5"]);
t.add_row(&["oranges", "123"]);
let rendered = t.render();
// The "5" should be right-padded on the left within its column
// Find the data line with "5"
let line = rendered.lines().find(|l| l.contains("apples")).unwrap();
// After the second box char, the number should be right-aligned
assert!(line.contains(" 5"));
}
#[test]
fn center_alignment() {
let pad = Table::pad("hi", 6, Align::Center);
assert_eq!(pad, " hi ");
let pad_odd = Table::pad("hi", 7, Align::Center);
assert_eq!(pad_odd, " hi ");
}
#[test]
fn empty_table() {
let t = Table::new(&["A", "B"]);
let rendered = t.render();
let lines: Vec<&str> = rendered.lines().collect();
// top, header, sep, bottom = 4 lines (no data rows)
assert_eq!(lines.len(), 4);
}
#[test]
fn missing_cells_filled() {
let mut t = Table::new(&["X", "Y", "Z"]);
t.add_row(&["only-one"]);
let rendered = t.render();
// Row should still have 3 columns; missing ones are empty
let data_line = rendered.lines().nth(3).unwrap();
// Count box-drawing vertical bars in data line
let bars = data_line.matches('\u{2502}').count();
assert_eq!(bars, 4); // left + 2 inner + right
}
#[test]
fn wide_cells_auto_width() {
let mut t = Table::new(&["ID", "Description"]);
t.add_row(&["1", "A very long description string"]);
let rendered = t.render();
assert!(rendered.contains("A very long description string"));
// The top border should be wide enough to contain the description
let top = rendered.lines().next().unwrap();
// At minimum: 2 padding + description length for second column
assert!(top.len() > 30);
}
}