1const MAX_CELL_WIDTH: usize = 60;
9
10pub fn render(headers: &[&str], rows: &[Vec<String>]) -> String {
13 let cols = headers.len();
14
15 let header_cells: Vec<String> = headers.iter().map(|h| trunc(h)).collect();
17 let row_cells: Vec<Vec<String>> = rows
18 .iter()
19 .map(|r| {
20 let mut row: Vec<String> = r.iter().take(cols).map(|c| trunc(c)).collect();
21 while row.len() < cols {
22 row.push(String::new());
23 }
24 row
25 })
26 .collect();
27
28 let mut widths: Vec<usize> = header_cells.iter().map(|h| h.chars().count()).collect();
29 for row in &row_cells {
30 for (i, cell) in row.iter().enumerate() {
31 let w = cell.chars().count();
32 if w > widths[i] {
33 widths[i] = w;
34 }
35 }
36 }
37
38 let top = border(&widths, '+', '+', '+');
39 let middle = border(&widths, '+', '+', '+');
40 let bottom = border(&widths, '+', '+', '+');
41
42 let mut out = String::new();
43 out.push_str("```\n");
44 out.push_str(&top);
45 out.push('\n');
46 out.push_str(&data_row(&header_cells, &widths));
47 out.push('\n');
48 out.push_str(&middle);
49 out.push('\n');
50 for (i, row) in row_cells.iter().enumerate() {
51 out.push_str(&data_row(row, &widths));
52 out.push('\n');
53 if i + 1 < row_cells.len() {
56 out.push_str(&middle);
57 out.push('\n');
58 }
59 }
60 out.push_str(&bottom);
61 out.push('\n');
62 out.push_str("```\n");
63 out
64}
65
66fn border(widths: &[usize], left: char, mid: char, right: char) -> String {
67 let mut s = String::new();
68 s.push(left);
69 for (i, w) in widths.iter().enumerate() {
70 for _ in 0..(*w + 2) {
71 s.push('-');
72 }
73 s.push(if i + 1 == widths.len() { right } else { mid });
74 }
75 s
76}
77
78fn data_row(cells: &[String], widths: &[usize]) -> String {
79 let mut s = String::new();
80 s.push('|');
81 for (i, cell) in cells.iter().enumerate() {
82 s.push(' ');
83 s.push_str(&pad(cell, widths[i]));
84 s.push(' ');
85 s.push('|');
86 }
87 s
88}
89
90fn pad(s: &str, width: usize) -> String {
91 let len = s.chars().count();
92 if len >= width {
93 return s.to_string();
94 }
95 let mut padded = String::with_capacity(s.len() + width - len);
96 padded.push_str(s);
97 for _ in 0..(width - len) {
98 padded.push(' ');
99 }
100 padded
101}
102
103fn trunc(s: &str) -> String {
104 let len = s.chars().count();
105 if len <= MAX_CELL_WIDTH {
106 return s.to_string();
107 }
108 let mut taken: String = s.chars().take(MAX_CELL_WIDTH - 1).collect();
109 taken.push('…');
110 taken
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116 #[test]
117 fn aligns_columns_inside_code_fence() {
118 let out = render(&["a", "b"], &[vec!["x".into(), "yyy".into()], vec!["xxxx".into(), "z".into()]]);
119 assert!(out.starts_with("```\n"));
120 assert!(out.contains('|'));
121 assert!(out.contains('+'));
122 }
123 #[test]
124 fn truncates_huge_cells() {
125 let big = "x".repeat(200);
126 let out = render(&["c"], &[vec![big]]);
127 for line in out.lines() {
128 assert!(line.chars().count() < 80);
129 }
130 }
131}