console_table/lib.rs
1//! Console table rendering with Unicode/CJK-aware alignment, truncation,
2//! and ANSI color support.
3//!
4//! # Example
5//!
6//! ```
7//! use console_table::{Align, Style, Table};
8//!
9//! let rows = vec![
10//! vec!["#".to_string(), "source".to_string(), "latency".to_string()],
11//! vec!["1".to_string(), "rsproxy".to_string(), "57 ms".to_string()],
12//! vec!["2".to_string(), "tuna".to_string(), "16 ms".to_string()],
13//! ];
14//!
15//! let table = Table::new(rows)
16//! .style(Style::Boxed)
17//! .aligns(vec![Align::Right, Align::Left, Align::Auto]);
18//!
19//! println!("{}", table.render());
20//! ```
21
22#![warn(missing_docs)]
23
24use unicode_width::UnicodeWidthStr;
25
26// ============================================================
27// Public types
28// ============================================================
29
30/// Border style of the table.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Style {
33 /// Header row, a single separator, then data rows.
34 Simple,
35 /// Full box drawing: top, header separator, row separators, bottom.
36 Boxed,
37}
38
39/// Horizontal alignment of a cell.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Align {
42 /// Left align.
43 Left,
44 /// Right align.
45 Right,
46 /// Right align if the first whitespace-separated token parses as `f64`,
47 /// otherwise left align.
48 Auto,
49}
50
51/// ANSI foreground color.
52///
53/// The first eight are the standard colors, the `Bright*` variants are
54/// the corresponding high-intensity colors. Mapping to ANSI codes:
55/// `Black`=30 ... `White`=37, `BrightBlack`=90 ... `BrightWhite`=97.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Color {
58 /// ANSI color 30.
59 Black,
60 /// ANSI color 31.
61 Red,
62 /// ANSI color 32.
63 Green,
64 /// ANSI color 33.
65 Yellow,
66 /// ANSI color 34.
67 Blue,
68 /// ANSI color 35.
69 Magenta,
70 /// ANSI color 36.
71 Cyan,
72 /// ANSI color 37.
73 White,
74 /// ANSI color 90 (high-intensity black / gray).
75 BrightBlack,
76 /// ANSI color 91.
77 BrightRed,
78 /// ANSI color 92.
79 BrightGreen,
80 /// ANSI color 93.
81 BrightYellow,
82 /// ANSI color 94.
83 BrightBlue,
84 /// ANSI color 95.
85 BrightMagenta,
86 /// ANSI color 96.
87 BrightCyan,
88 /// ANSI color 97.
89 BrightWhite,
90}
91
92impl Color {
93 /// The ANSI foreground color code.
94 fn fg_code(self) -> u8 {
95 match self {
96 Color::Black => 30,
97 Color::Red => 31,
98 Color::Green => 32,
99 Color::Yellow => 33,
100 Color::Blue => 34,
101 Color::Magenta => 35,
102 Color::Cyan => 36,
103 Color::White => 37,
104 Color::BrightBlack => 90,
105 Color::BrightRed => 91,
106 Color::BrightGreen => 92,
107 Color::BrightYellow => 93,
108 Color::BrightBlue => 94,
109 Color::BrightMagenta => 95,
110 Color::BrightCyan => 96,
111 Color::BrightWhite => 97,
112 }
113 }
114}
115
116/// Table configuration.
117#[derive(Debug, Clone)]
118pub struct Table {
119 rows: Vec<Vec<String>>,
120 style: Style,
121 aligns: Vec<Align>,
122 /// Maximum display width of a data cell (padding excluded).
123 /// `None` means no truncation.
124 max_cell_width: Option<usize>,
125 /// Foreground color for the header row.
126 header_color: Option<Color>,
127 /// Foreground color for data rows.
128 body_color: Option<Color>,
129}
130
131impl Table {
132 /// Create a table from `rows`. The first row is treated as the header.
133 ///
134 /// Rows may have different lengths; missing cells are treated as empty.
135 pub fn new(rows: Vec<Vec<String>>) -> Self {
136 Self {
137 rows,
138 style: Style::Simple,
139 aligns: Vec::new(),
140 max_cell_width: None,
141 header_color: None,
142 body_color: None,
143 }
144 }
145
146 /// Set the border style. Default is [`Style::Simple`].
147 pub fn style(mut self, style: Style) -> Self {
148 self.style = style;
149 self
150 }
151
152 /// Set per-column alignment. Missing columns default to [`Align::Left`].
153 pub fn aligns(mut self, aligns: Vec<Align>) -> Self {
154 self.aligns = aligns;
155 self
156 }
157
158 /// Truncate data cells to at most `width` display columns, appending
159 /// ASCII `...` on overflow. The header is never truncated.
160 pub fn max_cell_width(mut self, width: usize) -> Self {
161 self.max_cell_width = Some(width);
162 self
163 }
164
165 /// Set the header foreground color. Default is no color.
166 pub fn header_color(mut self, color: Color) -> Self {
167 self.header_color = Some(color);
168 self
169 }
170
171 /// Set the data-row foreground color. Default is no color.
172 pub fn body_color(mut self, color: Color) -> Self {
173 self.body_color = Some(color);
174 self
175 }
176
177 fn align_of(&self, col: usize) -> Align {
178 self.aligns.get(col).copied().unwrap_or(Align::Left)
179 }
180
181 /// Number of columns: the maximum row length.
182 fn column_count(&self) -> usize {
183 self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
184 }
185
186 /// Prepare a cell for rendering.
187 ///
188 /// Steps: strip ANSI escape sequences, then truncate to
189 /// `max_cell_width`. Returns `(final_text, display_width)`.
190 ///
191 /// Both width computation and rendering call this, so they always see
192 /// the same content.
193 fn prepare_cell(&self, content: &str) -> (String, usize) {
194 let stripped = strip_ansi(content);
195 let truncated = match self.max_cell_width {
196 Some(max) => truncate_visible(&stripped, max),
197 None => stripped,
198 };
199 let w = display_width(&truncated);
200 (truncated, w)
201 }
202
203 /// Compute the display width of each column.
204 ///
205 /// Each column is `max(display_width of all cells in that column,
206 /// including the header) + 2`, where `+2` reserves one space of padding
207 /// on each side. Data cells are prepared first via [`Self::prepare_cell`].
208 fn column_widths(&self) -> Vec<usize> {
209 let cols = self.column_count();
210 let mut widths = vec![0usize; cols];
211 for (r, row) in self.rows.iter().enumerate() {
212 for (i, cell) in row.iter().enumerate() {
213 let w = if r == 0 {
214 // Header: never truncated, but ANSI is still stripped
215 // before measuring.
216 display_width(cell)
217 } else {
218 // Data rows go through the same preparation path.
219 let (_, w) = self.prepare_cell(cell);
220 w
221 };
222 if w > widths[i] {
223 widths[i] = w;
224 }
225 }
226 }
227 // Reserve one space of padding on each side.
228 widths.into_iter().map(|w| w + 2).collect()
229 }
230
231 /// Render one data cell: one space of padding on each side, then
232 /// alignment, then `body_color`.
233 fn render_cell(&self, content: &str, width: usize, align: Align) -> String {
234 let (text, vis) = self.prepare_cell(content);
235
236 // `width` already includes one space of padding on each side.
237 let inner = width.saturating_sub(2);
238 let pad = inner.saturating_sub(vis);
239
240 let aligned = match align {
241 Align::Left => format!("{}{}", text, " ".repeat(pad)),
242 Align::Right => format!("{}{}", " ".repeat(pad), text),
243 Align::Auto => {
244 // Decide numeric-ness from the original content (ANSI stripped).
245 if is_numeric_like(&strip_ansi(content)) {
246 format!("{}{}", " ".repeat(pad), text)
247 } else {
248 format!("{}{}", text, " ".repeat(pad))
249 }
250 }
251 };
252
253 let padded = format!(" {} ", aligned);
254 colorize(&padded, self.body_color)
255 }
256
257 /// Render one header cell: left aligned, never truncated, one space of
258 /// padding on each side, then `header_color`.
259 fn render_header_cell(&self, content: &str, width: usize) -> String {
260 let stripped = strip_ansi(content);
261 let vis = display_width(&stripped);
262 let inner = width.saturating_sub(2);
263 let pad = inner.saturating_sub(vis);
264 let padded = format!(" {}{} ", stripped, " ".repeat(pad));
265 colorize(&padded, self.header_color)
266 }
267
268 /// Render one row (without the leading and trailing `│`).
269 fn render_row(&self, row: &[String], widths: &[usize], is_header: bool) -> String {
270 let mut cells = Vec::with_capacity(widths.len());
271 for (i, w) in widths.iter().enumerate() {
272 let content = row.get(i).map(String::as_str).unwrap_or("");
273 if is_header {
274 cells.push(self.render_header_cell(content, *w));
275 } else {
276 let align = self.align_of(i);
277 cells.push(self.render_cell(content, *w, align));
278 }
279 }
280 cells.join("│")
281 }
282
283 /// Build a horizontal line, e.g. `├───┼───┤`.
284 fn horizontal(widths: &[usize], left: &str, mid: &str, right: &str, fill: &str) -> String {
285 let segments: Vec<String> = widths.iter().map(|w| fill.repeat(*w)).collect();
286 format!("{}{}{}", left, segments.join(mid), right)
287 }
288
289 /// Render the table to a `String`. Every line ends with `\n`.
290 pub fn render(&self) -> String {
291 if self.rows.is_empty() {
292 return String::new();
293 }
294 let widths = self.column_widths();
295 let mut out = String::new();
296
297 match self.style {
298 Style::Simple => {
299 out.push('│');
300 out.push_str(&self.render_row(&self.rows[0], &widths, true));
301 out.push_str("│\n");
302 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
303 out.push('\n');
304 for row in &self.rows[1..] {
305 out.push('│');
306 out.push_str(&self.render_row(row, &widths, false));
307 out.push_str("│\n");
308 }
309 }
310 Style::Boxed => {
311 out.push_str(&Self::horizontal(&widths, "┌", "┬", "┐", "─"));
312 out.push('\n');
313 out.push('│');
314 out.push_str(&self.render_row(&self.rows[0], &widths, true));
315 out.push_str("│\n");
316 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
317 out.push('\n');
318 for (i, row) in self.rows[1..].iter().enumerate() {
319 out.push('│');
320 out.push_str(&self.render_row(row, &widths, false));
321 out.push_str("│\n");
322 if i + 1 < self.rows.len() - 1 {
323 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
324 out.push('\n');
325 }
326 }
327 out.push_str(&Self::horizontal(&widths, "└", "┴", "┘", "─"));
328 out.push('\n');
329 }
330 }
331 out
332 }
333}
334
335/// Convenience function: render a table directly.
336pub fn render_table(rows: Vec<Vec<String>>, style: Style) -> String {
337 Table::new(rows).style(style).render()
338}
339
340// ============================================================
341// Color
342// ============================================================
343
344/// Wrap `s` in an ANSI foreground color. `None` returns `s` unchanged.
345fn colorize(s: &str, color: Option<Color>) -> String {
346 match color {
347 Some(c) => format!("\x1b[{}m{}\x1b[0m", c.fg_code(), s),
348 None => s.to_string(),
349 }
350}
351
352// ============================================================
353// Width
354// ============================================================
355
356/// Terminal display width of `s`, ignoring ANSI escape sequences.
357pub fn display_width(s: &str) -> usize {
358 let stripped = strip_ansi(s);
359 UnicodeWidthStr::width(stripped.as_str())
360}
361
362/// Pad `s` on the right with spaces up to `width` display columns.
363pub fn pad_right_with_spaces(s: &str, width: usize) -> String {
364 let w = display_width(s);
365 if w >= width {
366 return s.to_string();
367 }
368 let mut out = String::with_capacity(s.len() + (width - w));
369 out.push_str(s);
370 out.push_str(&" ".repeat(width - w));
371 out
372}
373
374/// Pad `s` on the left with spaces up to `width` display columns.
375pub fn pad_left_with_spaces(s: &str, width: usize) -> String {
376 let w = display_width(s);
377 if w >= width {
378 return s.to_string();
379 }
380 let mut out = String::with_capacity(s.len() + (width - w));
381 out.push_str(&" ".repeat(width - w));
382 out.push_str(s);
383 out
384}
385
386// ============================================================
387// ANSI
388// ============================================================
389
390/// Strip CSI-style ANSI escape sequences (e.g. `\x1b[...m`) from `s`.
391pub fn strip_ansi(s: &str) -> String {
392 let mut out = String::with_capacity(s.len());
393 let mut chars = s.chars().peekable();
394 while let Some(c) = chars.next() {
395 if c == '\x1b' {
396 if chars.peek() == Some(&'[') {
397 chars.next(); // consume '['
398 for c2 in chars.by_ref() {
399 if c2.is_ascii_alphabetic() {
400 break;
401 }
402 }
403 }
404 } else {
405 out.push(c);
406 }
407 }
408 out
409}
410
411// ============================================================
412// Truncation
413// ============================================================
414
415/// Truncate `s` to at most `max_width` display columns, appending ASCII
416/// `...` (3 columns) on overflow.
417///
418/// ASCII `...` is used instead of `…` (U+2026) because the single-character
419/// ellipsis renders as 1 or 2 columns depending on terminal and font, which
420/// breaks alignment. ASCII `...` is always exactly 3 columns.
421///
422/// ANSI escape sequences are preserved (they do not consume width), but
423/// color closure after truncation is not guaranteed. Prefer stripping ANSI
424/// before calling this function.
425pub fn truncate_visible(s: &str, max_width: usize) -> String {
426 if max_width == 0 {
427 return String::new();
428 }
429 let vis = display_width(s);
430 if vis <= max_width {
431 return s.to_string();
432 }
433 let suffix = "...";
434 let suffix_w = 3usize;
435 if max_width <= suffix_w {
436 // Not enough room for any content; show the suffix only.
437 return suffix.to_string();
438 }
439 let target = max_width - suffix_w;
440 let mut out = String::new();
441 let mut used = 0usize;
442 let mut chars = s.chars().peekable();
443 while let Some(c) = chars.next() {
444 if c == '\x1b' {
445 out.push(c);
446 if chars.peek() == Some(&'[') {
447 out.push(chars.next().unwrap());
448 for c2 in chars.by_ref() {
449 out.push(c2);
450 if c2.is_ascii_alphabetic() {
451 break;
452 }
453 }
454 }
455 continue;
456 }
457 let cw = UnicodeWidthStr::width(c.to_string().as_str());
458 if used + cw > target {
459 break;
460 }
461 out.push(c);
462 used += cw;
463 }
464 out.push_str(suffix);
465 out
466}
467
468// ============================================================
469// Numeric heuristic
470// ============================================================
471
472/// Return `true` if `s` looks like a number, for [`Align::Auto`].
473///
474/// Rule: take the first whitespace-separated token and try to parse it as
475/// `f64`. For example, `"57 ms"` -> `"57"` -> `true`; `"失败"` -> `false`;
476/// `"-3.14"` -> `true`.
477pub fn is_numeric_like(s: &str) -> bool {
478 let s = s.trim();
479 if s.is_empty() {
480 return false;
481 }
482 let head = s.split_whitespace().next().unwrap_or("");
483 head.parse::<f64>().is_ok()
484}