summaryrefslogtreecommitdiffstats
path: root/src/utils.rs
diff options
context:
space:
mode:
authorpierresy <phsym@msn.com>2016-01-03 14:14:27 +0100
committerpierresy <phsym@msn.com>2016-01-03 14:14:27 +0100
commit93495d81195cd464016612fdd2bed284ddb6a1f0 (patch)
treed65d4ce48389eb69931207252019d24978e49173 /src/utils.rs
parentaac360ceac297ed09e1f036381a9ebe9e4ab709d (diff)
Implemented print_align function for #12
Implemented print_align function to replace rust's std fill/align capability.
Diffstat (limited to 'src/utils.rs')
-rw-r--r--src/utils.rs60
1 files changed, 57 insertions, 3 deletions
diff --git a/src/utils.rs b/src/utils.rs
index cfb5619..744bf0d 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -2,6 +2,10 @@
use std::io::{Error, ErrorKind, Write};
use std::str;
+use unicode_width::UnicodeWidthStr;
+
+use super::format::Align;
+
#[cfg(not(windows))]
pub static NEWLINE: &'static [u8] = b"\n";
#[cfg(windows)]
@@ -17,7 +21,7 @@ impl StringWriter {
pub fn new() -> StringWriter {
return StringWriter{string: String::new()};
}
-
+
/// Return a reference to the internally written `String`
pub fn as_string(&self) -> &str {
return &self.string;
@@ -33,9 +37,59 @@ impl Write for StringWriter {
self.string.push_str(string);
return Ok(data.len());
}
-
+
fn flush(&mut self) -> Result<(), Error> {
// Nothing to do here
return Ok(());
}
-} \ No newline at end of file
+}
+
+/// 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> {
+ let text_len = UnicodeWidthStr::width(text);
+ let mut nfill = if text_len < size { size - text_len } else { 0 };
+ match align {
+ Align::LEFT => {},
+ Align:: RIGHT => {try!(out.write(&vec![fill as u8; nfill])); nfill = 0;},
+ Align:: CENTER => {try!(out.write(&vec![fill as u8; nfill/2])); nfill -= nfill/2;}
+ }
+ try!(out.write(text.as_bytes()));
+ try!(out.write(&vec![fill as u8; nfill]));
+ return Ok(());
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use format::Align;
+ use std::io::Write;
+
+ #[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();
+ assert_eq!(out.as_string(), "foo bar");
+ }
+
+ #[test]
+ fn fill_align() {
+ let mut out = StringWriter::new();
+ print_align(&mut out, Align::RIGHT, "foo", '*', 10).unwrap();
+ assert_eq!(out.as_string(), "*******foo");
+
+ let mut out = StringWriter::new();
+ print_align(&mut out, Align::LEFT, "foo", '*', 10).unwrap();
+ assert_eq!(out.as_string(), "foo*******");
+
+ let mut out = StringWriter::new();
+ print_align(&mut out, Align::CENTER, "foo", '*', 10).unwrap();
+ assert_eq!(out.as_string(), "***foo****");
+
+ let mut out = StringWriter::new();
+ print_align(&mut out, Align::CENTER, "foo", '*', 1).unwrap();
+ assert_eq!(out.as_string(), "foo");
+ }
+}