#![warn(missing_docs)]
use ndarray::Array2;
use unicode_width::UnicodeWidthChar;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Style {
Simple,
Boxed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Align {
Left,
Right,
Auto,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
}
impl Color {
fn fg_code(self) -> u8 {
match self {
Color::Black => 30,
Color::Red => 31,
Color::Green => 32,
Color::Yellow => 33,
Color::Blue => 34,
Color::Magenta => 35,
Color::Cyan => 36,
Color::White => 37,
Color::BrightBlack => 90,
Color::BrightRed => 91,
Color::BrightGreen => 92,
Color::BrightYellow => 93,
Color::BrightBlue => 94,
Color::BrightMagenta => 95,
Color::BrightCyan => 96,
Color::BrightWhite => 97,
}
}
}
#[derive(Debug, Clone)]
pub struct Table {
rows: Vec<Vec<String>>,
style: Style,
aligns: Vec<Align>,
max_cell_width: Option<usize>,
header_color: Option<Color>,
body_color: Option<Color>,
}
impl Table {
pub fn new(rows: Vec<Vec<String>>) -> Self {
Self {
rows,
style: Style::Simple,
aligns: Vec::new(),
max_cell_width: None,
header_color: None,
body_color: None,
}
}
pub fn from_array2(array: Array2<String>) -> Self {
let rows = array
.outer_iter()
.map(|row| row.iter().cloned().collect())
.collect();
Self::new(rows)
}
pub fn style(mut self, style: Style) -> Self {
self.style = style;
self
}
pub fn aligns(mut self, aligns: Vec<Align>) -> Self {
self.aligns = aligns;
self
}
pub fn max_cell_width(mut self, width: usize) -> Self {
self.max_cell_width = Some(width);
self
}
pub fn header_color(mut self, color: Color) -> Self {
self.header_color = Some(color);
self
}
pub fn body_color(mut self, color: Color) -> Self {
self.body_color = Some(color);
self
}
pub fn render(&self) -> String {
if self.rows.is_empty() {
return String::new();
}
let widths = self.column_widths();
let mut out = String::new();
match self.style {
Style::Simple => {
out.push('│');
out.push_str(&self.render_row(&self.rows[0], &widths, true));
out.push_str("│\n");
out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
out.push('\n');
for row in &self.rows[1..] {
out.push('│');
out.push_str(&self.render_row(row, &widths, false));
out.push_str("│\n");
}
}
Style::Boxed => {
out.push_str(&Self::horizontal(&widths, "┌", "┬", "┐", "─"));
out.push('\n');
out.push('│');
out.push_str(&self.render_row(&self.rows[0], &widths, true));
out.push_str("│\n");
out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
out.push('\n');
for (i, row) in self.rows[1..].iter().enumerate() {
out.push('│');
out.push_str(&self.render_row(row, &widths, false));
out.push_str("│\n");
if i + 1 < self.rows.len() - 1 {
out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
out.push('\n');
}
}
out.push_str(&Self::horizontal(&widths, "└", "┴", "┘", "─"));
out.push('\n');
}
}
out
}
}
impl Table {
fn align_of(&self, col: usize) -> Align {
self.aligns.get(col).copied().unwrap_or(Align::Left)
}
fn column_count(&self) -> usize {
self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
}
fn prepare_cell(&self, content: &str) -> (String, usize) {
let stripped = strip_ansi(content);
let trimmed = stripped.trim();
let truncated = match self.max_cell_width {
Some(max) => truncate_visible(trimmed, max),
None => trimmed.to_string(),
};
let w = display_width(&truncated);
(truncated, w)
}
fn column_widths(&self) -> Vec<usize> {
let cols = self.column_count();
let mut widths = vec![0usize; cols];
for (r, row) in self.rows.iter().enumerate() {
for (i, cell) in row.iter().enumerate() {
let w = if r == 0 {
display_width(cell)
} else {
let (_, w) = self.prepare_cell(cell);
w
};
if w > widths[i] {
widths[i] = w;
}
}
}
widths.into_iter().map(|w| w + 2).collect()
}
fn render_cell(&self, content: &str, width: usize, align: Align) -> String {
let (text, vis) = self.prepare_cell(content);
let inner = width.saturating_sub(2);
let pad = inner.saturating_sub(vis);
let aligned = match align {
Align::Left => format!("{}{}", text, " ".repeat(pad)),
Align::Right => format!("{}{}", " ".repeat(pad), text),
Align::Auto => {
if is_numeric_like(&strip_ansi(content)) {
format!("{}{}", " ".repeat(pad), text)
} else {
format!("{}{}", text, " ".repeat(pad))
}
}
};
let padded = format!(" {} ", aligned);
colorize(&padded, self.body_color)
}
fn render_header_cell(&self, content: &str, width: usize) -> String {
let stripped = strip_ansi(content);
let vis = display_width(&stripped);
let inner = width.saturating_sub(2);
let pad = inner.saturating_sub(vis);
let padded = format!(" {}{} ", stripped, " ".repeat(pad));
colorize(&padded, self.header_color)
}
fn render_row(&self, row: &[String], widths: &[usize], is_header: bool) -> String {
let mut cells = Vec::with_capacity(widths.len());
for (i, w) in widths.iter().enumerate() {
let content = row.get(i).map(String::as_str).unwrap_or("");
if is_header {
cells.push(self.render_header_cell(content, *w));
} else {
let align = self.align_of(i);
cells.push(self.render_cell(content, *w, align));
}
}
cells.join("│")
}
fn horizontal(widths: &[usize], left: &str, mid: &str, right: &str, fill: &str) -> String {
let segments: Vec<String> = widths.iter().map(|w| fill.repeat(*w)).collect();
format!("{}{}{}", left, segments.join(mid), right)
}
}
pub fn render_table(rows: Vec<Vec<String>>, style: Style) -> String {
Table::new(rows).style(style).render()
}
fn colorize(s: &str, color: Option<Color>) -> String {
match color {
Some(c) => format!("\x1b[{}m{}\x1b[0m", c.fg_code(), s),
None => s.to_string(),
}
}
fn extra_wide(c: char) -> bool {
matches!(
c,
'Φ' | 'φ' | 'Ⅱ' | 'Ⅲ' | 'Ⅰ' | '±' | '×' | '÷' | '≤' | '≥' | '≠'
| '→' | '←' | '↑' | '↓'
| '①'..='⑳' )
}
fn char_width(c: char) -> usize {
if extra_wide(c) {
2
} else {
UnicodeWidthChar::width(c).unwrap_or(0)
}
}
pub fn display_width(s: &str) -> usize {
let stripped = strip_ansi(s);
stripped.chars().map(char_width).sum()
}
pub fn pad_right_with_spaces(s: &str, width: usize) -> String {
let w = display_width(s);
if w >= width {
return s.to_string();
}
let mut out = String::with_capacity(s.len() + (width - w));
out.push_str(s);
out.push_str(&" ".repeat(width - w));
out
}
pub fn pad_left_with_spaces(s: &str, width: usize) -> String {
let w = display_width(s);
if w >= width {
return s.to_string();
}
let mut out = String::with_capacity(s.len() + (width - w));
out.push_str(&" ".repeat(width - w));
out.push_str(s);
out
}
pub fn strip_ansi(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
if chars.peek() == Some(&'[') {
chars.next(); for c2 in chars.by_ref() {
if c2.is_ascii_alphabetic() {
break;
}
}
}
} else {
out.push(c);
}
}
out
}
pub fn truncate_visible(s: &str, max_width: usize) -> String {
if max_width == 0 {
return String::new();
}
let vis = display_width(s);
if vis <= max_width {
return s.to_string();
}
let suffix = "...";
let suffix_w = 3usize;
if max_width <= suffix_w {
return suffix.to_string();
}
let target = max_width - suffix_w;
let mut out = String::new();
let mut used = 0usize;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
out.push(c);
if chars.peek() == Some(&'[') {
out.push(chars.next().unwrap());
for c2 in chars.by_ref() {
out.push(c2);
if c2.is_ascii_alphabetic() {
break;
}
}
}
continue;
}
let cw = char_width(c);
if used + cw > target {
break;
}
out.push(c);
used += cw;
}
out.push_str(suffix);
out
}
pub fn is_numeric_like(s: &str) -> bool {
let s = s.trim();
if s.is_empty() {
return false;
}
let head = s.split_whitespace().next().unwrap_or("");
head.parse::<f64>().is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
use unicode_width::UnicodeWidthStr;
#[test]
fn phi_is_ambiguous_width() {
let s = "Φ170";
assert_eq!(UnicodeWidthStr::width(s), 4, "crate 默认宽度:Φ(1)+170(3)=4");
assert_eq!(
UnicodeWidthStr::width_cjk(s),
4,
"crate cjk 宽度同样是 4"
);
assert_eq!(
display_width(s),
5,
"display_width 补偿后:Φ(2)+170(3)=5"
);
}
#[test]
fn display_width_uses_cjk_for_phi() {
assert_eq!(display_width("Φ"), 2);
assert_eq!(display_width("Φ170"), 5);
assert_eq!(display_width("Φ8"), 3);
assert_eq!(display_width("Φ16 III"), 9);
}
#[test]
fn display_width_ascii_unchanged() {
assert_eq!(display_width("abc"), 3);
assert_eq!(display_width("170CD1"), 6);
assert_eq!(display_width("NUT-1"), 5);
}
#[test]
fn display_width_cjk_unchanged() {
assert_eq!(display_width("电杆"), 4);
assert_eq!(display_width("名称"), 4);
assert_eq!(display_width("电阻值设计定"), 12);
}
#[test]
fn display_width_strips_ansi() {
let colored = "\x1b[93m电杆\x1b[0m";
assert_eq!(display_width(colored), 4);
}
#[test]
fn phi_rows_align() {
let rows = vec![
vec!["名称".into(), "规格".into(), "材料".into()],
vec!["电杆".into(), "Φ170".into(), "".into()],
vec!["横担".into(), "03D103-133".into(), "2II2".into()],
vec!["接地线".into(), "Φ8".into(), "".into()],
vec!["拉线棒".into(), "03D103-187".into(), "Φ16 III".into()],
];
let out = Table::new(rows).style(Style::Boxed).render();
for line in out.lines() {
if line.starts_with('│') {
let n = line.matches('│').count();
assert_eq!(n, 4, "行竖线数量异常: {:?}", line);
}
}
}
#[test]
fn phi_align_matches_ascii_row() {
let rows = vec![
vec!["规格".into()],
vec!["Φ170".into()],
vec!["170C".into()], ];
let out = Table::new(rows).style(Style::Boxed).render();
let data_lines: Vec<&str> = out
.lines()
.filter(|l| l.starts_with('│') && !l.contains("规格"))
.collect();
let widths: Vec<usize> = data_lines
.iter()
.map(|l| {
let inner = l.trim_matches('│');
display_width(inner)
})
.collect();
assert!(
widths.windows(2).all(|w| w[0] == w[1]),
"含 Φ 的行与 ASCII 行宽度不一致: {:?}",
widths
);
}
#[test]
fn truncate_phi_consistent() {
let s = "Φ170CD1XYZ";
let t = truncate_visible(s, 6);
assert_eq!(t, "Φ1...");
assert_eq!(display_width(&t), 6);
}
#[test]
fn truncate_ascii_unchanged() {
let s = "abcdefghij";
let t = truncate_visible(s, 7);
assert_eq!(t, "abcd...");
assert_eq!(display_width(&t), 7);
}
#[test]
fn truncate_no_overflow_returns_original() {
let s = "Φ8";
let t = truncate_visible(s, 10);
assert_eq!(t, "Φ8");
}
}