1use std::cmp;
2use std::io::{self, Write};
3use std::iter::IntoIterator;
4use std::marker::Sized;
5
6fn prepare_line<U, V>(line: U, col_widths: &mut Vec<usize>, cell_strs: &mut Vec<String>)
7where
8 U: IntoIterator<Item = V>,
9 V: ToString + Sized,
10{
11 for (i, cell) in line.into_iter().enumerate() {
12 if i >= col_widths.len() {
13 col_widths.resize(i + 1, 0);
14 }
15 let cell_str = cell.to_string();
16 col_widths[i] = cmp::max(col_widths[i], cell_str.len());
17 cell_strs.push(cell_str);
18 }
19}
20
21pub fn write<H, I, T, U, V, W>(mut writer: W, header: H, mat: T) -> Result<(), io::Error>
22where
23 H: IntoIterator<Item = I>,
24 I: ToString + Sized,
25 T: IntoIterator<Item = U>,
26 U: IntoIterator<Item = V>,
27 V: ToString + Sized,
28 W: Write,
29{
30 let mut col_widths = vec![];
31 let mut cell_strs = vec![];
32 prepare_line(header, &mut col_widths, &mut cell_strs);
33 for line in mat {
34 prepare_line(line, &mut col_widths, &mut cell_strs);
35 }
36 let mut col = 0;
37 let width = col_widths.len();
38 let mut in_header = true;
39 for cell_str in &cell_strs {
40 writer.write_all(format!("{}", cell_str).as_bytes())?;
41 for _ in cell_str.len()..col_widths[col] {
42 writer.write_all(b" ")?;
43 }
44 col += 1;
45 if col == width {
46 col = 0;
47 writer.write_all(b"\n")?;
48 if in_header {
49 for (i, col_width) in (&col_widths).iter().enumerate() {
50 for _ in 0..*col_width {
51 writer.write_all(b"-")?;
52 }
53 if i < width - 1 {
54 writer.write_all(b"-+-")?;
55 }
56 }
57 writer.write_all(b"\n")?;
58 in_header = false
59 }
60 } else {
61 writer.write_all(b" | ")?;
62 }
63 }
64 Ok(())
65}