1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use core::fmt;
use core::marker::PhantomData;
#[derive(Debug)]
pub struct PrettyIndent {
prefix: &'static str,
level: usize
}
impl PrettyIndent {
pub fn new(prefix: &'static str) -> PrettyIndent {
PrettyIndent { prefix: prefix, level: 0 }
}
pub fn increase(&mut self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n")?;
self.level += 1;
Ok(())
}
}
impl fmt::Display for PrettyIndent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.level == 0 {
write!(f, "{}", self.prefix)
} else {
write!(f, "{0:1$}{0:2$}\\ ", "", self.prefix.len(), self.level - 1)
}
}
}
pub trait PrettyPrint {
fn pretty_print(buffer: &AsRef<[u8]>, fmt: &mut fmt::Formatter,
indent: &mut PrettyIndent) -> fmt::Result;
}
pub struct PrettyPrinter<'a, T: PrettyPrint> {
prefix: &'static str,
buffer: &'a AsRef<[u8]>,
phantom: PhantomData<T>
}
impl<'a, T: PrettyPrint> PrettyPrinter<'a, T> {
pub fn new(prefix: &'static str, buffer: &'a AsRef<[u8]>) -> PrettyPrinter<'a, T> {
PrettyPrinter {
prefix: prefix,
buffer: buffer,
phantom: PhantomData
}
}
}
impl<'a, T: PrettyPrint + AsRef<[u8]>> PrettyPrinter<'a, T> {
pub fn print(printable: &'a T) -> PrettyPrinter<'a, T> {
PrettyPrinter {
prefix: "",
buffer: printable,
phantom: PhantomData,
}
}
}
impl<'a, T: PrettyPrint> fmt::Display for PrettyPrinter<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
T::pretty_print(&self.buffer, f, &mut PrettyIndent::new(self.prefix))
}
}