rust_texas/component/
table.rs

1use itertools::Itertools;
2
3use crate::prelude::*;
4
5#[derive(Debug, Clone)]
6pub struct Row {
7    cells: Vec<Component>,
8}
9impl AsLatex for Row {
10    fn to_string(&self) -> String {
11        format!(
12            "{} \\\\ \n",
13            self.cells.iter().map(|x| x.to_string()).join(" & ")
14        )
15    }
16}
17impl Populate for Row {
18    fn attach(&mut self, other: Component) -> TexResult<&mut Self> {
19        self.cells.push(other);
20        Ok(self)
21    }
22    fn attach_vec(&mut self, other: Vec<Component>) -> TexResult<&mut Self> {
23        self.attach_iter(other.into_iter())
24    }
25
26    fn attach_iter<I: Iterator<Item = Component>>(&mut self, other: I) -> TexResult<&mut Self> {
27        self.cells.extend(other);
28        Ok(self)
29    }
30}
31impl Row {
32    pub fn new() -> Self {
33        Self { cells: vec![] }
34    }
35
36    pub fn with_cells(cells: Vec<Component>) -> Self {
37        Self { cells }
38    }
39}
40/// Tables!
41#[derive(Debug, Clone)]
42pub struct Table {
43    col: usize,
44    rows: Vec<Component>,
45    head: Row,
46}
47impl AsLatex for Table {
48    fn to_string(&self) -> String {
49        let s = (0..self.col).fold("|".to_string(), |acc, _x| acc + "c|");
50        let rows = self.rows.iter().map(|x| x.to_string()).collect::<String>();
51        format!(
52            "\\begin{{tabular}}{{{}}} \n \\hline \n {} \n \\hline \n {} \\hline \\end{{tabular}} ",
53            s,
54            self.head.to_string(),
55            rows
56        )
57    }
58}
59impl Populate for Table {
60    fn attach(&mut self, other: Component) -> TexResult<&mut Self> {
61        self.rows.push(other);
62        Ok(self)
63    }
64    fn attach_vec(&mut self, other: Vec<Component>) -> TexResult<&mut Self> {
65        self.attach_iter(other.into_iter())
66    }
67
68    fn attach_iter<I: Iterator<Item = Component>>(&mut self, other: I) -> TexResult<&mut Self> {
69        self.rows.extend(other);
70        Ok(self)
71    }
72}
73impl Table {
74    pub fn new(col: usize, head: Row) -> Self {
75        Self {
76            col,
77            rows: vec![],
78            head,
79        }
80    }
81
82    pub fn with_rows(col: usize, head: Row, rows: Vec<Component>) -> Self {
83        Self { col, rows, head }
84    }
85}