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
112
113
114
115
use std::fmt;
use std::io;
use std::iter;
pub struct IoFmt<'write, W: 'write>(pub &'write mut W);
impl<'write, W> fmt::Write for IoFmt<'write, W>
where
W: io::Write,
{
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.write_all(s.as_bytes()).map_err(|_| fmt::Error)
}
}
pub struct Formatter<'write> {
write: &'write mut dyn fmt::Write,
current_line_empty: bool,
indent: usize,
pub(crate) indentation: usize,
buffer: String,
}
impl<'write> Formatter<'write> {
pub fn new(write: &mut dyn fmt::Write) -> Formatter {
Formatter {
write: write,
current_line_empty: true,
indent: 0usize,
indentation: 2usize,
buffer: String::from(" "),
}
}
pub fn with_indentation(self, indentation: usize) -> Self {
Self {
indentation,
..self
}
}
fn check_indent(&mut self) -> fmt::Result {
if self.current_line_empty && self.indent > 0 {
self.write
.write_str(&self.buffer[0..(self.indent * self.indentation)])?;
self.current_line_empty = false;
}
Ok(())
}
pub fn write_str(&mut self, s: &str) -> fmt::Result {
if s.len() > 0 {
self.check_indent()?;
self.write.write_str(s)?;
self.current_line_empty = false;
}
Ok(())
}
pub fn new_line(&mut self) -> fmt::Result {
self.write.write_char('\n')?;
self.current_line_empty = true;
Ok(())
}
pub fn new_line_unless_empty(&mut self) -> fmt::Result {
if !self.current_line_empty {
self.new_line()?;
}
Ok(())
}
pub fn indent(&mut self) {
self.indent += 1;
let extra = (self.indent * self.indentation).saturating_sub(self.buffer.len());
for c in iter::repeat(' ').take(extra) {
self.buffer.push(c);
}
}
pub fn unindent(&mut self) {
self.indent = self.indent.saturating_sub(1);
}
}
impl<'write> fmt::Write for Formatter<'write> {
fn write_str(&mut self, s: &str) -> fmt::Result {
if s.len() > 0 {
self.check_indent()?;
self.write.write_str(s)?;
self.current_line_empty = false;
}
Ok(())
}
}