rust_hdl_core/
code_writer.rs1#[derive(Default)]
2pub(crate) struct CodeWriter {
3 lines: Vec<(usize, String)>,
4 indent: usize,
6 buffer: String,
8}
9
10impl CodeWriter {
11 pub(crate) fn push(&mut self) {
12 self.indent += 1
13 }
14
15 pub(crate) fn pop(&mut self) {
16 self.indent -= 1
17 }
18
19 pub(crate) fn add_line<S: AsRef<str>>(&mut self, val: S) {
20 self.lines.push((self.indent, String::from(val.as_ref())))
21 }
22
23 pub(crate) fn add<S: AsRef<str>>(&mut self, val: S) {
24 let temp = String::from(val.as_ref());
25 let pieces = temp.split_terminator('\n');
26 for piece in pieces {
27 self.add_line(piece)
28 }
29 }
30
31 pub(crate) fn write<S: AsRef<str>>(&mut self, val: S) {
32 self.buffer += val.as_ref()
33 }
34
35 pub(crate) fn writeln<S: AsRef<str>>(&mut self, val: S) {
36 self.write(val);
37 self.flush();
38 }
39
40 pub(crate) fn flush(&mut self) {
41 let line = self.buffer.clone();
42 self.add(&line);
43 self.buffer.clear()
44 }
45}
46
47impl ToString for CodeWriter {
48 fn to_string(&self) -> String {
49 let mut buf = String::new();
50 for (indent, line) in &self.lines {
51 buf += &" ".repeat(*indent);
52 buf += line;
53 buf += "\n"
54 }
55 buf
56 }
57}