summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPierre-Henri Symoneaux <phsym@users.noreply.github.com>2018-09-25 00:45:59 +0200
committerGitHub <noreply@github.com>2018-09-25 00:45:59 +0200
commitbf7aeaeeb7c7f4c83ff6c3572877a11a68dead05 (patch)
treea01d0e0d15b7c2124fb101b081426ec0b383050e
parent94a039ff3959d1459db2dd80518a56a729dc2929 (diff)
parentb8fcf15e69db1622e8fc432b2bd1e2f4e199fc45 (diff)
Merge pull request #92 from phsym/lines_count
Printing a table returns the number of printed lines
-rw-r--r--examples/tictactoe.rs15
-rw-r--r--src/format.rs30
-rw-r--r--src/lib.rs82
-rw-r--r--src/main.rs3
-rw-r--r--src/row.rs15
5 files changed, 90 insertions, 55 deletions
diff --git a/examples/tictactoe.rs b/examples/tictactoe.rs
index 4409155..727fc8e 100644
--- a/examples/tictactoe.rs
+++ b/examples/tictactoe.rs
@@ -1,5 +1,7 @@
#[macro_use]
extern crate prettytable;
+extern crate term;
+
use prettytable::Table;
use std::io;
@@ -16,24 +18,28 @@ fn main() {
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]
];
- table.printstd();
+ let mut height = table.printstd();
let stdin = io::stdin();
let mut stdout = io::stdout();
let mut current = CROSS;
+ let mut terminal = term::stdout().unwrap();
loop {
let mut line = String::new();
print!("{} plays > ", current);
+ height += 1;
stdout.flush().unwrap();
stdin.read_line(&mut line).expect("Cannot read input");
let i = match usize::from_str(line.trim()) {
Ok(i) => i,
_ => {
println!("Bad input");
+ height += 1;
continue;
}
};
if i < 1 || i > 9 {
println!("Bad input, should be between 1 and 9");
+ height += 1;
continue;
}
let x = (i - 1) % 3;
@@ -42,11 +48,16 @@ fn main() {
let row = table.get_mut_row(y).unwrap();
if row.get_cell(x).unwrap().to_string() != EMPTY {
println!("There's already someone there");
+ height += 1;
continue;
}
row.set_cell(cell!(current), x).unwrap();
}
- table.printstd();
+ for _ in 0..height {
+ terminal.cursor_up().unwrap();
+ terminal.delete_line().unwrap();
+ }
+ height = table.printstd();
if check(&table) {
return;
}
diff --git a/src/format.rs b/src/format.rs
index 4dec4fa..ddf6713 100644
--- a/src/format.rs
+++ b/src/format.rs
@@ -67,26 +67,16 @@ impl LineSeparator {
}
}
- /// Print a full line separator to `out`. `col_width` is a slice containing the width of each column
- #[deprecated(since = "0.6.7", note = "function will become private. See [issue #57](https://github.com/phsym/prettytable-rs/pull/57) and [issue #87](https://github.com/phsym/prettytable-rs/issues/87).")]
- pub fn print<T: Write + ?Sized>(&self,
- out: &mut T,
- col_width: &[usize],
- colsep: bool,
- lborder: bool,
- rborder: bool)
- -> Result<(), Error> {
- self._print(out, col_width, (1, 1), colsep, lborder, rborder)
- }
-
- fn _print<T: Write + ?Sized>(&self,
+ /// 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<T: Write + ?Sized>(&self,
out: &mut T,
col_width: &[usize],
padding: (usize, usize),
colsep: bool,
lborder: bool,
rborder: bool)
- -> Result<(), Error> {
+ -> Result<usize, Error> {
if lborder {
out.write_all(Utf8Char::from(self.ljunc).as_bytes())?;
}
@@ -102,7 +92,8 @@ impl LineSeparator {
if rborder {
out.write_all(Utf8Char::from(self.rjunc).as_bytes())?;
}
- out.write_all(NEWLINE)
+ out.write_all(NEWLINE)?;
+ Ok(1)
}
}
@@ -227,25 +218,26 @@ impl TableFormat {
self.indent
}
- /// Print a full line separator to `out`. `col_width` is a slice containing the width of each column
+ /// 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 fn print_line_separator<T: Write + ?Sized>(&self,
out: &mut T,
col_width: &[usize],
pos: LinePosition)
- -> Result<(), Error> {
+ -> Result<usize, Error> {
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,
+ l.print(out,
col_width,
self.get_padding(),
self.csep.is_some(),
self.lborder.is_some(),
self.rborder.is_some())
}
- None => Ok(()),
+ None => Ok(0),
}
}
diff --git a/src/lib.rs b/src/lib.rs
index 9de74fe..65f8b0c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -135,39 +135,43 @@ impl<'a> TableSlice<'a> {
}
/// Internal only
- fn __print<T: Write + ?Sized, F>(&self, out: &mut T, f: F) -> Result<(), Error>
- where F: Fn(&Row, &mut T, &TableFormat, &[usize]) -> Result<(), Error>
+ fn __print<T: Write + ?Sized, F>(&self, out: &mut T, f: F) -> Result<usize, Error>
+ where F: Fn(&Row, &mut T, &TableFormat, &[usize]) -> Result<usize, Error>
{
+ let mut height = 0;
// Compute columns width
let col_width = self.get_all_column_width();
- self.format
+ height += self.format
.print_line_separator(out, &col_width, LinePosition::Top)?;
if let Some(ref t) = *self.titles {
- f(t, out, self.format, &col_width)?;
- self.format
+ height += f(t, out, self.format, &col_width)?;
+ height += self.format
.print_line_separator(out, &col_width, LinePosition::Title)?;
}
// Print rows
let mut iter = self.rows.into_iter().peekable();
while let Some(r) = iter.next() {
- f(r, out, self.format, &col_width)?;
+ height += f(r, out, self.format, &col_width)?;
if iter.peek().is_some() {
- self.format
+ height += self.format
.print_line_separator(out, &col_width, LinePosition::Intern)?;
}
}
- self.format
+ height += self.format
.print_line_separator(out, &col_width, LinePosition::Bottom)?;
- out.flush()
+ out.flush()?;
+ Ok(height)
}
- /// Print the table to `out`
- pub fn print<T: Write + ?Sized>(&self, out: &mut T) -> Result<(), Error> {
+ /// Print the table to `out` and returns the number of
+ /// line printed, or an error
+ pub fn print<T: Write + ?Sized>(&self, out: &mut T) -> Result<usize, Error> {
self.__print(out, Row::print)
}
- /// Print the table to terminal `out`, applying styles when needed
- pub fn print_term<T: Terminal + ?Sized>(&self, out: &mut T) -> Result<(), Error> {
+ /// Print the table to terminal `out`, applying styles when needed and returns the number of
+ /// line printed, or an error
+ pub fn print_term<T: Terminal + ?Sized>(&self, out: &mut T) -> Result<usize, Error> {
self.__print(out, Row::print_term)
}
@@ -177,15 +181,18 @@ impl<'a> TableSlice<'a> {
/// output is redirected to a file, or piped to another program, the output is considered
/// as not beeing tty, and ANSI escape characters won't be displayed unless `force colorize`
/// is set to `true`.
+ /// # Returns
+ /// The number of lines printed
/// # Panic
/// Panic if writing to standard output fails
- pub fn print_tty(&self, force_colorize: bool) {
+ pub fn print_tty(&self, force_colorize: bool) -> usize {
let r = match (stdout(), atty::is(atty::Stream::Stdout) || force_colorize) {
(Some(mut o), true) => self.print_term(&mut *o),
_ => self.print(&mut io::stdout()),
};
- if let Err(e) = r {
- panic!("Cannot print table to standard output : {}", e);
+ match r {
+ Err(e) => panic!("Cannot print table to standard output : {}", e),
+ Ok(height) => height
}
}
@@ -194,10 +201,12 @@ impl<'a> TableSlice<'a> {
/// to another program, no color will be displayed.
/// To force colors rendering, use `print_tty()` method.
/// Calling `printstd()` is equivalent to calling `print_tty(false)`
+ /// # Returns
+ /// The number of lines printed
/// # Panic
/// Panic if writing to standard output fails
- pub fn printstd(&self) {
- self.print_tty(false);
+ pub fn printstd(&self) -> usize {
+ self.print_tty(false)
}
}
@@ -328,13 +337,15 @@ impl Table {
self.rows.iter_mut()
}
- /// Print the table to `out`
- pub fn print<T: Write + ?Sized>(&self, out: &mut T) -> Result<(), Error> {
+ /// Print the table to `out` and returns the number
+ /// of lines printed, or an error
+ pub fn print<T: Write + ?Sized>(&self, out: &mut T) -> Result<usize, Error> {
self.as_ref().print(out)
}
- /// Print the table to terminal `out`, applying styles when needed
- pub fn print_term<T: Terminal + ?Sized>(&self, out: &mut T) -> Result<(), Error> {
+ /// Print the table to terminal `out`, applying styles when needed and returns the number
+ /// of lines printed, or an error
+ pub fn print_term<T: Terminal + ?Sized>(&self, out: &mut T) -> Result<usize, Error> {
self.as_ref().print_term(out)
}
@@ -344,10 +355,12 @@ impl Table {
/// output is redirected to a file, or piped to another program, the output is considered
/// as not beeing tty, and ANSI escape characters won't be displayed unless `force colorize`
/// is set to `true`.
+ /// # Returns
+ /// The number of lines printed
/// # Panic
/// Panic if writing to standard output fails
- pub fn print_tty(&self, force_colorize: bool) {
- self.as_ref().print_tty(force_colorize);
+ pub fn print_tty(&self, force_colorize: bool) -> usize {
+ self.as_ref().print_tty(force_colorize)
}
/// Print the table to standard output. Colors won't be displayed unless
@@ -355,10 +368,12 @@ impl Table {
/// to another program, no color will be displayed.
/// To force colors rendering, use `print_tty()` method.
/// Calling `printstd()` is equivalent to calling `print_tty(false)`
+ /// # Returns
+ /// The number of lines printed
/// # Panic
/// Panic if writing to standard output fails
- pub fn printstd(&self) {
- self.as_ref().printstd();
+ pub fn printstd(&self) -> usize {
+ self.as_ref().printstd()
}
}
@@ -579,6 +594,7 @@ mod tests {
use Cell;
use format;
use format::consts::{FORMAT_DEFAULT, FORMAT_NO_LINESEP, FORMAT_NO_COLSEP, FORMAT_CLEAN, FORMAT_BOX_CHARS};
+ use utils::StringWriter;
#[test]
fn table() {
@@ -596,6 +612,7 @@ mod tests {
+-----+----+-----+
";
assert_eq!(table.to_string().replace("\r\n", "\n"), out);
+ assert_eq!(7, table.print(&mut StringWriter::new()).unwrap());
table.unset_titles();
let out = "\
+-----+----+-----+
@@ -605,6 +622,7 @@ mod tests {
+-----+----+-----+
";
assert_eq!(table.to_string().replace("\r\n", "\n"), out);
+ assert_eq!(5, table.print(&mut StringWriter::new()).unwrap());
}
#[test]
@@ -628,6 +646,7 @@ mod tests {
+-----+--------+-----+
";
assert_eq!(table.to_string().replace("\r\n", "\n"), out);
+ assert_eq!(7, table.print(&mut StringWriter::new()).unwrap());
}
#[test]
@@ -732,6 +751,7 @@ mod tests {
+-----+--------+-----+
";
assert_eq!(table.to_string().replace("\r\n", "\n"), out);
+ assert_eq!(5, table.print(&mut StringWriter::new()).unwrap());
}
#[test]
@@ -759,6 +779,7 @@ mod tests {
println!("____");
println!("{}", table.to_string().replace("\r\n", "\n"));
assert_eq!(table.to_string().replace("\r\n", "\n"), out);
+ assert_eq!(7, table.print(&mut StringWriter::new()).unwrap());
}
#[test]
@@ -782,6 +803,7 @@ mod tests {
println!("____");
println!("{}", table.to_string().replace("\r\n", "\n"));
assert_eq!(out, table.to_string().replace("\r\n", "\n"));
+ assert_eq!(3, table.print(&mut StringWriter::new()).unwrap());
}
#[test]
@@ -811,6 +833,7 @@ mod tests {
println!("____");
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]
@@ -829,6 +852,7 @@ mod tests {
+-----+----+-----+
";
assert_eq!(table.to_string().replace("\r\n", "\n"), out);
+ assert_eq!(7, table.print(&mut StringWriter::new()).unwrap());
}
#[test]
@@ -856,7 +880,9 @@ mod tests {
let slice = slice.slice(1..);
let slice = slice.slice(..3);
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());
}
#[test]
@@ -879,6 +905,7 @@ mod tests {
println!("____");
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]
@@ -913,6 +940,7 @@ mod tests {
println!("____");
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());
}
#[test]
@@ -936,6 +964,7 @@ mod tests {
println!("____");
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());
}
#[test]
@@ -957,5 +986,6 @@ mod tests {
println!("____");
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());
}
}
diff --git a/src/main.rs b/src/main.rs
index af9b745..3cf20c5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -47,6 +47,7 @@ fn main() {
table.set_titles(row!["Title 1", "Title 2"]);
table.set_format(*consts::FORMAT_DEFAULT);
table.get_format().indent(8);
- table.printstd();
+ let size = table.printstd();
+ println!("Table height = {}", size);
// println!("{:#?}", table);
}
diff --git a/src/row.rs b/src/row.rs
index 775a3d8..181793d 100644
--- a/src/row.rs
+++ b/src/row.rs
@@ -147,10 +147,11 @@ impl Row {
format: &TableFormat,
col_width: &[usize],
f: F)
- -> Result<(), Error>
+ -> Result<usize, Error>
where F: Fn(&Cell, &mut T, usize, usize, bool) -> Result<(), Error>
{
- for i in 0..self.get_height() {
+ let height = self.get_height();
+ for i in 0..height {
//TODO: Wrap this into dedicated function one day
out.write_all(&vec![b' '; format.get_indent()])?;
format.print_column_separator(out, ColumnPosition::Left)?;
@@ -184,28 +185,28 @@ impl Row {
format.print_column_separator(out, ColumnPosition::Right)?;
out.write_all(NEWLINE)?;
}
- Ok(())
+ Ok(height)
}
/// Print the row to `out`, with `separator` as column separator, and `col_width`
- /// specifying the width of each columns
+ /// 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 fn print<T: Write + ?Sized>(&self,
out: &mut T,
format: &TableFormat,
col_width: &[usize])
- -> Result<(), Error> {
+ -> Result<usize, Error> {
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
+ /// 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 fn print_term<T: Terminal + ?Sized>(&self,
out: &mut T,
format: &TableFormat,
col_width: &[usize])
- -> Result<(), Error> {
+ -> Result<usize, Error> {
self.__print(out, format, col_width, Cell::print_term)
}
}