summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorpierresy <pierre-henri.symoneaux@alcatel-lucent.com>2016-01-17 19:42:56 +0100
committerpierresy <pierre-henri.symoneaux@alcatel-lucent.com>2016-01-17 19:55:52 +0100
commitcad4b3cb9361ef3d999d06a9de03ab9d1ff1cb0e (patch)
tree4bb063466b743c4b84df6eec535d465dfaa86df3
parent45d77e82ab32622a2b06264ae660bd73edc6731d (diff)
Started format API refactoring
* Renamed Align enum to Alignment * Added left and right junction character customization * Added top and bottom lines customization * Added left and right borders customization
-rw-r--r--src/cell.rs34
-rw-r--r--src/format.rs150
-rw-r--r--src/lib.rs14
-rw-r--r--src/main.rs4
-rw-r--r--src/row.rs43
-rw-r--r--src/utils.rs20
6 files changed, 163 insertions, 102 deletions
diff --git a/src/cell.rs b/src/cell.rs
index 40bddd5..7487234 100644
--- a/src/cell.rs
+++ b/src/cell.rs
@@ -4,7 +4,7 @@ use std::io::{Write, Error};
use std::string::ToString;
use unicode_width::UnicodeWidthStr;
use term::{Attr, Terminal, color};
-use super::format::Align;
+use super::format::Alignment;
use super::utils::print_align;
/// Represent a table cell containing a string.
@@ -15,14 +15,14 @@ use super::utils::print_align;
pub struct Cell {
content: Vec<String>,
width: usize,
- align: Align,
+ align: Alignment,
style: Vec<Attr>
}
impl Cell {
/// Create a new `Cell` initialized with content from `string`.
/// Text alignment in cell is configurable with the `align` argument
- pub fn new_align(string: &str, align: Align) -> Cell {
+ pub fn new_align(string: &str, align: Alignment) -> Cell {
let content: Vec<String> = string.lines().map(|ref x| x.to_string()).collect();
let mut width = 0;
for cont in &content {
@@ -42,11 +42,11 @@ impl Cell {
/// Create a new `Cell` initialized with content from `string`.
/// By default, content is align to `LEFT`
pub fn new(string: &str) -> Cell {
- return Cell::new_align(string, Align::LEFT);
+ return Cell::new_align(string, Alignment::LEFT);
}
/// Set text alignment in the cell
- pub fn align(&mut self, align: Align) {
+ pub fn align(&mut self, align: Alignment) {
self.align = align;
}
@@ -64,7 +64,7 @@ impl Cell {
/// Remove all style attributes and reset alignment to default (LEFT)
pub fn reset_style(&mut self) {
self.style.clear();
- self.align(Align::LEFT);
+ self.align(Alignment::LEFT);
}
/// Set the cell's style by applying the given specifier string
@@ -144,9 +144,9 @@ impl Cell {
'b' => self.style(Attr::Bold),
'i' => self.style(Attr::Italic(true)),
'u' => self.style(Attr::Underline(true)),
- 'c' => self.align(Align::CENTER),
- 'l' => self.align(Align::LEFT),
- 'r' => self.align(Align::RIGHT),
+ 'c' => self.align(Alignment::CENTER),
+ 'l' => self.align(Alignment::LEFT),
+ 'r' => self.align(Alignment::RIGHT),
'd' => {/* Default : do nothing */}
_ => {/* Silently ignore unknown tags */}
}
@@ -224,7 +224,7 @@ impl Default for Cell {
return Cell {
content: vec!["".to_string(); 1],
width: 0,
- align: Align::LEFT,
+ align: Alignment::LEFT,
style: Vec::new()
};
}
@@ -268,7 +268,7 @@ macro_rules! cell {
mod tests {
use cell::Cell;
use utils::StringWriter;
- use format::Align;
+ use format::Alignment;
use term::{Attr, color};
#[test]
@@ -308,7 +308,7 @@ mod tests {
#[test]
fn align_left() {
- let cell = Cell::new_align("test", Align::LEFT);
+ let cell = Cell::new_align("test", Alignment::LEFT);
let mut out = StringWriter::new();
let _ = cell.print(&mut out, 0, 10);
assert_eq!(out.as_string(), " test ");
@@ -316,7 +316,7 @@ mod tests {
#[test]
fn align_center() {
- let cell = Cell::new_align("test", Align::CENTER);
+ let cell = Cell::new_align("test", Alignment::CENTER);
let mut out = StringWriter::new();
let _ = cell.print(&mut out, 0, 10);
assert_eq!(out.as_string(), " test ");
@@ -324,7 +324,7 @@ mod tests {
#[test]
fn align_right() {
- let cell = Cell::new_align("test", Align::RIGHT);
+ let cell = Cell::new_align("test", Alignment::RIGHT);
let mut out = StringWriter::new();
let _ = cell.print(&mut out, 0, 10);
assert_eq!(out.as_string(), " test ");
@@ -339,13 +339,13 @@ mod tests {
assert!(cell.style.contains(&Attr::Bold));
assert!(cell.style.contains(&Attr::ForegroundColor(color::RED)));
assert!(cell.style.contains(&Attr::BackgroundColor(color::BRIGHT_BLUE)));
- assert_eq!(cell.align, Align::CENTER);
+ assert_eq!(cell.align, Alignment::CENTER);
cell = cell.style_spec("FDBwr");
assert_eq!(cell.style.len(), 2);
assert!(cell.style.contains(&Attr::ForegroundColor(color::BRIGHT_BLACK)));
assert!(cell.style.contains(&Attr::BackgroundColor(color::WHITE)));
- assert_eq!(cell.align, Align::RIGHT)
+ assert_eq!(cell.align, Alignment::RIGHT)
}
#[test]
@@ -354,6 +354,6 @@ mod tests {
assert_eq!(cell.style.len(), 2);
cell.reset_style();
assert_eq!(cell.style.len(), 0);
- assert_eq!(cell.align, Align::LEFT);
+ assert_eq!(cell.align, Alignment::LEFT);
}
}
diff --git a/src/format.rs b/src/format.rs
index 91d167f..acffad6 100644
--- a/src/format.rs
+++ b/src/format.rs
@@ -6,38 +6,65 @@ use super::utils::NEWLINE;
/// Alignment for cell's content
#[derive(Clone, Debug, PartialEq, Copy)]
-pub enum Align {
+pub enum Alignment {
LEFT,
CENTER,
RIGHT
}
+/// Position of a line separator in a table
+#[derive(Clone, Debug, PartialEq, Copy)]
+pub enum LinePosition {
+ Top,
+ Title,
+ Intern,
+ Bottom
+}
+
+/// Position of a column separator in a row
+#[derive(Clone, Debug, PartialEq, Copy)]
+pub enum ColumnPosition {
+ Left,
+ Intern,
+ Right
+}
+
/// Contains the character used for printing a line separator
#[derive(Clone, Debug)]
pub struct LineSeparator {
- line: [u8; 1],
- cross: [u8; 1],
+ /// Line separator
+ line: char,
+ /// Internal junction separator
+ junc: char,
+ /// Left junction separator
+ ljunc: char,
+ /// Right junction separator
+ rjunc: char
}
impl LineSeparator {
/// Create a new line separator instance where `line` is the character used to separate 2 lines
- /// and `cross` is the one used when column separaors and line separators cross
- pub fn new(line: char, cross: char) -> LineSeparator {
- return LineSeparator{line: [line as u8], cross: [cross as u8]};
+ /// and `junc` is the one used for junctions between columns and lines
+ pub fn new(line: char, junc: char, ljunc: char, rjunc: char) -> LineSeparator {
+ return LineSeparator{line: line, junc: junc, ljunc: ljunc, rjunc: rjunc};
}
/// Print a full line separator to `out`. `col_width` is a slice containing the width of each column
- pub fn print<T: Write+?Sized>(&self, out: &mut T, col_width: &[usize], with_colsep: bool) -> Result<(), Error> {
- if with_colsep {
- try!(out.write_all(&self.cross));
+ pub fn print<T: Write+?Sized>(&self, out: &mut T, col_width: &[usize], colsep: bool, lborder: bool, rborder: bool) -> Result<(), Error> {
+ if lborder {
+ try!(out.write_all(&[self.ljunc as u8]));
}
- for width in col_width {
- try!(out.write_all(&vec![self.line[0]; width+2]));
- if with_colsep {
- try!(out.write_all(&self.cross));
+ let mut iter = col_width.into_iter().peekable();
+ while let Some(width) = iter.next() {
+ try!(out.write_all(&vec![self.line as u8; width+2]));
+ if colsep && iter.peek().is_some() {
+ try!(out.write_all(&[self.junc as u8]));
}
}
+ if rborder {
+ try!(out.write_all(&[self.rjunc as u8]));
+ }
return out.write_all(NEWLINE);
}
}
@@ -45,56 +72,83 @@ impl LineSeparator {
/// Contains the table formatting rules
#[derive(Clone, Debug)]
pub struct TableFormat {
- col_sep: Option<[u8; 1]>,
- line_sep: Option<LineSeparator>,
- title_sep: Option<LineSeparator>
+ /// Optional column separator character
+ csep: Option<char>,
+ /// Optional left border character
+ lborder: Option<char>,
+ /// Optional right border character
+ rborder: Option<char>,
+ /// Optional internal line separator
+ lsep: Option<LineSeparator>,
+ /// Optional title line separator
+ tsep: Option<LineSeparator>,
+ /// Optional top line separator
+ top_sep: Option<LineSeparator>,
+ /// Optional bottom line separator
+ bottom_sep: Option<LineSeparator>
}
impl TableFormat {
/// Create a new TableFormat.
///
- /// `col_sep` is the character used for separating columns.
- /// `line_sep` is an optional `LineSeparator` defining how to separate lines.
- /// `title_sep` is an optional `LineSeparator` defining the format of the separator after the title line (if set).
- /// If `title_sep` is set to `None`, then `line_sep` will be used, f it's set.
- pub fn new(col_sep: Option<char>, line_sep: Option<LineSeparator>, title_sep: Option<LineSeparator>) -> TableFormat {
- let csep = match col_sep {
- Some(c) => Some([c as u8]),
- None => None
+ /// `csep` is the character used for separating columns.
+ /// `lsep` is an optional `LineSeparator` defining how to separate lines.
+ /// `tsep` is an optional `LineSeparator` defining the format of the separator after the title line (if set).
+ /// If `tsep` is set to `None`, then `lsep` will be used, f it's set.
+ pub fn new(csep: Option<char>, lsep: Option<LineSeparator>, tsep: Option<LineSeparator>) -> TableFormat {
+ return TableFormat{
+ csep: csep,
+ lborder: None,
+ rborder: None,
+ lsep: lsep,
+ tsep: tsep,
+ top_sep: None,
+ bottom_sep: None
};
- return TableFormat{col_sep: csep, line_sep: line_sep, title_sep: title_sep};
+ }
+
+ fn get_sep_for_line(&self, pos: LinePosition) -> &Option<LineSeparator> {
+ return match pos {
+ LinePosition::Intern => return &self.lsep,
+ LinePosition::Top => return &self.top_sep,
+ LinePosition::Bottom => return &self.bottom_sep,
+ LinePosition::Title => match &self.tsep {
+ s @ &Some(_) => s,
+ &None => &self.lsep
+ }
+ };
}
/// Print a full line separator to `out`. `col_width` is a slice containing the width of each column
- pub fn print_line_separator<T: Write+?Sized>(&self, out: &mut T, col_width: &[usize]) -> Result<(), Error> {
- if let Some(ref l) = self.line_sep {
- return l.print(out, col_width, self.col_sep.is_some());
- }
- return Ok(());
+ pub fn print_line_separator<T: Write+?Sized>(&self, out: &mut T, col_width: &[usize], pos: LinePosition) -> Result<(), Error> {
+ return match *self.get_sep_for_line(pos) {
+ Some(ref l) => l.print(out, col_width, self.csep.is_some(), self.lborder.is_some(), self.rborder.is_some()),
+ None => Ok(())
+ };
}
- /// Print a full title separator to `out`. `col_width` is a slice containing the width of each column
- pub fn print_title_separator<T: Write+?Sized>(&self, out: &mut T, col_width: &[usize]) -> Result<(), Error> {
- if let Some(ref l) = self.title_sep {
- return l.print(out, col_width, self.col_sep.is_some());
- }
- return self.print_line_separator(out, col_width);
+ /// Print a column separator
+ fn get_column_separator(&self, pos: ColumnPosition) -> Option<char> {
+ return match pos {
+ ColumnPosition::Left => self.lborder,
+ ColumnPosition::Intern => self.csep,
+ ColumnPosition::Right => self.rborder
+ };
}
- /// Print a column separator to `out`
- pub fn print_column_separator<T: Write+?Sized>(&self, out: &mut T) -> Result<(), Error> {
- return match self.col_sep {
- Some(ref s) => out.write_all(s),
+ pub fn print_column_separator<T: Write+?Sized>(&self, out: &mut T, pos: ColumnPosition) -> Result<(), Error> {
+ return match self.get_column_separator(pos) {
+ Some(s) => out.write_all(&[s as u8]),
None => Ok(())
};
}
}
/// A line separator mad of `-` and `+`
-pub const MINUS_PLUS_SEP: LineSeparator = LineSeparator{line: ['-' as u8], cross: ['+' as u8]};
+pub const MINUS_PLUS_SEP: LineSeparator = LineSeparator{line: '-', junc: '+', ljunc: '+', rjunc: '+'};
/// A line separator mad of `=` and `+`
-pub const EQU_PLUS_SEP: LineSeparator = LineSeparator{line: ['=' as u8], cross: ['+' as u8]};
+pub const EQU_PLUS_SEP: LineSeparator = LineSeparator{line: '=', junc: '+', ljunc: '+', rjunc: '+'};
/// Default table format, printing a table like this :
///
@@ -107,19 +161,19 @@ pub const EQU_PLUS_SEP: LineSeparator = LineSeparator{line: ['=' as u8], cross:
/// | | |
/// +----+----+
/// ```
-pub const FORMAT_DEFAULT: TableFormat = TableFormat{col_sep: Some(['|' as u8]), line_sep: Some(MINUS_PLUS_SEP), title_sep: Some(EQU_PLUS_SEP)};
+pub const FORMAT_DEFAULT: TableFormat = TableFormat{csep: Some('|'), lborder: Some('|'), rborder: Some('|'), lsep: Some(MINUS_PLUS_SEP), tsep: Some(EQU_PLUS_SEP), top_sep: Some(MINUS_PLUS_SEP), bottom_sep: Some(MINUS_PLUS_SEP)};
/// Similar to `FORMAT_DEFAULT` but without special separator after title line
-pub const FORMAT_NO_TITLE: TableFormat = TableFormat{col_sep: Some(['|' as u8]), line_sep: Some(MINUS_PLUS_SEP), title_sep: Some(MINUS_PLUS_SEP)};
+pub const FORMAT_NO_TITLE: TableFormat = TableFormat{csep: Some('|'), lborder: Some('|'), rborder: Some('|'), lsep: Some(MINUS_PLUS_SEP), tsep: Some(MINUS_PLUS_SEP), top_sep: Some(MINUS_PLUS_SEP), bottom_sep: Some(MINUS_PLUS_SEP)};
/// With no line separator, but with title separator
-pub const FORMAT_NO_LINESEP_WITH_TITLE: TableFormat = TableFormat{col_sep: Some(['|' as u8]), line_sep: None, title_sep: Some(MINUS_PLUS_SEP)};
+pub const FORMAT_NO_LINESEP_WITH_TITLE: TableFormat = TableFormat{csep: Some('|'), lborder: Some('|'), rborder: Some('|'), lsep: None, tsep: Some(MINUS_PLUS_SEP), top_sep: Some(MINUS_PLUS_SEP), bottom_sep: Some(MINUS_PLUS_SEP)};
/// With no line or title separator
-pub const FORMAT_NO_LINESEP: TableFormat = TableFormat{col_sep: Some(['|' as u8]), line_sep: None, title_sep: None};
+pub const FORMAT_NO_LINESEP: TableFormat = TableFormat{csep: Some('|'), lborder: Some('|'), rborder: Some('|'), lsep: None, tsep: None, top_sep: None, bottom_sep: None};
/// No column seprarator
-pub const FORMAT_NO_COLSEP: TableFormat = TableFormat{col_sep: None, line_sep: Some(MINUS_PLUS_SEP), title_sep: Some(EQU_PLUS_SEP)};
+pub const FORMAT_NO_COLSEP: TableFormat = TableFormat{csep: None, lborder: None, rborder: None, lsep: Some(MINUS_PLUS_SEP), tsep: Some(EQU_PLUS_SEP), top_sep: Some(MINUS_PLUS_SEP), bottom_sep: Some(MINUS_PLUS_SEP)};
/// Format for printing a table without any separators (only alignment)
-pub const FORMAT_NO_BORDER: TableFormat = TableFormat{col_sep: None, line_sep: None, title_sep: None};
+pub const FORMAT_NO_BORDER: TableFormat = TableFormat{csep: None, lborder: None, rborder: None, lsep: None, tsep: None, top_sep: None, bottom_sep: None};
diff --git a/src/lib.rs b/src/lib.rs
index 20b2389..304825c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -18,7 +18,7 @@ mod utils;
use row::Row;
use cell::Cell;
-use format::{TableFormat, FORMAT_DEFAULT};
+use format::{TableFormat, LinePosition, FORMAT_DEFAULT};
use utils::StringWriter;
/// An owned printable table
@@ -115,16 +115,20 @@ impl <'a> TableSlice<'a> {
where F: Fn(&Row, &mut T, &TableFormat, &[usize]) -> Result<(), Error> {
// Compute columns width
let col_width = self.get_all_column_width();
- try!(self.format.print_line_separator(out, &col_width));
+ try!(self.format.print_line_separator(out, &col_width, LinePosition::Top));
if let Some(ref t) = *self.titles {
try!(f(t, out, &self.format, &col_width));
- try!(self.format.print_title_separator(out, &col_width));
+ try!(self.format.print_line_separator(out, &col_width, LinePosition::Title));
}
// Print rows
- for r in self.rows {
+ let mut iter = self.rows.into_iter().peekable();
+ while let Some(r) = iter.next() {
try!(f(r, out, &self.format, &col_width));
- try!(self.format.print_line_separator(out, &col_width));
+ if iter.peek().is_some() {
+ try!(self.format.print_line_separator(out, &col_width, LinePosition::Intern));
+ }
}
+ try!(self.format.print_line_separator(out, &col_width, LinePosition::Bottom));
return out.flush();
}
diff --git a/src/main.rs b/src/main.rs
index 3344952..78eac2d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -27,10 +27,10 @@ fn main() {
Cell::new("foo2").style_spec("FrByb")])
);
for cell in table.column_iter_mut(2) {
- cell.align(Align::RIGHT);
+ cell.align(Alignment::RIGHT);
}
for cell in table.column_iter_mut(1) {
- cell.align(Align::CENTER);
+ cell.align(Alignment::CENTER);
}
table.printstd();
println!("Modified : ");
diff --git a/src/row.rs b/src/row.rs
index 0a4ca7c..1c39cc1 100644
--- a/src/row.rs
+++ b/src/row.rs
@@ -7,7 +7,7 @@ use term::Terminal;
use super::utils::NEWLINE;
use super::cell::Cell;
-use super::format::TableFormat;
+use super::format::{TableFormat, ColumnPosition};
/// Represent a table row made of cells
#[derive(Clone, Debug)]
@@ -22,17 +22,17 @@ impl Row {
cells: cells
};
}
-
+
/// Create an row of length `size`, with empty strings stored
pub fn empty() -> Row {
return Self::new(vec![Cell::default(); 0]);
}
-
+
/// Get the number of cells in this row
pub fn len(&self) -> usize {
return self.cells.len();
}
-
+
/// Get the height of this row
pub fn get_height(&self) -> usize {
let mut height = 1; // Minimum height must be 1 to print empty rows
@@ -44,7 +44,7 @@ impl Row {
}
return height;
}
-
+
/// Get the minimum width required by the cell in the column `column`.
/// Return 0 if the cell does not exist in this row
pub fn get_cell_width(&self, column: usize) -> usize {
@@ -53,17 +53,17 @@ impl Row {
None => 0
}
}
-
+
/// Get the cell at index `idx`
pub fn get_cell(&self, idx: usize) -> Option<&Cell> {
return self.cells.get(idx);
}
-
+
/// Get the mutable cell at index `idx`
pub fn get_mut_cell(&mut self, idx: usize) -> Option<&mut Cell> {
return self.cells.get_mut(idx);
}
-
+
/// Set the `cell` in the row at the given `column`
pub fn set_cell(&mut self, cell: Cell, column: usize) -> Result<(), &str> {
if column >= self.len() {
@@ -72,12 +72,12 @@ impl Row {
self.cells[column] = cell;
return Ok(());
}
-
+
/// Append a `cell` at the end of the row
pub fn add_cell(&mut self, cell: Cell) {
self.cells.push(cell);
}
-
+
/// Insert `cell` at position `index`. If `index` is higher than the row lenght,
/// the cell will be appended at the end
pub fn insert_cell(&mut self, index: usize, cell: Cell) {
@@ -87,38 +87,41 @@ impl Row {
self.add_cell(cell);
}
}
-
+
/// Remove the cell at position `index`. Silently skip if this cell does not exist
pub fn remove_cell(&mut self, index: usize) {
if index < self.cells.len() {
self.cells.remove(index);
}
}
-
+
/// Internal only
- fn __print<T:Write+?Sized, F>(&self, out: &mut T, format: &TableFormat, col_width: &[usize], f: F) -> Result<(), Error>
- where F: Fn(&Cell, &mut T, usize, usize) -> Result<(), Error>
+ fn __print<T:Write+?Sized, F>(&self, out: &mut T, format: &TableFormat, col_width: &[usize], f: F) -> Result<(), Error>
+ where F: Fn(&Cell, &mut T, usize, usize) -> Result<(), Error>
{
for i in 0..self.get_height() {
- try!(format.print_column_separator(out));
+ try!(format.print_column_separator(out, ColumnPosition::Left));
for j in 0..col_width.len() {
match self.get_cell(j) {
Some(ref c) => try!(f(c, out, i, col_width[j])),
None => try!(f(&Cell::default(), out, i, col_width[j]))
};
- try!(format.print_column_separator(out));
+ if j < col_width.len() - 1 {
+ try!(format.print_column_separator(out, ColumnPosition::Intern));
+ }
}
+ try!(format.print_column_separator(out, ColumnPosition::Right));
try!(out.write_all(NEWLINE));
}
return Ok(());
}
-
+
/// Print the row to `out`, with `separator` as column separator, and `col_width`
/// specifying the width of each columns
pub fn print<T: Write+?Sized>(&self, out: &mut T, format: &TableFormat, col_width: &[usize]) -> Result<(), Error> {
return 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
pub fn print_term<T: Terminal+?Sized>(&self, out: &mut T, format: &TableFormat, col_width: &[usize]) -> Result<(), Error> {
@@ -158,7 +161,7 @@ impl <T, A> From<T> for Row where A: ToString, T : IntoIterator<Item=A> {
}
/// This macro simplifies `Row` creation
-///
+///
/// The syntax support style spec
/// # Example
/// ```
@@ -185,7 +188,7 @@ macro_rules! row {
(($($out:tt)*); $value:expr, $($n:tt)*) => (row!(($($out)* cell!($value),); $($n)*));
(($($out:tt)*); $style:ident : $value:expr) => (vec![$($out)* cell!($style : $value)]);
(($($out:tt)*); $style:ident : $value:expr, $($n: tt)*) => (row!(($($out)* cell!($style : $value),); $($n)*));
-
+
($($content:expr), *) => ($crate::row::Row::new(vec![$(cell!($content)), *]));
($style:ident -> $($content:expr), *) => ($crate::row::Row::new(vec![$(cell!($style : $content)), *]));
($($content:tt)*) => ($crate::row::Row::new(row!((); $($content)*)));
diff --git a/src/utils.rs b/src/utils.rs
index dd0b0ee..669b926 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -4,7 +4,7 @@ use std::str;
use unicode_width::UnicodeWidthStr;
-use super::format::Align;
+use super::format::Alignment;
#[cfg(not(windows))]
pub static NEWLINE: &'static [u8] = b"\n";
@@ -45,13 +45,13 @@ impl Write for StringWriter {
}
/// Align/fill a string and print it to `out`
-pub fn print_align<T: Write+?Sized>(out: &mut T, align: Align, text: &str, fill: char, size: usize) -> Result<(), Error> {
+pub fn print_align<T: Write+?Sized>(out: &mut T, align: Alignment, text: &str, fill: char, size: usize) -> Result<(), Error> {
let text_len = UnicodeWidthStr::width(text);
let mut nfill = if text_len < size { size - text_len } else { 0 };
let n = match align {
- Align::LEFT => 0,
- Align:: RIGHT => nfill,
- Align:: CENTER => nfill/2
+ Alignment::LEFT => 0,
+ Alignment:: RIGHT => nfill,
+ Alignment:: CENTER => nfill/2
};
if n > 0 {
try!(out.write(&vec![fill as u8; n]));
@@ -67,7 +67,7 @@ pub fn print_align<T: Write+?Sized>(out: &mut T, align: Align, text: &str, fill:
#[cfg(test)]
mod tests {
use super::*;
- use format::Align;
+ use format::Alignment;
use std::io::Write;
#[test]
@@ -83,19 +83,19 @@ mod tests {
#[test]
fn fill_align() {
let mut out = StringWriter::new();
- print_align(&mut out, Align::RIGHT, "foo", '*', 10).unwrap();
+ print_align(&mut out, Alignment::RIGHT, "foo", '*', 10).unwrap();
assert_eq!(out.as_string(), "*******foo");
let mut out = StringWriter::new();
- print_align(&mut out, Align::LEFT, "foo", '*', 10).unwrap();
+ print_align(&mut out, Alignment::LEFT, "foo", '*', 10).unwrap();
assert_eq!(out.as_string(), "foo*******");
let mut out = StringWriter::new();
- print_align(&mut out, Align::CENTER, "foo", '*', 10).unwrap();
+ print_align(&mut out, Alignment::CENTER, "foo", '*', 10).unwrap();
assert_eq!(out.as_string(), "***foo****");
let mut out = StringWriter::new();
- print_align(&mut out, Align::CENTER, "foo", '*', 1).unwrap();
+ print_align(&mut out, Alignment::CENTER, "foo", '*', 1).unwrap();
assert_eq!(out.as_string(), "foo");
}
}