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
use super::*;
pub struct Indented<'a, T> {
initial: &'a str,
hanging: &'a str,
value: T,
}
pub struct IndentedFormatter<'a, F> {
f: F,
initial: &'a str,
hanging: &'a str,
line: usize,
start_of_line: bool,
}
pub fn indent<'a, T>(initial: &'a str, hanging: &'a str, value: T) -> Indented<'a, T> {
Indented { initial, hanging, value }
}
impl<'a, F: Write + 'a> IndentedFormatter<'a, F> {
pub fn new(f: F, initial: &'a str, hanging: &'a str) -> Self {
Self { f, initial, hanging, line: 1, start_of_line: true }
}
}
impl<'a, T: Debug> Debug for Indented<'a, T> {
fn fmt(&self, f: &mut Formatter) -> Result {
let alt = f.alternate();
let mut f = IndentedFormatter::new(f, self.initial, self.hanging);
if alt {
write!(f, "{:#?}", self.value)
} else {
write!(f, "{:?}", self.value)
}
}
}
impl<'a, T: Display> Display for Indented<'a, T> {
fn fmt(&self, f: &mut Formatter) -> Result {
let alt = f.alternate();
let mut f = IndentedFormatter::new(f, self.initial, self.hanging);
if alt {
write!(f, "{:#}", self.value)
} else {
write!(f, "{}", self.value)
}
}
}
impl<'a, F: 'a + Write> Write for IndentedFormatter<'a, F> {
fn write_str(&mut self, s: &str) -> Result {
for c in s.chars() {
if c == '\n' {
self.f.write_char(c)?;
self.start_of_line = true;
self.line += 1;
continue;
}
if self.start_of_line {
if self.line == 1 {
self.f.write_str(self.initial)?;
} else {
self.f.write_str(self.hanging)?;
}
self.start_of_line = false;
}
self.f.write_char(c)?;
}
Ok(())
}
}