From f3d4999dee75529211bf80e50648cedf89c357ae Mon Sep 17 00:00:00 2001 From: Arthur Skobara Date: Thu, 9 Jul 2015 23:28:15 +0600 Subject: add unicode support into Cell --- Cargo.toml | 3 +++ src/cell.rs | 39 ++++++++++++++++++++++++++++++++++----- src/lib.rs | 4 +++- 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e112a35..8fe27f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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.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(), " привет "); + } +} + diff --git a/src/lib.rs b/src/lib.rs index 4fd2655..a255405 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 +} -- cgit v1.2.3