1use crate::XmlError;
2use crate::XmlRootTag;
3use quick_xml::events::{BytesStart, Event};
4use quick_xml::name::ResolveResult;
5use std::io::BufRead;
6pub use xml_derive::XmlDeserialize;
7pub use xml_derive::XmlDocument;
8
9pub trait XmlDeserialize: Sized {
10 fn deserialize<R: BufRead>(
11 reader: &mut quick_xml::NsReader<R>,
12 start: &BytesStart,
13 empty: bool,
14 ) -> Result<Self, XmlError>;
15}
16
17pub trait XmlDocument: XmlDeserialize {
18 fn parse<R: BufRead>(reader: quick_xml::NsReader<R>) -> Result<Self, XmlError>;
19
20 #[inline]
21 fn parse_reader<R: BufRead>(input: R) -> Result<Self, XmlError> {
22 let reader = quick_xml::NsReader::from_reader(input);
23 Self::parse(reader)
24 }
25
26 #[inline]
27 fn parse_str(s: &str) -> Result<Self, XmlError> {
28 Self::parse_reader(s.as_bytes())
29 }
30}
31
32impl<T: XmlRootTag + XmlDeserialize> XmlDocument for T {
33 fn parse<R: BufRead>(mut reader: quick_xml::NsReader<R>) -> Result<Self, XmlError>
34 where
35 Self: XmlDeserialize,
36 {
37 let mut buf = Vec::new();
38 loop {
39 let event = reader.read_event_into(&mut buf)?;
40 let empty = matches!(event, Event::Empty(_));
41 match event {
42 Event::Decl(_) | Event::Comment(_) => { }
43 Event::Start(start) | Event::Empty(start) => {
44 let (ns, name) = reader.resolver().resolve_element(start.name());
45 let matches = match (Self::root_ns(), &ns, name) {
46 (_, _, name) if name.as_ref() != Self::root_tag().as_bytes() => false,
48 (Some(root_ns), ns, _) if &ResolveResult::Bound(root_ns) != ns => false,
50 _ => true,
51 };
52 if !matches {
53 let root_ns = Self::root_ns();
54 return Err(XmlError::InvalidTag(
55 format!("{ns:?}"),
56 String::from_utf8_lossy(name.as_ref()).to_string(),
57 format!("{root_ns:?}"),
58 Self::root_tag().to_owned(),
59 ));
60 }
61
62 return Self::deserialize(&mut reader, &start, empty);
63 }
64 Event::Eof => return Err(XmlError::Eof),
65 Event::Text(text) => {
66 if text
67 .xml11_content()?
68 .chars()
69 .any(|chr| !chr.is_whitespace())
70 {
71 return Err(XmlError::UnsupportedEvent("unexpected text"));
72 }
73 }
74 _ => return Err(XmlError::UnsupportedEvent("unknown, todo")),
75 }
76 }
77 }
78}
79
80impl XmlDeserialize for () {
81 fn deserialize<R: BufRead>(
82 reader: &mut quick_xml::NsReader<R>,
83 start: &BytesStart,
84 empty: bool,
85 ) -> Result<Self, XmlError> {
86 if empty {
87 return Ok(());
88 }
89 let mut buf = Vec::new();
90 loop {
91 match reader.read_event_into(&mut buf)? {
92 Event::End(e) if e.name() == start.name() => return Ok(()),
93 Event::Eof => return Err(XmlError::Eof),
94 _ => {}
95 }
96 }
97 }
98}