1pub struct CodeWriter {
3 buf: String,
4 indent: usize,
5}
6
7impl Default for CodeWriter {
8 fn default() -> Self {
9 Self::new()
10 }
11}
12
13impl CodeWriter {
14 pub fn new() -> Self {
15 Self {
16 buf: String::new(),
17 indent: 0,
18 }
19 }
20
21 pub fn line(&mut self, text: &str) {
23 if text.is_empty() {
24 self.buf.push('\n');
25 } else {
26 for _ in 0..self.indent {
27 self.buf.push_str(" ");
28 }
29 self.buf.push_str(text);
30 self.buf.push('\n');
31 }
32 }
33
34 pub fn indent(&mut self) {
36 self.indent += 1;
37 }
38
39 pub fn dedent(&mut self) {
41 self.indent = self.indent.saturating_sub(1);
42 }
43
44 pub fn open_block(&mut self, prefix: &str) {
46 self.line(&format!("{prefix} {{"));
47 self.indent();
48 }
49
50 pub fn close_block(&mut self) {
52 self.dedent();
53 self.line("}");
54 }
55
56 pub fn blank(&mut self) {
58 self.buf.push('\n');
59 }
60
61 pub fn finish(self) -> String {
63 self.buf
64 }
65}