summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorpierresy <pierre-henri.symoneaux@alcatel-lucent.com>2015-05-30 16:28:50 +0200
committerpierresy <pierre-henri.symoneaux@alcatel-lucent.com>2015-05-31 01:23:10 +0200
commitfe226b041fb669722a81557b1e80da5904fc95c0 (patch)
tree0f0a493ae73370a8265eaf5f632ac5b8156ca583 /src
parentde0d5ca6fe6827ea077f4dce79f94c3c4cdc118a (diff)
Implemented Display (and implicitly ToString) trait for Table
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs47
1 files changed, 46 insertions, 1 deletions
diff --git a/src/lib.rs b/src/lib.rs
index a70a10c..6c318ca 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,5 +1,8 @@
//! A formatted and aligned table printer written in rust
-use std::io::{stdout, Write, Error};
+use std::io::{stdout, Write, Error, ErrorKind};
+use std::fmt;
+use std::str;
+use std::string::ToString;
/// A Struct representing a printable table
#[derive(Clone, Debug)]
@@ -159,6 +162,48 @@ impl Table {
}
}
+impl fmt::Display for Table {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+ let mut writer = StringWriter::new();
+ if let Err(_) = self.print(&mut writer) {
+ return Err(fmt::Error)
+ }
+ return write!(fmt, "{}", writer.as_string());
+ }
+}
+
+/// Internal utility for writing data into a string
+struct StringWriter {
+ string: String
+}
+
+impl StringWriter {
+ /// Create a new `StringWriter`
+ fn new() -> StringWriter {
+ return StringWriter{string: String::new()};
+ }
+
+ /// Return a reference to the internal written `String`
+ fn as_string(&self) -> &String {
+ return &self.string;
+ }
+}
+
+impl Write for StringWriter {
+ fn write(&mut self, data: &[u8]) -> Result<usize, Error> {
+ let string = match str::from_utf8(data) {
+ Ok(s) => s,
+ Err(e) => return Err(Error::new(ErrorKind::Other, format!("Cannot decode utf8 string : {}", e)))
+ };
+ self.string.push_str(string);
+ return Ok(data.len());
+ }
+
+ fn flush(&mut self) -> Result<(), Error> {
+ return Ok(());
+ }
+}
+
/// Create a table with column's titles from arguments.
///
/// The table can also be initialized with some values.