comfy_table/utils/arrangement/
helper.rs

1use super::DisplayInfos;
2use crate::utils::formatting::borders::{
3    should_draw_left_border, should_draw_right_border, should_draw_vertical_lines,
4};
5use crate::{Cell, Column, Table};
6
7/// The ColumnDisplayInfo works with a fixed value for content width.
8/// However, if a column is supposed to get a absolute width, we have to make sure that
9/// the padding on top of the content width doesn't get larger than the specified absolute width.
10///
11/// For this reason, we take the targeted width, subtract the column's padding and make sure that
12/// the content width is always a minimum of 1
13pub fn absolute_width_with_padding(column: &Column, width: u16) -> u16 {
14    let mut content_width = width
15        .saturating_sub(column.padding.0)
16        .saturating_sub(column.padding.1);
17    if content_width == 0 {
18        content_width = 1;
19    }
20
21    content_width
22}
23
24/// Return the amount of visible columns
25pub fn count_visible_columns(columns: &[Column]) -> usize {
26    columns.iter().filter(|column| !column.is_hidden()).count()
27}
28
29/// Return the amount of visible columns that haven't been checked yet.
30///
31/// - `column_count` is the total amount of columns that are visible, calculated
32///   with [count_visible_columns].
33/// - `infos` are all columns that have already been fixed in size or are hidden.
34pub fn count_remaining_columns(column_count: usize, infos: &DisplayInfos) -> usize {
35    column_count - infos.iter().filter(|(_, info)| !info.is_hidden).count()
36}
37
38/// Return the amount of border columns, that will be visible in the final table output.
39pub fn count_border_columns(table: &Table, visible_columns: usize) -> usize {
40    let mut lines = 0;
41    // Remove space occupied by borders from remaining_width
42    if should_draw_left_border(table) {
43        lines += 1;
44    }
45    if should_draw_right_border(table) {
46        lines += 1;
47    }
48    if should_draw_vertical_lines(table) {
49        lines += visible_columns.saturating_sub(1);
50    }
51
52    lines
53}
54
55/// Get the delimiter for a Cell.
56/// Priority is in decreasing order: Cell -> Column -> Table.
57pub fn delimiter(table: &Table, column: &Column, cell: &Cell) -> char {
58    // Determine, which delimiter should be used
59    if let Some(delimiter) = cell.delimiter {
60        delimiter
61    } else if let Some(delimiter) = column.delimiter {
62        delimiter
63    } else if let Some(delimiter) = table.delimiter {
64        delimiter
65    } else {
66        ' '
67    }
68}