Skip to main content

schema_sql_generator/common/
print_writer.rs

1use std::io::{BufWriter, Write};
2
3pub struct PrintWriter {
4    writer: BufWriter<Box<dyn Write>>,
5    auto_flush: bool,
6}
7
8impl PrintWriter {
9    pub fn new(writer: Box<dyn Write>) -> Self {
10        Self {
11            writer: BufWriter::new(writer),
12            auto_flush: false,
13        }
14    }
15
16    pub fn new_auto_flush(writer: Box<dyn Write>) -> Self {
17        Self {
18            writer: BufWriter::new(writer),
19            auto_flush: true,
20        }
21    }
22
23    pub fn print(&mut self, text: &str) {
24        write!(self.writer, "{}", text).unwrap_or_else(|e| panic!("Error while writing: {}", e))
25    }
26
27    pub fn println(&mut self, text: &str) {
28        writeln!(self.writer, "{}", text).unwrap_or_else(|e| panic!("Error while writing: {}", e));
29        if self.auto_flush {
30            self.flush();
31        }
32    }
33
34    pub fn printf(&mut self, args: std::fmt::Arguments) {
35        write!(self.writer, "{}", args).unwrap_or_else(|e| panic!("Error while writing: {}", e));
36        if self.auto_flush {
37            self.flush();
38        }
39    }
40
41    pub fn newline(&mut self) {
42        writeln!(self.writer).unwrap_or_else(|e| panic!("Error while writing: {}", e));
43        if self.auto_flush {
44            self.flush();
45        }
46    }
47
48    pub fn flush(&mut self) {
49        self.writer.flush().unwrap_or_else(|e| panic!("Error while flushing: {}", e))
50    }
51}