Skip to main content

comfy_table/
row.rs

1use std::slice::Iter;
2
3use crate::{
4    cell::{Cell, Cells},
5    utils::formatting::content_split::measure_text_width,
6};
7
8/// Each row contains [Cells](crate::Cell) and can be added to a [Table](crate::Table).
9#[derive(Clone, Debug, Default)]
10pub struct Row {
11    /// Index of the row.
12    /// This will be set as soon as the row is added to the table.
13    pub(crate) index: Option<usize>,
14    pub(crate) cells: Vec<Cell>,
15    pub(crate) max_height: Option<usize>,
16}
17
18impl Row {
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    /// Add a cell to the row.
24    ///
25    /// **Attention:**
26    /// If a row has already been added to a table and you add more cells to it
27    /// than there're columns currently know to the [Table](crate::Table) struct,
28    /// these columns won't be known to the table unless you call
29    /// [crate::Table::discover_columns].
30    ///
31    /// ```rust
32    /// use comfy_table::{Cell, Row};
33    ///
34    /// let mut row = Row::new();
35    /// row.add_cell(Cell::new("One"));
36    /// ```
37    pub fn add_cell(&mut self, cell: Cell) -> &mut Self {
38        self.cells.push(cell);
39
40        self
41    }
42
43    /// Truncate content of cells which occupies more than X lines of space.
44    ///
45    /// At least one line of content is always shown, hence a value of `0` is
46    /// implicitly treated as `1`.
47    ///
48    /// ```
49    /// use comfy_table::{Cell, Row};
50    ///
51    /// let mut row = Row::new();
52    /// row.max_height(5);
53    /// ```
54    pub fn max_height(&mut self, lines: usize) -> &mut Self {
55        self.max_height = Some(lines.max(1));
56
57        self
58    }
59
60    /// Get the longest content width for all cells of this row
61    pub(crate) fn max_content_widths(&self) -> Vec<usize> {
62        // Iterate over all cells
63        self.cells
64            .iter()
65            .map(|cell| {
66                // Iterate over all content strings and return a vector of string widths.
67                // Each entry represents the longest string width for a cell.
68                cell.content
69                    .iter()
70                    .map(|string| measure_text_width(string))
71                    .max()
72                    .unwrap_or(0)
73            })
74            .collect()
75    }
76
77    /// Get the amount of cells on this row.
78    pub fn cell_count(&self) -> usize {
79        self.cells.len()
80    }
81
82    /// Returns an iterator over all cells of this row
83    pub fn cell_iter(&self) -> Iter<'_, Cell> {
84        self.cells.iter()
85    }
86}
87
88/// Create a Row from any `Into<Cells>`. \
89/// [Cells] is a simple wrapper around a `Vec<Cell>`.
90///
91/// Check the [From] implementations on [Cell] for more information.
92///
93/// ```rust
94/// use comfy_table::{Cell, Row};
95///
96/// let row = Row::from(vec!["One", "Two", "Three"]);
97/// let row = Row::from(vec![Cell::new("One"), Cell::new("Two"), Cell::new("Three")]);
98/// let row = Row::from(vec![1, 2, 3, 4]);
99/// ```
100impl<T: Into<Cells>> From<T> for Row {
101    fn from(cells: T) -> Self {
102        Self {
103            index: None,
104            cells: cells.into().0,
105            max_height: None,
106        }
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn test_correct_max_content_width() {
116        let row = Row::from(vec![
117            "",
118            "four",
119            "fivef",
120            "sixsix",
121            "11 but with\na newline",
122        ]);
123
124        let max_content_widths = row.max_content_widths();
125
126        assert_eq!(max_content_widths, vec![0, 4, 5, 6, 11]);
127    }
128
129    #[test]
130    fn test_some_functions() {
131        let cells = ["one", "two", "three"];
132        let mut row = Row::new();
133        for cell in cells.iter() {
134            row.add_cell(Cell::new(cell));
135        }
136        assert_eq!(row.cell_count(), cells.len());
137
138        let mut cell_content_iter = cells.iter();
139        for cell in row.cell_iter() {
140            assert_eq!(
141                cell.content(),
142                cell_content_iter.next().unwrap().to_string()
143            );
144        }
145    }
146}