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