use core::fmt::Write as _;
use jiff::civil::Date;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{path}: {kind}")]
pub struct WriteError {
pub path: String,
pub kind: WriteErrorKind,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum WriteErrorKind {
#[error("{element} occurs {actual} times, at most {max} allowed")]
TooMany {
element: &'static str,
max: usize,
actual: usize,
},
#[error("{element} must occur at least once")]
Missing {
element: &'static str,
},
}
pub fn escape(out: &mut String, text: &str) {
for c in text.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
'\r' => out.push_str(" "),
c => out.push(c),
}
}
}
#[derive(Debug, Default)]
pub struct Writer {
pub out: String,
pub depth: usize,
path: Vec<&'static str>,
}
impl Writer {
#[must_use]
pub const fn new() -> Self {
Self { out: String::new(), depth: 0, path: Vec::new() }
}
fn indent(&mut self) {
for _ in 0..self.depth {
self.out.push_str(" ");
}
}
pub fn open(&mut self, name: &'static str, attrs: &[(&str, &str)]) {
self.indent();
self.out.push('<');
self.out.push_str(name);
for (k, v) in attrs {
self.out.push(' ');
self.out.push_str(k);
self.out.push_str("=\"");
escape(&mut self.out, v);
self.out.push('"');
}
self.out.push_str(">\n");
self.depth += 1;
self.path.push(name);
}
pub fn close(&mut self, name: &'static str) {
self.depth = self.depth.saturating_sub(1);
self.path.pop();
self.indent();
self.out.push_str("</");
self.out.push_str(name);
self.out.push_str(">\n");
}
pub fn typed(&mut self, name: &'static str, prefix: &str, ty: &str) {
let value = format!("{prefix}:{ty}");
self.open(name, &[("xsi:type", &value)]);
}
pub fn leaf(&mut self, name: &'static str, text: &str) {
self.indent();
let _ = write!(self.out, "<{name}>");
escape(&mut self.out, text);
let _ = writeln!(self.out, "</{name}>");
}
pub fn opt(&mut self, name: &'static str, text: Option<&str>) {
if let Some(text) = text {
self.leaf(name, text);
}
}
pub fn date(&mut self, name: &'static str, d: Date) {
self.leaf(name, &d.to_string());
}
pub fn opt_date(&mut self, name: &'static str, d: Option<Date>) {
if let Some(d) = d {
self.date(name, d);
}
}
pub fn boolean(&mut self, name: &'static str, b: bool) {
self.leaf(name, if b { "true" } else { "false" });
}
#[must_use]
pub fn path(&self) -> String {
self.path.join("/")
}
pub fn count(&self, element: &'static str, actual: usize, min: usize, max: usize) -> Result<(), WriteError> {
if actual < min {
return Err(WriteError { path: self.path(), kind: WriteErrorKind::Missing { element } });
}
if actual > max {
return Err(WriteError { path: self.path(), kind: WriteErrorKind::TooMany { element, max, actual } });
}
Ok(())
}
}