Skip to content

Commit

Permalink
Add column helper methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Techassi committed Sep 7, 2023
1 parent af3924c commit deed3e1
Show file tree
Hide file tree
Showing 3 changed files with 144 additions and 3 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Add helper methods `(col,row)_count` and `is_empty`. The first set of methods return the number of columns and rows
respectively. The method `is_empty` returns if the table is empty (contains no data rows). Implemented by
[Techassi](https://github.com/Techassi) in [#119](https://github.com/Nukesor/comfy-table/pull/119).
- Add four new methods for dynamically adding new columns to the header: `add_column`, `add_column_if`, `add_columns`,
and `add_columns_if`. Implemented by [Techassi](https://github.com/Techassi) in [#CHANGEME]().

## [7.0.1] - 2023-06-16

## Fix

- Fix a panic when working with extreme paddings, where `(padding.left + padding.right) > u16::MAX`.
- Fix a panic when working with extremely long content, where `(content_width + padding) > u16::MAX`.
- Properly enforce lower boundery constraints.
- Properly enforce lower boundary constraints.
Previously, "normal" columns were allocated before lower boundaries were respected.
This could lead to scenarios, where the table would grow beyond the specified size, when there was a lower boundary.
- Fix calculation of column widths for empty columns.
Expand Down
122 changes: 120 additions & 2 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,109 @@ impl Table {
self.columns.len()
}

/// Adds a column with `column_name` to the header. If the header is already
/// present, the new column gets appended to the end. Otherwise, a header
/// with one column will be created.
///
/// ```
/// use comfy_table::Table;
///
/// let mut table = Table::new();
/// table.set_header(vec!["Col 1", "Col 2", "Col 3"]);
/// table.add_column("Col 4");
///
/// assert_eq!(table.column_count(), 4);
/// ```
pub fn add_column<T>(&mut self, column_name: T) -> &mut Self
where
T: ToString,
{
match &mut self.header {
Some(header) => {
header.add_cell(column_name.into());
self.discover_header_columns()
}
None => {
self.set_header(vec![column_name]);
}
};

self
}

/// Adds a new column with `column_name` to the header if the `predicate`
/// evaluates to `true`. If the header is already present, the new column
/// gets appended to the end. Otherwise, a header with one column will be
/// created.
///
/// ```
/// use comfy_table::Table;
///
/// let mut table = Table::new();
/// table.set_header(vec!["Col 1", "Col 2", "Col 3"]);
/// table.add_column_if(|index, column| true, "Col 4");
///
/// assert_eq!(table.column_count(), 4);
/// ```
pub fn add_column_if<P, T>(&mut self, predicate: P, column_name: T) -> &mut Self
where
P: Fn(usize, &T) -> bool,
T: ToString,
{
if predicate(self.column_count(), &column_name) {
return self.add_column(column_name);
}

self
}

/// Adds new columns to the header.
///
/// ```
/// use comfy_table::Table;
///
/// let mut table = Table::new();
/// table.set_header(vec!["Col 1", "Col 2", "Col 3"]);
/// table.add_columns(vec!["Col 4", "Col 5"]);
///
/// assert_eq!(table.column_count(), 5);
/// ```
pub fn add_columns<I>(&mut self, column_names: I) -> &mut Self
where
I: IntoIterator,
I::Item: ToString,
{
for column_name in column_names.into_iter() {
self.add_column(column_name);
}

self
}

/// Adds new columns to the header if `predicate` evaluates to `true`.
///
/// ```
/// use comfy_table::Table;
///
/// let mut table = Table::new();
/// table.set_header(vec!["Col 1", "Col 2", "Col 3"]);
/// table.add_columns_if(|index, columns| true, vec!["Col 4", "Col 5"]);
///
/// assert_eq!(table.column_count(), 5);
/// ```
pub fn add_columns_if<P, I>(&mut self, predicate: P, column_names: I) -> &mut Self
where
P: Fn(usize, &I) -> bool,
I: IntoIterator,
I::Item: ToString,
{
if predicate(self.column_count(), &column_names) {
return self.add_columns(column_names);
}

self
}

/// Add a new row to the table.
///
/// ```
Expand Down Expand Up @@ -165,7 +268,7 @@ impl Table {
P: Fn(usize, &T) -> bool,
T: Into<Row>,
{
if predicate(self.rows.len(), &row) {
if predicate(self.row_count(), &row) {
return self.add_row(row);
}

Expand Down Expand Up @@ -217,7 +320,7 @@ impl Table {
I: IntoIterator,
I::Item: Into<Row>,
{
if predicate(self.rows.len(), &rows) {
if predicate(self.row_count(), &rows) {
return self.add_rows(rows);
}

Expand Down Expand Up @@ -789,6 +892,21 @@ impl Table {
}
}
}

/// Calling this might be necessary if you add new cells to the table
/// header.
fn discover_header_columns(&mut self) {
match &self.header {
Some(header) => {
if header.cell_count() > self.columns.len() {
for index in self.columns.len()..header.cell_count() {
self.columns.push(Column::new(index));
}
}
}
None => (),
}
}
}

/// An iterator over cells of a specific column.
Expand Down
21 changes: 21 additions & 0 deletions tests/all/simple_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,24 @@ fn lines() {

assert_eq!(actual.collect::<Vec<String>>(), expected);
}

#[test]
fn add_column() {
let mut table = Table::new();
table
.set_header(&vec!["Header1", "Header2", "Header3"])
.add_row(&vec!["One One", "One Two", "One Three"])
.add_column("Header4")
.add_row(&vec!["Two One", "Two Two", "Two Three", "Two Four"]);

println!("{table}");
let expected = "
+---------+---------+-----------+----------+
| Header1 | Header2 | Header3 | Header4 |
+==========================================+
| One One | One Two | One Three | |
|---------+---------+-----------+----------|
| Two One | Two Two | Two Three | Two Four |
+---------+---------+-----------+----------+";
assert_eq!(expected, "\n".to_string() + &table.to_string());
}

0 comments on commit deed3e1

Please sign in to comment.