123use super::{Changeset, Difference};
4use std::fmt;
56impl fmt::Display for Changeset {
7fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8for d in &self.diffs {
9match *d {
10 Difference::Same(ref x) => {
11try!(write!(f, "{}{}", x, self.split));
12 }
13 Difference::Add(ref x) => {
14try!(write!(f, "\x1b[92m{}\x1b[0m{}", x, self.split));
15 }
16 Difference::Rem(ref x) => {
17try!(write!(f, "\x1b[91m{}\x1b[0m{}", x, self.split));
18 }
19 }
20 }
21Ok(())
22 }
23}
2425#[cfg(test)]
26mod tests {
27use super::super::Changeset;
28use std::io::Write;
29use std::iter::FromIterator;
30use std::thread;
31use std::time;
3233/// convert slice to vector for assert_eq
34fn vb(b: &'static [u8]) -> Vec<u8> {
35 Vec::from_iter(b.iter().cloned())
36 }
3738/// if the format changes, you can use this to help create the test for color
39 /// just pass it in and copy-paste (validating that it looks right first of course...)
40#[allow(dead_code)]
41fn debug_bytes(result: &[u8], expected: &[u8]) {
42// sleep for a bit so stderr passes us
43thread::sleep(time::Duration::new(0, 2e8 as u32));
44println!("Debug Result:");
45for b in result {
46print!("{}", *b as char);
47 }
48println!("Repr Result:");
49 repr_bytes(result);
50println!("");
51println!("--Result Repr DONE");
5253println!("Debug Expected:");
54for b in expected {
55print!("{}", *b as char);
56 }
57println!("Repr Expected:");
58 repr_bytes(expected);
59println!("");
60println!("--Expected Repr DONE");
61 }
6263/// for helping debugging what the actual bytes are
64 /// for writing user tests
65fn repr_bytes(bytes: &[u8]) {
66for b in bytes {
67match *b {
68// 9 => print!("{}", *b as char), // TAB
69b'\n' => print!("\\n"),
70b'\r' => print!("\\r"),
7132...126 => print!("{}", *b as char), // visible ASCII
72_ => print!(r"\x{:0>2x}", b),
7374 }
75 }
76 }
7778#[test]
79fn test_display() {
80let text1 = "Roses are red, violets are blue,\n\
81 I wrote this library,\n\
82 just for you.\n\
83 (It's true).";
8485let text2 = "Roses are red, violets are blue,\n\
86 I wrote this documentation,\n\
87 just for you.\n\
88 (It's quite true).";
89let expected = b"Roses are red, violets are blue,\n\x1b[91mI wrote this library,\x1b\
90 [0m\n\x1b[92mI wrote this documentation,\x1b[0m\njust for you.\n\x1b\
91 [91m(It's true).\x1b[0m\n\x1b[92m(It's quite true).\x1b[0m\n";
9293let ch = Changeset::new(text1, text2, "\n");
94let mut result: Vec<u8> = Vec::new();
95write!(result, "{}", ch).unwrap();
96 debug_bytes(&result, expected);
97assert_eq!(result, vb(expected));
9899 }
100}