Skip to main content

carrier_core/xml/
write.rs

1//! The indenting writer.
2
3use core::fmt::Write as _;
4
5use jiff::civil::Date;
6
7/// A value the schema would reject, found while writing.
8#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
9#[error("{path}: {kind}")]
10pub struct WriteError {
11    /// Element path, e.g. `annehmenMeldungRequest/Meldung/Position`.
12    pub path: String,
13    /// What is wrong.
14    pub kind: WriteErrorKind,
15}
16
17/// What a [`WriteError`] reports.
18#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
19#[non_exhaustive]
20pub enum WriteErrorKind {
21    /// An element repeats more often than the schema allows.
22    #[error("{element} occurs {actual} times, at most {max} allowed")]
23    TooMany {
24        /// The element.
25        element: &'static str,
26        /// Schema maximum.
27        max: usize,
28        /// Count found.
29        actual: usize,
30    },
31    /// A mandatory repeated element is empty.
32    #[error("{element} must occur at least once")]
33    Missing {
34        /// The element.
35        element: &'static str,
36    },
37}
38
39/// Escapes text for element content and attribute values. Carriage returns are written as
40/// character references so they survive the parser's line-end normalisation.
41pub fn escape(out: &mut String, text: &str) {
42    for c in text.chars() {
43        match c {
44            '&' => out.push_str("&"),
45            '<' => out.push_str("&lt;"),
46            '>' => out.push_str("&gt;"),
47            '"' => out.push_str("&quot;"),
48            '\'' => out.push_str("&apos;"),
49            '\r' => out.push_str("&#13;"),
50            c => out.push(c),
51        }
52    }
53}
54
55/// Writes elements, two spaces per level, one element per line.
56#[derive(Debug, Default)]
57pub struct Writer {
58    /// The output so far.
59    pub out: String,
60    /// The current indentation level.
61    pub depth: usize,
62    path: Vec<&'static str>,
63}
64
65impl Writer {
66    /// An empty writer.
67    #[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    /// Opens `name` with attributes.
79    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    /// Closes `name`.
96    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    /// Opens `name` with `xsi:type="prefix:ty"`.
106    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    /// A text element.
112    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    /// A text element if `text` is present.
120    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    /// An `xsd:date` element.
127    pub fn date(&mut self, name: &'static str, d: Date) {
128        self.leaf(name, &d.to_string());
129    }
130
131    /// An optional `xsd:date` element.
132    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    /// An `xsd:boolean` element.
139    pub fn boolean(&mut self, name: &'static str, b: bool) {
140        self.leaf(name, if b { "true" } else { "false" });
141    }
142
143    /// The path of the open elements, joined by `/`.
144    #[must_use]
145    pub fn path(&self) -> String {
146        self.path.join("/")
147    }
148
149    /// Checks that `element` occurs `min..=max` times.
150    ///
151    /// # Errors
152    ///
153    /// [`WriteErrorKind::Missing`] or [`WriteErrorKind::TooMany`] at the current path.
154    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}