1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7pub enum StrCmd {
8 Write(Box<str>),
10 NewLine,
12 Push(Box<str>),
14 Pop,
16}
17
18pub struct PrefixWriter<'a, W: std::io::Write> {
19 file: &'a mut W,
20 stack: Vec<Box<str>>,
21 escaping: bool,
27 bracketed: bool,
30}
31
32impl<'a, W: std::io::Write> PrefixWriter<'a, W> {
33 pub fn new(file: &'a mut W) -> Self {
34 Self {
35 file,
36 stack: Vec::new(),
37 escaping: false,
38 bracketed: false,
39 }
40 }
41
42 pub fn quilt(file: &'a mut W) -> Self {
44 Self {
45 escaping: true,
46 ..Self::new(file)
47 }
48 }
49
50 pub fn set_escaping(&mut self, escaping: bool) -> bool {
54 std::mem::replace(&mut self.escaping, escaping)
55 }
56
57 #[must_use]
58 pub fn escaping(&self) -> bool {
59 self.escaping
60 }
61
62 pub fn set_bracketed(&mut self, bracketed: bool) -> bool {
69 std::mem::replace(&mut self.bracketed, bracketed)
70 }
71
72 #[must_use]
73 pub fn bracketed(&self) -> bool {
74 self.bracketed
75 }
76
77 pub fn write(&mut self, s: &str) {
78 if self.escaping {
79 write!(self.file, "{}", crate::glyphs::escape(s)).unwrap();
80 } else {
81 write!(self.file, "{s}").unwrap();
82 }
83 }
84
85 pub fn newline(&mut self) {
86 writeln!(self.file).unwrap();
87 for prefix in &self.stack {
88 write!(self.file, "{prefix}").unwrap();
89 }
90 }
91
92 pub fn push(&mut self, s: &str) {
93 self.stack.push(s.into());
94 }
95
96 pub fn pop(&mut self) {
97 self.stack.pop();
98 }
99
100 pub fn interpret(&mut self, cmd: &StrCmd) {
101 match cmd {
102 StrCmd::Write(s) => self.write(s),
103 StrCmd::NewLine => self.newline(),
104 StrCmd::Push(s) => self.push(s),
105 StrCmd::Pop => self.pop(),
106 }
107 }
108}
109
110pub fn write(s: &str) -> StrCmd {
111 StrCmd::Write(s.into())
112}
113
114pub fn newline() -> StrCmd {
115 StrCmd::NewLine
116}
117
118pub fn push(s: &str) -> StrCmd {
119 StrCmd::Push(s.into())
120}
121
122pub fn pop() -> StrCmd {
123 StrCmd::Pop
124}
125
126pub const NL: StrCmd = StrCmd::NewLine;
127pub const POP: StrCmd = StrCmd::Pop;