From 6bf66516b5ca354599d927efbd60fec257c2c0a4 Mon Sep 17 00:00:00 2001 From: pinkforest <36498018+pinkforest@users.noreply.github.com> Date: Tue, 27 Dec 2022 16:04:46 +1100 Subject: [PATCH] Fix fmt --- examples/basic.rs | 24 ++- examples/csv.rs | 14 +- examples/formatting.rs | 51 +++-- examples/multiline.rs | 16 +- examples/slices.rs | 11 +- examples/span.rs | 22 +-- examples/style.rs | 22 +-- examples/tictactoe.rs | 2 +- src/cell.rs | 38 ++-- src/csv.rs | 106 +++++++---- src/evcxr.rs | 2 +- src/format.rs | 85 +++++---- src/lib.rs | 420 ++++++++++++++++++++++++++++++----------- src/main.rs | 24 +-- src/row.rs | 97 ++++++---- src/utils.rs | 44 +++-- 16 files changed, 642 insertions(+), 336 deletions(-) diff --git a/examples/basic.rs b/examples/basic.rs index 0bbab1f226..913ef8d352 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -1,4 +1,4 @@ -use prettytable::{Table, Row, Cell, row, table, ptable}; +use prettytable::{ptable, row, table, Cell, Row, Table}; /* Following main function will print : @@ -22,19 +22,27 @@ fn main() { let mut table = Table::new(); table.add_row(row!["ABC", "DEFG", "HIJKLMN"]); table.add_row(row!["foobar", "bar", "foo"]); - table.add_row(Row::new(vec![Cell::new("foobar2"), Cell::new("bar2"), Cell::new("foo2")])); + table.add_row(Row::new(vec![ + Cell::new("foobar2"), + Cell::new("bar2"), + Cell::new("foo2"), + ])); table.printstd(); println!("Modified : "); table.set_element("new_foo", 2, 1).unwrap(); table.printstd(); // The same table can be built the following way : - let _table = table!(["ABC", "DEFG", "HIJKLMN"], - ["foobar", "bar", "foo"], - ["foobar2", "bar2", "foo2"]); + let _table = table!( + ["ABC", "DEFG", "HIJKLMN"], + ["foobar", "bar", "foo"], + ["foobar2", "bar2", "foo2"] + ); // Or directly print it like this - let _table = ptable!(["ABC", "DEFG", "HIJKLMN"], - ["foobar", "bar", "foo"], - ["foobar2", "bar2", "foo2"]); + let _table = ptable!( + ["ABC", "DEFG", "HIJKLMN"], + ["foobar", "bar", "foo"], + ["foobar2", "bar2", "foo2"] + ); } diff --git a/examples/csv.rs b/examples/csv.rs index 4a94afbe11..37c897ac62 100644 --- a/examples/csv.rs +++ b/examples/csv.rs @@ -16,15 +16,19 @@ fn main() { use prettytable::Table; - let table = Table::from_csv_string("ABC,DEFG,HIJKLMN\n\ + let table = Table::from_csv_string( + "ABC,DEFG,HIJKLMN\n\ foobar,bar,foo\n\ - foobar2,bar2,foo2") - .unwrap(); + foobar2,bar2,foo2", + ) + .unwrap(); table.printstd(); println!(""); - println!("{}", - String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap()); + println!( + "{}", + String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap() + ); } #[cfg(not(feature = "csv"))] diff --git a/examples/formatting.rs b/examples/formatting.rs index e6e9aa0afc..430568783b 100644 --- a/examples/formatting.rs +++ b/examples/formatting.rs @@ -1,4 +1,4 @@ -use prettytable::{format, table, row}; +use prettytable::{format, row, table}; fn main() { let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]); @@ -49,14 +49,17 @@ fn main() { // | Value three | Value four | // +-------------+------------+ println!("Custom :"); - table.set_format(format::FormatBuilder::new() - .column_separator('|') - .borders('|') - .separators(&[format::LinePosition::Top, - format::LinePosition::Bottom], - format::LineSeparator::new('-', '+', '+', '+')) - .padding(1, 1) - .build()); + table.set_format( + format::FormatBuilder::new() + .column_separator('|') + .borders('|') + .separators( + &[format::LinePosition::Top, format::LinePosition::Bottom], + format::LineSeparator::new('-', '+', '+', '+'), + ) + .padding(1, 1) + .build(), + ); table.printstd(); // Customized format with unicode @@ -69,17 +72,25 @@ fn main() { // │ Value three │ Value four │ // └─────────────┴────────────┘ println!("With unicode:"); - table.set_format(format::FormatBuilder::new() - .column_separator('│') - .borders('│') - .separators(&[format::LinePosition::Top], - format::LineSeparator::new('─', '┬', '┌', '┐')) - .separators(&[format::LinePosition::Intern], - format::LineSeparator::new('─', '┼', '├', '┤')) - .separators(&[format::LinePosition::Bottom], - format::LineSeparator::new('─', '┴', '└', '┘')) - .padding(1, 1) - .build()); + table.set_format( + format::FormatBuilder::new() + .column_separator('│') + .borders('│') + .separators( + &[format::LinePosition::Top], + format::LineSeparator::new('─', '┬', '┌', '┐'), + ) + .separators( + &[format::LinePosition::Intern], + format::LineSeparator::new('─', '┼', '├', '┤'), + ) + .separators( + &[format::LinePosition::Bottom], + format::LineSeparator::new('─', '┴', '└', '┘'), + ) + .padding(1, 1) + .build(), + ); table.printstd(); // Customized format with unicode and different padding diff --git a/examples/multiline.rs b/examples/multiline.rs index 143815dce9..81070f4135 100644 --- a/examples/multiline.rs +++ b/examples/multiline.rs @@ -18,11 +18,15 @@ use prettytable::table; +-------------------------+------------------------------+ */ fn main() { - let table1 = table!(["ABC", "DEFG", "HIJKLMN"], - ["foobar", "bar", "foo"], - ["foobar2", "bar2", "foo2"]); - let table2 = table!(["Title 1", "Title 2"], - ["This is\na multiline\ncell", "foo"], - ["Yo dawg ;) You can even\nprint tables\ninto tables", table1]); + let table1 = table!( + ["ABC", "DEFG", "HIJKLMN"], + ["foobar", "bar", "foo"], + ["foobar2", "bar2", "foo2"] + ); + let table2 = table!( + ["Title 1", "Title 2"], + ["This is\na multiline\ncell", "foo"], + ["Yo dawg ;) You can even\nprint tables\ninto tables", table1] + ); table2.printstd(); } diff --git a/examples/slices.rs b/examples/slices.rs index 9130718daf..812511ad2c 100644 --- a/examples/slices.rs +++ b/examples/slices.rs @@ -1,7 +1,14 @@ -use prettytable::{Slice, table, row}; +use prettytable::{row, table, Slice}; fn main() { - let mut table = table![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]]; + let mut table = table![ + [0, 0, 0], + [1, 1, 1], + [2, 2, 2], + [3, 3, 3], + [4, 4, 4], + [5, 5, 5] + ]; table.set_titles(row!["t1", "t2", "t3"]); let slice = table.slice(..); diff --git a/examples/span.rs b/examples/span.rs index 5c3b4e294f..53ae3b51bd 100644 --- a/examples/span.rs +++ b/examples/span.rs @@ -1,8 +1,6 @@ -use prettytable::{Row, Cell, format::Alignment, table}; - +use prettytable::{format::Alignment, table, Cell, Row}; fn main() { - /* The following code will output @@ -18,12 +16,14 @@ fn main() { */ let mut table: prettytable::Table = table![ - [H2 -> "This is a cell with span of 2", "span of 1"], - ["span of 1", "span of 1", "span of 1"], - [H03c -> "This cell with a span of 3 is centered"] - ]; - table.set_titles(Row::new(vec![ - Cell::new_align("A table with horizontal span", Alignment::CENTER).with_hspan(3) - ])); + [H2 -> "This is a cell with span of 2", "span of 1"], + ["span of 1", "span of 1", "span of 1"], + [H03c -> "This cell with a span of 3 is centered"] + ]; + table.set_titles(Row::new(vec![Cell::new_align( + "A table with horizontal span", + Alignment::CENTER, + ) + .with_hspan(3)])); table.printstd(); -} \ No newline at end of file +} diff --git a/examples/style.rs b/examples/style.rs index ad3c4e3f1c..6d5ca70840 100644 --- a/examples/style.rs +++ b/examples/style.rs @@ -1,6 +1,6 @@ -use prettytable::{Table, Row, Cell}; -use prettytable::{Attr, color}; -use prettytable::{table, row, cell, ptable}; +use prettytable::{cell, ptable, row, table}; +use prettytable::{color, Attr}; +use prettytable::{Cell, Row, Table}; #[allow(dead_code)] fn main() { @@ -11,14 +11,14 @@ fn main() { // Add style to a full row table.add_row(row![FY => "styled", "bar", "foo"]); table.add_row(Row::new(vec![ - Cell::new("foobar2"), - // Create a cell with a red foreground color - Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)), - // Create a cell with red foreground color, yellow background color, with bold characters - Cell::new("foo2").style_spec("FrByb"), - // Using the cell! macro - cell!(Fr->"red")]) - ); + Cell::new("foobar2"), + // Create a cell with a red foreground color + Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)), + // Create a cell with red foreground color, yellow background color, with bold characters + Cell::new("foo2").style_spec("FrByb"), + // Using the cell! macro + cell!(Fr->"red"), + ])); table.printstd(); diff --git a/examples/tictactoe.rs b/examples/tictactoe.rs index 0c299f95b7..14586d0aad 100644 --- a/examples/tictactoe.rs +++ b/examples/tictactoe.rs @@ -1,4 +1,4 @@ -use prettytable::{Table, table, cell}; +use prettytable::{cell, table, Table}; use std::io; use std::io::Write; diff --git a/src/cell.rs b/src/cell.rs index 39c418bb76..b9affefbf5 100644 --- a/src/cell.rs +++ b/src/cell.rs @@ -4,8 +4,8 @@ use super::format::Alignment; use super::utils::{display_width, print_align, HtmlEscape}; use super::{color, Attr, Terminal}; use std::io::{Error, Write}; -use std::string::ToString; use std::str::FromStr; +use std::string::ToString; /// Represent a table cell containing a string. /// @@ -177,19 +177,19 @@ impl Cell { /// Return the height of the cell // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn get_height(&self) -> usize { + pub(crate) fn get_height(&self) -> usize { self.content.len() } /// Return the width of the cell // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn get_width(&self) -> usize { + pub(crate) fn get_width(&self) -> usize { self.width } /// Set horizontal span for this cell (must be > 0) pub fn set_hspan(&mut self, hspan: usize) { - self.hspan = if hspan == 0 {1} else {hspan}; + self.hspan = if hspan == 0 { 1 } else { hspan }; } /// Get horizontal span of this cell (> 0) @@ -207,7 +207,7 @@ impl Cell { /// fill the cells with blanks so it fits in the table. /// If `ìdx` is higher than this cell's height, it will print empty content // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn print( + pub(crate) fn print( &self, out: &mut T, idx: usize, @@ -220,7 +220,7 @@ impl Cell { /// Apply style then call `print` to print the cell into a terminal // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn print_term( + pub(crate) fn print_term( &self, out: &mut T, idx: usize, @@ -393,8 +393,8 @@ macro_rules! cell { mod tests { use super::Cell; use crate::format::Alignment; - use term::{color, Attr}; use crate::utils::StringWriter; + use term::{color, Attr}; #[test] fn get_content() { @@ -438,7 +438,10 @@ mod tests { let mut out = StringWriter::new(); let _ = ascii_cell.print_html(&mut out); - assert_eq!(out.as_string(), r#"hello"#); + assert_eq!( + out.as_string(), + r#"hello"# + ); } #[test] @@ -447,7 +450,10 @@ mod tests { let mut out = StringWriter::new(); let _ = ascii_cell.print_html(&mut out); - assert_eq!(out.as_string(), r#"<abc">&'"#); + assert_eq!( + out.as_string(), + r#"<abc">&'"# + ); } #[test] @@ -482,18 +488,16 @@ mod tests { assert!(cell.style.contains(&Attr::Italic(true))); assert!(cell.style.contains(&Attr::Bold)); assert!(cell.style.contains(&Attr::ForegroundColor(color::RED))); - assert!( - cell.style - .contains(&Attr::BackgroundColor(color::BRIGHT_BLUE)) - ); + assert!(cell + .style + .contains(&Attr::BackgroundColor(color::BRIGHT_BLUE))); assert_eq!(cell.align, Alignment::CENTER); cell = cell.style_spec("FDBwr"); assert_eq!(cell.style.len(), 2); - assert!( - cell.style - .contains(&Attr::ForegroundColor(color::BRIGHT_BLACK)) - ); + assert!(cell + .style + .contains(&Attr::ForegroundColor(color::BRIGHT_BLACK))); assert!(cell.style.contains(&Attr::BackgroundColor(color::WHITE))); assert_eq!(cell.align, Alignment::RIGHT); diff --git a/src/csv.rs b/src/csv.rs index db70328481..dac4f0e85f 100644 --- a/src/csv.rs +++ b/src/csv.rs @@ -2,10 +2,10 @@ use csv; -pub use self::csv::{Reader, Writer, Result, ReaderBuilder}; +pub use self::csv::{Reader, ReaderBuilder, Result, Writer}; use crate::AsTableSlice; -use std::path::Path; use std::io::{Read, Write}; +use std::path::Path; impl<'a> super::TableSlice<'a> { /// Write the table to the specified writer. @@ -16,9 +16,7 @@ impl<'a> super::TableSlice<'a> { /// Write the table to the specified writer. /// /// This allows for format customisation. - pub fn to_csv_writer(&self, - mut writer: Writer) - -> Result> { + pub fn to_csv_writer(&self, mut writer: Writer) -> Result> { for title in self.titles { writer.write_record(title.iter().map(|c| c.get_content()))?; } @@ -39,7 +37,8 @@ impl super::Table { Ok(Self::from_csv( &mut ReaderBuilder::new() .has_headers(false) - .from_reader(csv_s.as_bytes()))) + .from_reader(csv_s.as_bytes()), + )) } /// Create a table from a CSV file @@ -47,25 +46,27 @@ impl super::Table { /// For more customisability use `from_csv()` pub fn from_csv_file>(csv_p: P) -> Result { Ok(Self::from_csv( - &mut ReaderBuilder::new() - .has_headers(false) - .from_path(csv_p)?)) + &mut ReaderBuilder::new().has_headers(false).from_path(csv_p)?, + )) } /// Create a table from a CSV reader pub fn from_csv(reader: &mut Reader) -> Self { - Self::init(reader - .records() - .map(|row| { - super::Row::new(row.unwrap() - .into_iter() - .map(|cell| super::Cell::new(&cell)) - .collect()) - }) - .collect()) + Self::init( + reader + .records() + .map(|row| { + super::Row::new( + row.unwrap() + .into_iter() + .map(|cell| super::Cell::new(&cell)) + .collect(), + ) + }) + .collect(), + ) } - /// Write the table to the specified writer. pub fn to_csv(&self, w: W) -> Result> { self.as_slice().to_csv(w) @@ -79,10 +80,9 @@ impl super::Table { } } - #[cfg(test)] mod tests { - use crate::{Table, Row, Cell}; + use crate::{Cell, Row, Table}; static CSV_S: &str = "ABC,DEFG,HIJKLMN\n\ foobar,bar,foo\n\ @@ -90,22 +90,33 @@ mod tests { fn test_table() -> Table { let mut table = Table::new(); - table - .add_row(Row::new(vec![Cell::new("ABC"), Cell::new("DEFG"), Cell::new("HIJKLMN")])); - table.add_row(Row::new(vec![Cell::new("foobar"), Cell::new("bar"), Cell::new("foo")])); - table.add_row(Row::new(vec![Cell::new("foobar2"), - Cell::new("bar2"), - Cell::new("foo2")])); + table.add_row(Row::new(vec![ + Cell::new("ABC"), + Cell::new("DEFG"), + Cell::new("HIJKLMN"), + ])); + table.add_row(Row::new(vec![ + Cell::new("foobar"), + Cell::new("bar"), + Cell::new("foo"), + ])); + table.add_row(Row::new(vec![ + Cell::new("foobar2"), + Cell::new("bar2"), + Cell::new("foo2"), + ])); table } #[test] fn from() { - assert_eq!(test_table().to_string().replace("\r\n", "\n"), - Table::from_csv_string(CSV_S) - .unwrap() - .to_string() - .replace("\r\n", "\n")); + assert_eq!( + test_table().to_string().replace("\r\n", "\n"), + Table::from_csv_string(CSV_S) + .unwrap() + .to_string() + .replace("\r\n", "\n") + ); } #[test] @@ -117,8 +128,10 @@ mod tests { .unwrap() .into_inner() .unwrap() - ).unwrap(), - CSV_S); + ) + .unwrap(), + CSV_S + ); } #[test] @@ -131,21 +144,34 @@ mod tests { .unwrap() .into_inner() .unwrap() - ).unwrap() - ).unwrap() + ) + .unwrap() + ) + .unwrap() .to_string() .replace("\r\n", "\n"), - test_table().to_string().replace("\r\n", "\n")); + test_table().to_string().replace("\r\n", "\n") + ); } #[test] fn extend_table() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("ABC"), Cell::new("DEFG"), Cell::new("HIJKLMN")])); + table.add_row(Row::new(vec![ + Cell::new("ABC"), + Cell::new("DEFG"), + Cell::new("HIJKLMN"), + ])); table.extend(vec![vec!["A", "B", "C"]]); let t2 = table.clone(); table.extend(t2.rows); - assert_eq!(table.get_row(1).unwrap().get_cell(2).unwrap().get_content(), "C"); - assert_eq!(table.get_row(2).unwrap().get_cell(1).unwrap().get_content(), "DEFG"); + assert_eq!( + table.get_row(1).unwrap().get_cell(2).unwrap().get_content(), + "C" + ); + assert_eq!( + table.get_row(2).unwrap().get_cell(1).unwrap().get_content(), + "DEFG" + ); } } diff --git a/src/evcxr.rs b/src/evcxr.rs index 6df05efd5e..2dbe41afde 100644 --- a/src/evcxr.rs +++ b/src/evcxr.rs @@ -1,7 +1,7 @@ //! This modules contains traits and implementations to work within Evcxr -use super::AsTableSlice; use super::utils::StringWriter; +use super::AsTableSlice; use std::io::Write; /// Evcxr specific output trait diff --git a/src/format.rs b/src/format.rs index 10bee2697d..5ddaeb104c 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,6 +1,6 @@ //! Define table formatting utilities -use std::io::{Write, Error}; +use std::io::{Error, Write}; use encode_unicode::Utf8Char; @@ -69,14 +69,15 @@ impl LineSeparator { /// Print a full line separator to `out`. `col_width` is a slice containing the width of each column. /// Returns the number of printed lines - fn print(&self, - out: &mut T, - col_width: &[usize], - padding: (usize, usize), - colsep: bool, - lborder: bool, - rborder: bool) - -> Result { + fn print( + &self, + out: &mut T, + col_width: &[usize], + padding: (usize, usize), + colsep: bool, + lborder: bool, + rborder: bool, + ) -> Result { if lborder { out.write_all(Utf8Char::from(self.ljunc).as_bytes())?; } @@ -180,11 +181,11 @@ impl TableFormat { /// Set a line separator pub fn separator(&mut self, what: LinePosition, separator: LineSeparator) { *match what { - LinePosition::Top => &mut self.top_sep, - LinePosition::Bottom => &mut self.bottom_sep, - LinePosition::Title => &mut self.tsep, - LinePosition::Intern => &mut self.lsep, - } = Some(separator); + LinePosition::Top => &mut self.top_sep, + LinePosition::Bottom => &mut self.bottom_sep, + LinePosition::Title => &mut self.tsep, + LinePosition::Intern => &mut self.lsep, + } = Some(separator); } /// Set format for multiple kind of line separator @@ -199,12 +200,10 @@ impl TableFormat { LinePosition::Intern => &self.lsep, LinePosition::Top => &self.top_sep, LinePosition::Bottom => &self.bottom_sep, - LinePosition::Title => { - match &self.tsep { - s @ &Some(_) => s, - &None => &self.lsep, - } - } + LinePosition::Title => match &self.tsep { + s @ &Some(_) => s, + &None => &self.lsep, + }, } } @@ -221,21 +220,24 @@ impl TableFormat { /// Print a full line separator to `out`. `col_width` is a slice containing the width of each column. /// Returns the number of printed lines // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn print_line_separator(&self, - out: &mut T, - col_width: &[usize], - pos: LinePosition) - -> Result { + pub(crate) fn print_line_separator( + &self, + out: &mut T, + col_width: &[usize], + pos: LinePosition, + ) -> Result { match *self.get_sep_for_line(pos) { Some(ref l) => { //TODO: Wrap this into dedicated function one day out.write_all(&vec![b' '; self.get_indent()])?; - l.print(out, - col_width, - self.get_padding(), - self.csep.is_some(), - self.lborder.is_some(), - self.rborder.is_some()) + l.print( + out, + col_width, + self.get_padding(), + self.csep.is_some(), + self.lborder.is_some(), + self.rborder.is_some(), + ) } None => Ok(0), } @@ -253,10 +255,11 @@ impl TableFormat { /// Print a column separator or a table border // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn print_column_separator(&self, - out: &mut T, - pos: ColumnPosition) - -> Result<(), Error> { + pub(crate) fn print_column_separator( + &self, + out: &mut T, + pos: ColumnPosition, + ) -> Result<(), Error> { match self.get_column_separator(pos) { Some(s) => out.write_all(Utf8Char::from(s).as_bytes()), None => Ok(()), @@ -278,7 +281,9 @@ pub struct FormatBuilder { impl FormatBuilder { /// Creates a new builder pub fn new() -> FormatBuilder { - FormatBuilder { format: Box::new(TableFormat::new()) } + FormatBuilder { + format: Box::new(TableFormat::new()), + } } /// Set left and right padding @@ -343,14 +348,16 @@ impl Into for FormatBuilder { impl From for FormatBuilder { fn from(fmt: TableFormat) -> Self { - FormatBuilder { format: Box::new(fmt) } + FormatBuilder { + format: Box::new(fmt), + } } } /// Predifined formats. Those constants are lazily evaluated when /// the corresponding struct is dereferenced pub mod consts { - use super::{TableFormat, LineSeparator, FormatBuilder, LinePosition}; + use super::{FormatBuilder, LinePosition, LineSeparator, TableFormat}; lazy_static! { /// A line separator made of `-` and `+` @@ -524,7 +531,7 @@ pub mod consts { .build(); /// A table with borders and delimiters made with box characters - /// + /// /// # Example /// ```text /// ┌────┬────┬────┐ diff --git a/src/lib.rs b/src/lib.rs index 79c766d369..8d6ae39122 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,24 +1,26 @@ -#![warn(missing_docs, - unused_extern_crates, - unused_import_braces, - unused_qualifications)] +#![warn( + missing_docs, + unused_extern_crates, + unused_import_braces, + unused_qualifications +)] //! A formatted and aligned table printer written in rust #[macro_use] extern crate lazy_static; -use std::io::{self, Write, Error}; use std::fmt; +use std::io::{self, Error, Write}; use std::iter::{FromIterator, IntoIterator}; -use std::slice::{Iter, IterMut}; use std::ops::{Index, IndexMut}; +use std::slice::{Iter, IterMut}; -pub use term::{Attr, color}; -pub(crate) use term::{Terminal, stdout}; +pub use term::{color, Attr}; +pub(crate) use term::{stdout, Terminal}; mod cell; -mod row; pub mod format; +mod row; mod utils; #[cfg(feature = "csv")] @@ -27,9 +29,9 @@ pub mod csv; #[cfg(feature = "evcxr")] pub mod evcxr; -pub use row::Row; pub use cell::Cell; -use format::{TableFormat, LinePosition, consts}; +use format::{consts, LinePosition, TableFormat}; +pub use row::Row; use utils::StringWriter; /// An owned printable table @@ -138,16 +140,19 @@ impl<'a> TableSlice<'a> { /// Internal only fn __print(&self, out: &mut T, f: F) -> Result - where F: Fn(&Row, &mut T, &TableFormat, &[usize]) -> Result + where + F: Fn(&Row, &mut T, &TableFormat, &[usize]) -> Result, { let mut height = 0; // Compute columns width let col_width = self.get_all_column_width(); - height += self.format + height += self + .format .print_line_separator(out, &col_width, LinePosition::Top)?; if let Some(ref t) = *self.titles { height += f(t, out, self.format, &col_width)?; - height += self.format + height += self + .format .print_line_separator(out, &col_width, LinePosition::Title)?; } // Print rows @@ -155,11 +160,13 @@ impl<'a> TableSlice<'a> { while let Some(r) = iter.next() { height += f(r, out, self.format, &col_width)?; if iter.peek().is_some() { - height += self.format - .print_line_separator(out, &col_width, LinePosition::Intern)?; + height += + self.format + .print_line_separator(out, &col_width, LinePosition::Intern)?; } } - height += self.format + height += self + .format .print_line_separator(out, &col_width, LinePosition::Bottom)?; out.flush()?; Ok(height) @@ -223,7 +230,6 @@ impl<'a> TableSlice<'a> { out.flush()?; Ok(()) } - } impl<'a> IntoIterator for &'a TableSlice<'a> { @@ -262,7 +268,7 @@ impl Table { /// Compute and return the number of column // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] #[cfg(test)] // Only used for testing for now - pub (crate) fn get_column_num(&self) -> usize { + pub(crate) fn get_column_num(&self) -> usize { self.as_slice().get_column_num() } @@ -392,20 +398,26 @@ impl Table { pub fn print_html(&self, out: &mut T) -> Result<(), Error> { self.as_slice().print_html(out) } - } trait AsTableSlice { - fn as_slice(&self) -> TableSlice<'_> ; + fn as_slice(&self) -> TableSlice<'_>; } impl AsTableSlice for Table { fn as_slice(&self) -> TableSlice<'_> { - TableSlice { format: &self.format, titles: &self.titles, rows: &self.rows } + TableSlice { + format: &self.format, + titles: &self.titles, + rows: &self.rows, + } } } -impl AsTableSlice for T where T: AsRef { +impl AsTableSlice for T +where + T: AsRef
, +{ fn as_slice(&self) -> TableSlice<'_> { self.as_ref().as_slice() } @@ -449,7 +461,8 @@ impl<'a> fmt::Display for TableSlice<'a> { impl> FromIterator for Table { fn from_iter(iterator: T) -> Table - where T: IntoIterator + where + T: IntoIterator, { Self::init(iterator.into_iter().map(Row::from).collect()) } @@ -457,16 +470,18 @@ impl> FromIterator for Table { impl FromIterator for Table { fn from_iter(iterator: T) -> Table - where T: IntoIterator + where + T: IntoIterator, { Self::init(iterator.into_iter().collect()) } } impl From for Table - where B: ToString, - A: IntoIterator, - T: IntoIterator +where + B: ToString, + A: IntoIterator, + T: IntoIterator, { fn from(it: T) -> Table { Self::from_iter(it) @@ -497,8 +512,8 @@ impl<'a> IntoIterator for &'a mut Table { // } // } -impl > Extend for Table { - fn extend>(&mut self, iter: T) { +impl> Extend for Table { + fn extend>(&mut self, iter: T) { self.rows.extend(iter.into_iter().map(|r| r.into())); } } @@ -523,7 +538,7 @@ impl<'a> Iterator for ColumnIterMut<'a> { } } -impl <'a> AsTableSlice for TableSlice<'a> { +impl<'a> AsTableSlice for TableSlice<'a> { fn as_slice(&self) -> TableSlice<'_> { *self } @@ -535,7 +550,6 @@ impl<'a> AsRef> for TableSlice<'a> { } } - /// Trait implemented by types which can be sliced pub trait Slice<'a, E> { /// Type output after slicing @@ -545,14 +559,15 @@ pub trait Slice<'a, E> { } impl<'a, T, E> Slice<'a, E> for T - where T: AsTableSlice, - [Row]: Index +where + T: AsTableSlice, + [Row]: Index, { type Output = TableSlice<'a>; fn slice(&'a self, arg: E) -> Self::Output { - let mut sl = self.as_slice(); - sl.rows = sl.rows.index(arg); - sl + let mut sl = self.as_slice(); + sl.rows = sl.rows.index(arg); + sl } } @@ -614,16 +629,30 @@ macro_rules! ptable { #[cfg(test)] mod tests { - use crate::{Table, Slice, Row, Cell, format, AsTableSlice}; - use format::consts::{FORMAT_DEFAULT, FORMAT_NO_LINESEP, FORMAT_NO_COLSEP, FORMAT_CLEAN, FORMAT_BOX_CHARS}; use crate::utils::StringWriter; + use crate::{format, AsTableSlice, Cell, Row, Slice, Table}; + use format::consts::{ + FORMAT_BOX_CHARS, FORMAT_CLEAN, FORMAT_DEFAULT, FORMAT_NO_COLSEP, FORMAT_NO_LINESEP, + }; #[test] fn table() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); let out = "\ +-----+----+-----+ | t1 | t2 | t3 | @@ -650,9 +679,21 @@ mod tests { #[test] fn index() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); assert_eq!(table[1][1].get_content(), "bc"); table[1][1] = Cell::new("newval"); @@ -695,8 +736,16 @@ mod tests { #[test] fn get_row() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); assert!(table.get_row(12).is_none()); assert!(table.get_row(1).is_some()); assert_eq!(table.get_row(1).unwrap()[0].get_content(), "def"); @@ -718,8 +767,16 @@ mod tests { #[test] fn remove_row() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); table.remove_row(12); assert_eq!(table.len(), 2); table.remove_row(0); @@ -730,14 +787,26 @@ mod tests { #[test] fn insert_row() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.insert_row(12, - Row::new(vec![Cell::new("1"), Cell::new("2"), Cell::new("3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.insert_row( + 12, + Row::new(vec![Cell::new("1"), Cell::new("2"), Cell::new("3")]), + ); assert_eq!(table.len(), 3); assert_eq!(table[2][1].get_content(), "2"); - table.insert_row(1, - Row::new(vec![Cell::new("3"), Cell::new("4"), Cell::new("5")])); + table.insert_row( + 1, + Row::new(vec![Cell::new("3"), Cell::new("4"), Cell::new("5")]), + ); assert_eq!(table.len(), 4); assert_eq!(table[1][1].get_content(), "4"); assert_eq!(table[2][1].get_content(), "bc"); @@ -746,8 +815,16 @@ mod tests { #[test] fn set_element() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); assert!(table.set_element("foo", 12, 12).is_err()); assert!(table.set_element("foo", 1, 1).is_ok()); assert_eq!(table[1][1].get_content(), "foo"); @@ -757,9 +834,21 @@ mod tests { fn no_linesep() { let mut table = Table::new(); table.set_format(*FORMAT_NO_LINESEP); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); assert_eq!(table[1][1].get_content(), "bc"); table[1][1] = Cell::new("newval"); @@ -780,9 +869,21 @@ mod tests { fn no_colsep() { let mut table = Table::new(); table.set_format(*FORMAT_NO_COLSEP); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); assert_eq!(table[1][1].get_content(), "bc"); table[1][1] = Cell::new("newval"); @@ -808,9 +909,21 @@ mod tests { fn clean() { let mut table = Table::new(); table.set_format(*FORMAT_CLEAN); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); assert_eq!(table[1][1].get_content(), "bc"); table[1][1] = Cell::new("newval"); @@ -834,9 +947,21 @@ mod tests { let mut format = *FORMAT_DEFAULT; format.padding(2, 2); table.set_format(format); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); assert_eq!(table[1][1].get_content(), "bc"); table[1][1] = Cell::new("newval"); @@ -861,9 +986,21 @@ mod tests { #[test] fn indent() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); table.get_format().indent(8); let out = " +-----+----+-----+ | t1 | t2 | t3 | @@ -880,13 +1017,41 @@ mod tests { #[test] fn slices() { let mut table = Table::new(); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); - table.add_row(Row::new(vec![Cell::new("0"), Cell::new("0"), Cell::new("0")])); - table.add_row(Row::new(vec![Cell::new("1"), Cell::new("1"), Cell::new("1")])); - table.add_row(Row::new(vec![Cell::new("2"), Cell::new("2"), Cell::new("2")])); - table.add_row(Row::new(vec![Cell::new("3"), Cell::new("3"), Cell::new("3")])); - table.add_row(Row::new(vec![Cell::new("4"), Cell::new("4"), Cell::new("4")])); - table.add_row(Row::new(vec![Cell::new("5"), Cell::new("5"), Cell::new("5")])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); + table.add_row(Row::new(vec![ + Cell::new("0"), + Cell::new("0"), + Cell::new("0"), + ])); + table.add_row(Row::new(vec![ + Cell::new("1"), + Cell::new("1"), + Cell::new("1"), + ])); + table.add_row(Row::new(vec![ + Cell::new("2"), + Cell::new("2"), + Cell::new("2"), + ])); + table.add_row(Row::new(vec![ + Cell::new("3"), + Cell::new("3"), + Cell::new("3"), + ])); + table.add_row(Row::new(vec![ + Cell::new("4"), + Cell::new("4"), + Cell::new("4"), + ])); + table.add_row(Row::new(vec![ + Cell::new("5"), + Cell::new("5"), + Cell::new("5"), + ])); let out = "\ +----+----+----+ | t1 | t2 | t3 | @@ -904,16 +1069,31 @@ mod tests { assert_eq!(out, slice.to_string().replace("\r\n", "\n")); assert_eq!(9, slice.print(&mut StringWriter::new()).unwrap()); assert_eq!(out, table.slice(1..4).to_string().replace("\r\n", "\n")); - assert_eq!(9, table.slice(1..4).print(&mut StringWriter::new()).unwrap()); + assert_eq!( + 9, + table.slice(1..4).print(&mut StringWriter::new()).unwrap() + ); } #[test] fn test_unicode_separators() { let mut table = Table::new(); table.set_format(*FORMAT_BOX_CHARS); - table.add_row(Row::new(vec![Cell::new("1"), Cell::new("1"), Cell::new("1")])); - table.add_row(Row::new(vec![Cell::new("2"), Cell::new("2"), Cell::new("2")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("1"), + Cell::new("1"), + Cell::new("1"), + ])); + table.add_row(Row::new(vec![ + Cell::new("2"), + Cell::new("2"), + Cell::new("2"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); let out = "\ ┌────┬────┬────┐ │ t1 │ t2 │ t3 │ @@ -932,23 +1112,26 @@ mod tests { #[test] fn test_readme_format() { - // The below is lifted from the README let mut table = Table::new(); let format = format::FormatBuilder::new() .column_separator('|') .borders('|') - .separators(&[format::LinePosition::Top, - format::LinePosition::Bottom], - format::LineSeparator::new('-', '+', '+', '+')) + .separators( + &[format::LinePosition::Top, format::LinePosition::Bottom], + format::LineSeparator::new('-', '+', '+', '+'), + ) .padding(1, 1) .build(); table.set_format(format); table.set_titles(Row::new(vec![Cell::new("Title 1"), Cell::new("Title 2")])); table.add_row(Row::new(vec![Cell::new("Value 1"), Cell::new("Value 2")])); - table.add_row(Row::new(vec![Cell::new("Value three"), Cell::new("Value four")])); + table.add_row(Row::new(vec![ + Cell::new("Value three"), + Cell::new("Value four"), + ])); let out = "\ +-------------+------------+ @@ -960,8 +1143,8 @@ mod tests { println!("{}", out); println!("____"); - println!("{}", table.to_string().replace("\r\n","\n")); - assert_eq!(out, table.to_string().replace("\r\n","\n")); + println!("{}", table.to_string().replace("\r\n", "\n")); + assert_eq!(out, table.to_string().replace("\r\n", "\n")); assert_eq!(5, table.print(&mut StringWriter::new()).unwrap()); } @@ -972,7 +1155,10 @@ mod tests { table.set_titles(Row::new(vec![Cell::new("Title 1"), Cell::new("Title 2")])); table.add_row(Row::new(vec![Cell::new("Value 1"), Cell::new("Value 2")])); - table.add_row(Row::new(vec![Cell::new("Value three"), Cell::new("Value four")])); + table.add_row(Row::new(vec![ + Cell::new("Value three"), + Cell::new("Value four"), + ])); let out = "\ +-------------+------------+ @@ -984,8 +1170,8 @@ mod tests { "; println!("{}", out); println!("____"); - println!("{}", table.to_string().replace("\r\n","\n")); - assert_eq!(out, table.to_string().replace("\r\n","\n")); + println!("{}", table.to_string().replace("\r\n", "\n")); + assert_eq!(out, table.to_string().replace("\r\n", "\n")); assert_eq!(6, table.print(&mut StringWriter::new()).unwrap()); } @@ -1004,17 +1190,27 @@ mod tests { "; println!("{}", out); println!("____"); - println!("{}", table.to_string().replace("\r\n","\n")); - assert_eq!(out, table.to_string().replace("\r\n","\n")); + println!("{}", table.to_string().replace("\r\n", "\n")); + assert_eq!(out, table.to_string().replace("\r\n", "\n")); assert_eq!(4, table.print(&mut StringWriter::new()).unwrap()); } #[test] fn test_horizontal_span() { let mut table = Table::new(); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2").with_hspan(2)])); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def").style_spec("H02c"), Cell::new("a")])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2").with_hspan(2), + ])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def").style_spec("H02c"), + Cell::new("a"), + ])); let out = "\ +----+----+-----+ | t1 | t2 | @@ -1026,17 +1222,29 @@ mod tests { "; println!("{}", out); println!("____"); - println!("{}", table.to_string().replace("\r\n","\n")); - assert_eq!(out, table.to_string().replace("\r\n","\n")); + println!("{}", table.to_string().replace("\r\n", "\n")); + assert_eq!(out, table.to_string().replace("\r\n", "\n")); assert_eq!(7, table.print(&mut StringWriter::new()).unwrap()); } #[test] fn table_html() { let mut table = Table::new(); - table.add_row(Row::new(vec![Cell::new("a"), Cell::new("bc"), Cell::new("def")])); - table.add_row(Row::new(vec![Cell::new("def"), Cell::new("bc"), Cell::new("a")])); - table.set_titles(Row::new(vec![Cell::new("t1"), Cell::new("t2"), Cell::new("t3")])); + table.add_row(Row::new(vec![ + Cell::new("a"), + Cell::new("bc"), + Cell::new("def"), + ])); + table.add_row(Row::new(vec![ + Cell::new("def"), + Cell::new("bc"), + Cell::new("a"), + ])); + table.set_titles(Row::new(vec![ + Cell::new("t1"), + Cell::new("t2"), + Cell::new("t3"), + ])); let out = "\
\ \ @@ -1080,9 +1288,9 @@ mod tests { Cell::new("white on bright green").style_spec("FwBG"), Cell::new("default on blue").style_spec("Bb"), ])); - table.set_titles(Row::new(vec![ - Cell::new("span horizontal").style_spec("H3"), - ])); + table.set_titles(Row::new( + vec![Cell::new("span horizontal").style_spec("H3")], + )); let out = "\
t1t2t3
\ \ diff --git a/src/main.rs b/src/main.rs index f18461b1b7..dbe8bda7e1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,9 @@ -use prettytable::Table; -use prettytable::Row; -use prettytable::Cell; use prettytable::format::*; -use prettytable::{Attr, color}; -use prettytable::{table, row, ptable}; // Import macros +use prettytable::Cell; +use prettytable::Row; +use prettytable::Table; +use prettytable::{color, Attr}; +use prettytable::{ptable, row, table}; // Import macros // trace_macros!(true); @@ -17,12 +17,14 @@ fn main() { // Add style to a full row table.add_row(row![FY => "styled", "bar", "foo"]); table.add_row(Row::new(vec![ - Cell::new("foobar2"), - // Create a cell with a red foreground color - Cell::new_align("bar2", Alignment::CENTER).with_style(Attr::ForegroundColor(color::RED)).with_hspan(2), - // Create a cell with red foreground color, yellow background color, with bold characters - Cell::new("foo2").style_spec("FrByb")]) - ); + Cell::new("foobar2"), + // Create a cell with a red foreground color + Cell::new_align("bar2", Alignment::CENTER) + .with_style(Attr::ForegroundColor(color::RED)) + .with_hspan(2), + // Create a cell with red foreground color, yellow background color, with bold characters + Cell::new("foo2").style_spec("FrByb"), + ])); for cell in table.column_iter_mut(2) { cell.align(Alignment::RIGHT); } diff --git a/src/row.rs b/src/row.rs index ae14429f1c..4190322037 100644 --- a/src/row.rs +++ b/src/row.rs @@ -1,5 +1,5 @@ //! This module contains definition of table rows stuff -use std::io::{Write, Error}; +use std::io::{Error, Write}; use std::iter::FromIterator; use std::slice::{Iter, IterMut}; // use std::vec::IntoIter; @@ -7,9 +7,9 @@ use std::ops::{Index, IndexMut}; use super::Terminal; +use super::format::{ColumnPosition, TableFormat}; use super::utils::NEWLINE; use super::Cell; -use super::format::{TableFormat, ColumnPosition}; /// Represent a table row made of cells #[derive(Clone, Debug, Hash, PartialEq, Eq)] @@ -32,7 +32,7 @@ impl Row { /// It takes into account horizontal spanning of cells. For /// example, a cell with an hspan of 3 will add 3 column to the grid // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn column_count(&self) -> usize { + pub(crate) fn column_count(&self) -> usize { self.cells.iter().map(|c| c.get_hspan()).sum() } @@ -63,7 +63,7 @@ impl Row { /// Get the minimum width required by the cell in the column `column`. /// Return 0 if the cell does not exist in this row // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn get_column_width(&self, column: usize, format: &TableFormat) -> usize { + pub(crate) fn get_column_width(&self, column: usize, format: &TableFormat) -> usize { let mut i = 0; for c in &self.cells { if i + c.get_hspan() > column { @@ -71,8 +71,11 @@ impl Row { return c.get_width(); } let (lp, rp) = format.get_padding(); - let sep = format.get_column_separator(ColumnPosition::Intern).map(|_| 1).unwrap_or_default(); - let rem = lp + rp +sep; + let sep = format + .get_column_separator(ColumnPosition::Intern) + .map(|_| 1) + .unwrap_or_default(); + let rem = lp + rp + sep; let mut w = c.get_width(); if w > rem { w -= rem; @@ -138,13 +141,15 @@ impl Row { } /// Internal only - fn __print(&self, - out: &mut T, - format: &TableFormat, - col_width: &[usize], - f: F) - -> Result - where F: Fn(&Cell, &mut T, usize, usize, bool) -> Result<(), Error> + fn __print( + &self, + out: &mut T, + format: &TableFormat, + col_width: &[usize], + f: F, + ) -> Result + where + F: Fn(&Cell, &mut T, usize, usize, bool) -> Result<(), Error>, { let height = self.get_height(); for i in 0..height { @@ -154,29 +159,34 @@ impl Row { let (lp, rp) = format.get_padding(); let mut j = 0; let mut hspan = 0; // The additional offset caused by cell's horizontal spanning - while j+hspan < col_width.len() { + while j + hspan < col_width.len() { out.write_all(&vec![b' '; lp])?; // Left padding - // skip_r_fill skip filling the end of the last cell if there's no character - // delimiting the end of the table - let skip_r_fill = (j == col_width.len() - 1) && - format.get_column_separator(ColumnPosition::Right).is_none(); + // skip_r_fill skip filling the end of the last cell if there's no character + // delimiting the end of the table + let skip_r_fill = (j == col_width.len() - 1) + && format.get_column_separator(ColumnPosition::Right).is_none(); match self.get_cell(j) { Some(c) => { // In case of horizontal spanning, width is the sum of all spanned columns' width - let mut w = col_width[j+hspan..j+hspan+c.get_hspan()].iter().sum(); - let real_span = c.get_hspan()-1; - w += real_span * (lp + rp) + real_span * format.get_column_separator(ColumnPosition::Intern).map(|_| 1).unwrap_or_default(); + let mut w = col_width[j + hspan..j + hspan + c.get_hspan()].iter().sum(); + let real_span = c.get_hspan() - 1; + w += real_span * (lp + rp) + + real_span + * format + .get_column_separator(ColumnPosition::Intern) + .map(|_| 1) + .unwrap_or_default(); // Print cell content f(c, out, i, w, skip_r_fill)?; hspan += real_span; // Add span to offset - }, - None => f(&Cell::default(), out, i, col_width[j+hspan], skip_r_fill)?, + } + None => f(&Cell::default(), out, i, col_width[j + hspan], skip_r_fill)?, }; out.write_all(&vec![b' '; rp])?; // Right padding - if j+hspan < col_width.len() - 1 { + if j + hspan < col_width.len() - 1 { format.print_column_separator(out, ColumnPosition::Intern)?; } - j+=1; + j += 1; } format.print_column_separator(out, ColumnPosition::Right)?; out.write_all(NEWLINE)?; @@ -187,22 +197,24 @@ impl Row { /// Print the row to `out`, with `separator` as column separator, and `col_width` /// specifying the width of each columns. Returns the number of printed lines // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn print(&self, - out: &mut T, - format: &TableFormat, - col_width: &[usize]) - -> Result { + pub(crate) fn print( + &self, + out: &mut T, + format: &TableFormat, + col_width: &[usize], + ) -> Result { self.__print(out, format, col_width, Cell::print) } /// Print the row to terminal `out`, with `separator` as column separator, and `col_width` /// specifying the width of each columns. Apply style when needed. returns the number of printed lines // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] - pub (crate) fn print_term(&self, - out: &mut T, - format: &TableFormat, - col_width: &[usize]) - -> Result { + pub(crate) fn print_term( + &self, + out: &mut T, + format: &TableFormat, + col_width: &[usize], + ) -> Result { self.__print(out, format, col_width, Cell::print_term) } @@ -243,15 +255,17 @@ impl IndexMut for Row { impl FromIterator for Row { fn from_iter(iterator: T) -> Row - where T: IntoIterator + where + T: IntoIterator, { Self::new(iterator.into_iter().map(|ref e| Cell::from(e)).collect()) } } impl From for Row - where A: ToString, - T: IntoIterator +where + A: ToString, + T: IntoIterator, { fn from(it: T) -> Row { Self::from_iter(it) @@ -282,9 +296,10 @@ impl<'a> IntoIterator for &'a mut Row { } } -impl Extend for Row { - fn extend>(&mut self, iter: T) { - self.cells.extend(iter.into_iter().map(|s| Cell::new(&s.to_string()))); +impl Extend for Row { + fn extend>(&mut self, iter: T) { + self.cells + .extend(iter.into_iter().map(|s| Cell::new(&s.to_string()))); } } diff --git a/src/utils.rs b/src/utils.rs index f876735c75..1256ced7bd 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -3,13 +3,13 @@ use std::fmt; use std::io::{Error, ErrorKind, Write}; use std::str; -use unicode_width::{UnicodeWidthStr, UnicodeWidthChar}; +use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; use super::format::Alignment; -#[cfg(any(not(windows), not(feature="win_crlf")))] +#[cfg(any(not(windows), not(feature = "win_crlf")))] pub static NEWLINE: &[u8] = b"\n"; -#[cfg(all(windows, feature="win_crlf"))] +#[cfg(all(windows, feature = "win_crlf"))] pub static NEWLINE: &[u8] = b"\r\n"; /// Internal utility for writing data into a string @@ -20,7 +20,9 @@ pub struct StringWriter { impl StringWriter { /// Create a new `StringWriter` pub fn new() -> StringWriter { - StringWriter { string: String::new() } + StringWriter { + string: String::new(), + } } /// Return a reference to the internally written `String` @@ -34,8 +36,10 @@ impl Write for StringWriter { let string = match str::from_utf8(data) { Ok(s) => s, Err(e) => { - return Err(Error::new(ErrorKind::Other, - format!("Cannot decode utf8 string : {}", e))) + return Err(Error::new( + ErrorKind::Other, + format!("Cannot decode utf8 string : {}", e), + )) } }; self.string.push_str(string); @@ -51,13 +55,14 @@ impl Write for StringWriter { /// Align/fill a string and print it to `out` /// If `skip_right_fill` is set to `true`, then no space will be added after the string /// to complete alignment -pub fn print_align(out: &mut T, - align: Alignment, - text: &str, - fill: char, - size: usize, - skip_right_fill: bool) - -> Result<(), Error> { +pub fn print_align( + out: &mut T, + align: Alignment, + text: &str, + fill: char, + size: usize, + skip_right_fill: bool, +) -> Result<(), Error> { let text_len = display_width(text); let mut nfill = if text_len < size { size - text_len } else { 0 }; let n = match align { @@ -76,7 +81,6 @@ pub fn print_align(out: &mut T, Ok(()) } - /// Return the display width of a unicode string. /// This functions takes ANSI-escaped color codes into account. pub fn display_width(text: &str) -> usize { @@ -119,7 +123,13 @@ pub fn display_width(text: &str) -> usize { } } - assert!(width >= hidden, "internal error: width {} less than hidden {} on string {:?}", width, hidden, text); + assert!( + width >= hidden, + "internal error: width {} less than hidden {} on string {:?}", + width, + hidden, + text + ); width - hidden } @@ -138,14 +148,14 @@ impl<'a> fmt::Display for HtmlEscape<'a> { for (i, ch) in s.bytes().enumerate() { match ch as char { '<' | '>' | '&' | '\'' | '"' => { - fmt.write_str(&pile_o_bits[last.. i])?; + fmt.write_str(&pile_o_bits[last..i])?; let s = match ch as char { '>' => ">", '<' => "<", '&' => "&", '\'' => "'", '"' => """, - _ => unreachable!() + _ => unreachable!(), }; fmt.write_str(s)?; last = i + 1;
span horizontal