use std::fmt::{Display, Formatter};
#[derive(Clone, Debug)]
pub struct CodeBuffer {
indent: String,
line_ending: String,
code: String,
}
impl CodeBuffer {
pub const DEFAULT_INDENT: &'static str = " ";
pub const DEFAULT_LINE_ENDING: &'static str = "\n";
pub const DEFAULT_CAPACITY: usize = 4 * 1024;
}
impl CodeBuffer {
pub fn new<S0, S1>(indent: S0, line_ending: S1, capacity: usize) -> Self
where
S0: Into<String>,
S1: Into<String>,
{
Self {
indent: indent.into(),
line_ending: line_ending.into(),
code: String::with_capacity(capacity),
}
}
}
impl Default for CodeBuffer {
fn default() -> Self {
Self::new(
Self::DEFAULT_INDENT,
Self::DEFAULT_LINE_ENDING,
Self::DEFAULT_CAPACITY,
)
}
}
impl CodeBuffer {
pub fn write(&mut self, code: &str) {
self.code.push_str(code);
}
pub fn indent(&mut self, level: usize) {
for _ in 0..level {
self.code.push_str(self.indent.as_mut_str());
}
}
pub fn end_line(&mut self) {
self.code.push_str(self.line_ending.as_str());
}
pub fn line(&mut self, level: usize, code: &str) {
self.indent(level);
self.write(code);
self.end_line();
}
pub fn space(&mut self) {
self.code.push_str(" ");
}
}
impl CodeBuffer {
pub fn peek(&self) -> &str {
self.code.as_str()
}
pub fn export(self) -> String {
self.code
}
pub fn clear(&mut self) {
self.code.clear();
}
}
impl Display for CodeBuffer {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.peek())
}
}