carrier_core/xml/
write.rs1use core::fmt::Write as _;
4
5use jiff::civil::Date;
6
7#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
9#[error("{path}: {kind}")]
10pub struct WriteError {
11 pub path: String,
13 pub kind: WriteErrorKind,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
19#[non_exhaustive]
20pub enum WriteErrorKind {
21 #[error("{element} occurs {actual} times, at most {max} allowed")]
23 TooMany {
24 element: &'static str,
26 max: usize,
28 actual: usize,
30 },
31 #[error("{element} must occur at least once")]
33 Missing {
34 element: &'static str,
36 },
37}
38
39pub fn escape(out: &mut String, text: &str) {
42 for c in text.chars() {
43 match c {
44 '&' => out.push_str("&"),
45 '<' => out.push_str("<"),
46 '>' => out.push_str(">"),
47 '"' => out.push_str("""),
48 '\'' => out.push_str("'"),
49 '\r' => out.push_str(" "),
50 c => out.push(c),
51 }
52 }
53}
54
55#[derive(Debug, Default)]
57pub struct Writer {
58 pub out: String,
60 pub depth: usize,
62 path: Vec<&'static str>,
63}
64
65impl Writer {
66 #[must_use]
68 pub const fn new() -> Self {
69 Self { out: String::new(), depth: 0, path: Vec::new() }
70 }
71
72 fn indent(&mut self) {
73 for _ in 0..self.depth {
74 self.out.push_str(" ");
75 }
76 }
77
78 pub fn open(&mut self, name: &'static str, attrs: &[(&str, &str)]) {
80 self.indent();
81 self.out.push('<');
82 self.out.push_str(name);
83 for (k, v) in attrs {
84 self.out.push(' ');
85 self.out.push_str(k);
86 self.out.push_str("=\"");
87 escape(&mut self.out, v);
88 self.out.push('"');
89 }
90 self.out.push_str(">\n");
91 self.depth += 1;
92 self.path.push(name);
93 }
94
95 pub fn close(&mut self, name: &'static str) {
97 self.depth = self.depth.saturating_sub(1);
98 self.path.pop();
99 self.indent();
100 self.out.push_str("</");
101 self.out.push_str(name);
102 self.out.push_str(">\n");
103 }
104
105 pub fn typed(&mut self, name: &'static str, prefix: &str, ty: &str) {
107 let value = format!("{prefix}:{ty}");
108 self.open(name, &[("xsi:type", &value)]);
109 }
110
111 pub fn leaf(&mut self, name: &'static str, text: &str) {
113 self.indent();
114 let _ = write!(self.out, "<{name}>");
115 escape(&mut self.out, text);
116 let _ = writeln!(self.out, "</{name}>");
117 }
118
119 pub fn opt(&mut self, name: &'static str, text: Option<&str>) {
121 if let Some(text) = text {
122 self.leaf(name, text);
123 }
124 }
125
126 pub fn date(&mut self, name: &'static str, d: Date) {
128 self.leaf(name, &d.to_string());
129 }
130
131 pub fn opt_date(&mut self, name: &'static str, d: Option<Date>) {
133 if let Some(d) = d {
134 self.date(name, d);
135 }
136 }
137
138 pub fn boolean(&mut self, name: &'static str, b: bool) {
140 self.leaf(name, if b { "true" } else { "false" });
141 }
142
143 #[must_use]
145 pub fn path(&self) -> String {
146 self.path.join("/")
147 }
148
149 pub fn count(&self, element: &'static str, actual: usize, min: usize, max: usize) -> Result<(), WriteError> {
155 if actual < min {
156 return Err(WriteError { path: self.path(), kind: WriteErrorKind::Missing { element } });
157 }
158 if actual > max {
159 return Err(WriteError { path: self.path(), kind: WriteErrorKind::TooMany { element, max, actual } });
160 }
161 Ok(())
162 }
163}