diff options
author | Arthur Skobara <skobara.arthur@gmail.com> | 2015-07-09 23:28:15 +0600 |
---|---|---|
committer | Arthur Skobara <skobara.arthur@gmail.com> | 2015-07-09 23:28:15 +0600 |
commit | f3d4999dee75529211bf80e50648cedf89c357ae (patch) | |
tree | 312083b6824fb3a271f0795ad89e260af88b31d9 | |
parent | 1f6716412b0d6543db98c68fc5280d019f8a2fdb (diff) |
add unicode support into Cell
-rw-r--r-- | Cargo.toml | 3 | ||||
-rw-r--r-- | src/cell.rs | 39 | ||||
-rw-r--r-- | src/lib.rs | 4 |
3 files changed, 40 insertions, 6 deletions
@@ -16,3 +16,6 @@ name = "main" [lib]
name = "prettytable"
+
+[dependencies]
+unicode-width = "*"
diff --git a/src/cell.rs b/src/cell.rs index 203886d..5001538 100644 --- a/src/cell.rs +++ b/src/cell.rs @@ -1,9 +1,11 @@ //! This module contains definition of table/row cells stuff
+
use std::io::{Write, Error};
use std::string::ToString;
+use unicode_width::UnicodeWidthStr;
/// Represent a table cell containing a string.
-///
+///
/// Once created, a cell's content cannot be modified.
/// The cell would have to be replaced by another one
#[derive(Clone, Debug)]
@@ -18,7 +20,7 @@ impl Cell { let content: Vec<String> = string.lines_any().map(|ref x| x.to_string()).collect();
let mut width = 0;
for cont in &content {
- let l = cont.len();
+ let l = UnicodeWidthStr::width(&cont[..]);
if l > width {
width = l;
}
@@ -53,11 +55,11 @@ impl Cell { let mut len = 0;
if let Some(content) = self.content.get(idx) {
try!(out.write_all(content.as_bytes()));
- len = content.len();
+ len = UnicodeWidthStr::width(&content[..]);
}
try!(out.write_all(&vec![' ' as u8; col_width - len + 1]));
return Ok(());
- }
+ }
}
impl <'a, T: ToString> From<&'a T> for Cell {
@@ -80,4 +82,31 @@ impl Default for Cell { width: 0
};
}
-}
\ No newline at end of file +}
+
+#[cfg(test)]
+mod tests {
+ use cell::Cell;
+ use utils::StringWriter;
+
+ #[test]
+ fn ascii() {
+ let ascii_cell = Cell::new(&String::from("hello"));
+ assert_eq!(ascii_cell.get_width(), 5);
+
+ let mut out = StringWriter::new();
+ let _ = ascii_cell.print(&mut out, 0, 10);
+ assert_eq!(out.as_string(), " hello ");
+ }
+
+ #[test]
+ fn unicode() {
+ let unicode_cell = Cell::new(&String::from("привет"));
+ assert_eq!(unicode_cell.get_width(), 6);
+
+ let mut out = StringWriter::new();
+ let _ = unicode_cell.print(&mut out, 0, 10);
+ assert_eq!(out.as_string(), " привет ");
+ }
+}
+
@@ -1,4 +1,6 @@ //! A formatted and aligned table printer written in rust
+extern crate unicode_width;
+
use std::io::{stdout, Write, Error};
use std::fmt;
use std::iter::{FromIterator, IntoIterator};
@@ -228,4 +230,4 @@ macro_rules! ptable { tab
}
)
-}
\ No newline at end of file +}
|