Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add column helper methods #126

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
- x86_64-pc-windows-msvc
- x86_64-apple-darwin
- wasm32-wasi
toolchain: [stable, nightly, 1.64]
toolchain: [stable, nightly, 1.70]
include:
- target: x86_64-unknown-linux-gnu
os: ubuntu-latest
Expand Down
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
81 changes: 81 additions & 0 deletions tests/all/simple_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,84 @@ 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());
}

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

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

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

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

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

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