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

Remove panic in print_tty and return a Result #114

Merged
merged 2 commits into from Aug 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/tictactoe.rs
Expand Up @@ -14,7 +14,7 @@ fn main() {
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]
];
let mut height = table.printstd();
let mut height = table.print_tty(false).unwrap();
let stdin = io::stdin();
let mut stdout = io::stdout();
let mut current = CROSS;
Expand Down Expand Up @@ -53,7 +53,7 @@ fn main() {
terminal.cursor_up().unwrap();
terminal.delete_line().unwrap();
}
height = table.printstd();
height = table.print_tty(false).unwrap();
if check(&table) {
return;
}
Expand Down
3 changes: 1 addition & 2 deletions src/cell.rs
Expand Up @@ -231,8 +231,7 @@ impl Cell {
for a in &self.style {
match out.attr(*a) {
Ok(..) | Err(::term::Error::NotSupported) | Err(::term::Error::ColorOutOfRange) => {
()
} // Ignore unsupported atrributes
} // Ignore unsupported attributes
Err(e) => return Err(term_error_to_io_error(e)),
};
}
Expand Down
6 changes: 3 additions & 3 deletions src/csv.rs
Expand Up @@ -83,9 +83,9 @@ impl super::Table {
mod tests {
use crate::{Table, Row, Cell};

static CSV_S: &'static str = "ABC,DEFG,HIJKLMN\n\
foobar,bar,foo\n\
foobar2,bar2,foo2\n";
static CSV_S: &str = "ABC,DEFG,HIJKLMN\n\
foobar,bar,foo\n\
foobar2,bar2,foo2\n";

fn test_table() -> Table {
let mut table = Table::new();
Expand Down
10 changes: 5 additions & 5 deletions src/format.rs
Expand Up @@ -60,10 +60,10 @@ impl LineSeparator {
/// and `junc` is the one used for junctions between columns and lines
pub fn new(line: char, junc: char, ljunc: char, rjunc: char) -> LineSeparator {
LineSeparator {
line: line,
junc: junc,
ljunc: ljunc,
rjunc: rjunc,
line,
junc,
ljunc,
rjunc,
}
}

Expand All @@ -80,7 +80,7 @@ impl LineSeparator {
if lborder {
out.write_all(Utf8Char::from(self.ljunc).as_bytes())?;
}
let mut iter = col_width.into_iter().peekable();
let mut iter = col_width.iter().peekable();
while let Some(width) = iter.next() {
for _ in 0..width + padding.0 + padding.1 {
out.write_all(Utf8Char::from(self.line).as_bytes())?;
Expand Down
44 changes: 15 additions & 29 deletions src/lib.rs
Expand Up @@ -3,7 +3,7 @@
unused_import_braces,
unused_qualifications)]
//! A formatted and aligned table printer written in rust
//!

#[macro_use]
extern crate lazy_static;

Expand Down Expand Up @@ -145,7 +145,7 @@ impl<'a> TableSlice<'a> {
.print_line_separator(out, &col_width, LinePosition::Title)?;
}
// Print rows
let mut iter = self.rows.into_iter().peekable();
let mut iter = self.rows.iter().peekable();
while let Some(r) = iter.next() {
height += f(r, out, self.format, &col_width)?;
if iter.peek().is_some() {
Expand Down Expand Up @@ -178,31 +178,22 @@ impl<'a> TableSlice<'a> {
/// 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) -> usize {
let r = match (stdout(), atty::is(atty::Stream::Stdout) || force_colorize) {
/// A `Result` holding the number of lines printed, or an `io::Error` if any failure happens
pub fn print_tty(&self, force_colorize: bool) -> Result<usize, Error> {
match (stdout(), atty::is(atty::Stream::Stdout) || force_colorize) {
(Some(mut o), true) => self.print_term(&mut *o),
_ => self.print(&mut io::stdout()),
};
match r {
Err(e) => panic!("Cannot print table to standard output : {}", e),
Ok(height) => height
}
}

/// Print the table to standard output. Colors won't be displayed unless
/// stdout is a tty terminal. This means that if stdout is redirected to a file, or piped
/// 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) -> usize {
self.print_tty(false)
/// Any failure to print is ignored. For better control, use `print_tty()`.
/// Calling `printstd()` is equivalent to calling `print_tty(false)` and ignoring the result.
pub fn printstd(&self) {
let _ = self.print_tty(false); // Ignore result
}
}

Expand All @@ -223,7 +214,7 @@ impl Table {
/// Create a table initialized with `rows`
pub fn init(rows: Vec<Row>) -> Table {
Table {
rows: rows,
rows,
titles: Box::new(None),
format: Box::new(*consts::FORMAT_DEFAULT),
}
Expand Down Expand Up @@ -352,23 +343,18 @@ impl Table {
/// 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) -> usize {
/// A `Result` holding the number of lines printed, or an `io::Error` if any failure happens
pub fn print_tty(&self, force_colorize: bool) -> Result<usize, Error> {
self.as_ref().print_tty(force_colorize)
}

/// Print the table to standard output. Colors won't be displayed unless
/// stdout is a tty terminal. This means that if stdout is redirected to a file, or piped
/// 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) -> usize {
/// Any failure to print is ignored. For better control, use `print_tty()`.
/// Calling `printstd()` is equivalent to calling `print_tty(false)` and ignoring the result.
pub fn printstd(&self) {
self.as_ref().printstd()
}

Expand Down
3 changes: 1 addition & 2 deletions src/main.rs
Expand Up @@ -45,7 +45,6 @@ fn main() {
table.set_titles(row!["Title 1", "Title 2"]);
table.set_format(*consts::FORMAT_DEFAULT);
table.get_format().indent(8);
let size = table.printstd();
println!("Table height = {}", size);
table.printstd();
// println!("{:#?}", table);
}
2 changes: 1 addition & 1 deletion src/row.rs
Expand Up @@ -20,7 +20,7 @@ pub struct Row {
impl Row {
/// Create a new `Row` backed with `cells` vector
pub fn new(cells: Vec<Cell>) -> Row {
Row { cells: cells }
Row { cells }
}

/// Create an row of length `size`, with empty strings stored
Expand Down
14 changes: 7 additions & 7 deletions src/utils.rs
Expand Up @@ -7,9 +7,9 @@ use unicode_width::UnicodeWidthStr;
use super::format::Alignment;

#[cfg(any(not(windows), not(feature="win_crlf")))]
pub static NEWLINE: &'static [u8] = b"\n";
pub static NEWLINE: &[u8] = b"\n";
#[cfg(all(windows, feature="win_crlf"))]
pub static NEWLINE: &'static [u8] = b"\r\n";
pub static NEWLINE: &[u8] = b"\r\n";

/// Internal utility for writing data into a string
pub struct StringWriter {
Expand Down Expand Up @@ -114,10 +114,10 @@ mod tests {
#[test]
fn string_writer() {
let mut out = StringWriter::new();
out.write("foo".as_bytes()).unwrap();
out.write(" ".as_bytes()).unwrap();
out.write("".as_bytes()).unwrap();
out.write("bar".as_bytes()).unwrap();
out.write_all(b"foo").unwrap();
out.write_all(b" ").unwrap();
out.write_all(b"").unwrap();
out.write_all(b"bar").unwrap();
assert_eq!(out.as_string(), "foo bar");
}

Expand Down Expand Up @@ -162,7 +162,7 @@ mod tests {
#[test]
fn utf8_error() {
let mut out = StringWriter::new();
let res = out.write_all(&vec![0, 255]);
let res = out.write_all(&[0, 255]);
assert!(res.is_err());
}
}