1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use crate::errors::*;

use crate::hlua::AnyLuaValue;
use crate::json::LuaJsonValue;
use serde::Serialize;
use std::collections::HashMap;
use xml::attribute::OwnedAttribute;
use xml::name::OwnedName;
use xml::reader::{EventReader, ParserConfig, XmlEvent};

#[derive(Debug, PartialEq, Serialize)]
pub struct XmlDocument {
    pub children: Vec<XmlElement>,
}

impl Default for XmlDocument {
    fn default() -> Self {
        Self::new()
    }
}

impl XmlDocument {
    #[inline(always)]
    pub fn new() -> XmlDocument {
        XmlDocument {
            children: Vec::new(),
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct XmlElement {
    pub name: String,
    pub attrs: HashMap<String, String>,
    pub text: Option<String>,
    pub children: Vec<XmlElement>,
}

impl XmlElement {
    #[inline]
    fn from(name: OwnedName, attributes: Vec<OwnedAttribute>) -> XmlElement {
        let name = name.local_name;
        let attrs = attributes
            .into_iter()
            .map(|attr| (attr.name.local_name, attr.value))
            .collect();
        XmlElement {
            name,
            attrs,
            text: None,
            children: Vec::new(),
        }
    }
}

#[inline]
pub fn decode(x: &str) -> Result<AnyLuaValue> {
    let v = decode_raw(x)?;
    let v = serde_json::to_value(v)?;
    let v: LuaJsonValue = v.into();
    Ok(v.into())
}

#[inline]
fn append_text(stack: &mut [XmlElement], text: String) {
    if let Some(tail) = stack.last_mut() {
        if let Some(prev) = tail.text.as_mut() {
            prev.push_str(&text);
        } else {
            tail.text = Some(text);
        }
    }
}

fn decode_raw(x: &str) -> Result<XmlDocument> {
    let config = ParserConfig::new()
        .trim_whitespace(true)
        .whitespace_to_characters(true)
        .cdata_to_characters(true)
        .ignore_comments(true)
        .coalesce_characters(true);

    let parser = EventReader::new_with_config(x.as_bytes(), config);
    let mut stack = Vec::new();

    let mut doc = XmlDocument::new();

    for next in parser {
        let next = next?;
        debug!("xml element: {:?}", next);

        match next {
            XmlEvent::StartElement {
                name, attributes, ..
            } => {
                stack.push(XmlElement::from(name, attributes));
            }
            XmlEvent::EndElement { name } => {
                let child = stack
                    .pop()
                    .ok_or_else(|| format_err!("end element has no matching start element"))?;

                let name = name.local_name;
                if child.name != name {
                    bail!("end element name doesn't match start element name")
                }

                if let Some(tail) = stack.last_mut() {
                    tail.children.push(child);
                } else {
                    doc.children.push(child);
                }
            }
            XmlEvent::CData(text) => append_text(&mut stack, text),
            XmlEvent::Characters(text) => append_text(&mut stack, text),
            _ => (),
        }
    }

    // TODO: consider ignoring this?
    if !stack.is_empty() {
        bail!("end of document but still open elements remaining")
    }

    Ok(doc)
}

#[cfg(test)]
mod tests {
    use super::*;
    use maplit::hashmap;

    #[test]
    fn verify_xml_decode_empty() {
        let result = decode_raw("");
        assert!(result.is_err());
    }

    #[test]
    fn verify_xml_decode_empty_body() {
        let doc = decode_raw("<body></body>").unwrap();
        assert_eq!(
            doc,
            XmlDocument {
                children: vec![XmlElement {
                    name: String::from("body"),
                    attrs: HashMap::new(),
                    text: None,
                    children: vec![],
                }]
            }
        );
    }

    #[test]
    fn verify_xml_decode_single_tag() {
        let doc = decode_raw("<body><foo x=\"1\" /></body>").unwrap();
        assert_eq!(
            doc,
            XmlDocument {
                children: vec![XmlElement {
                    name: String::from("body"),
                    attrs: HashMap::new(),
                    text: None,
                    children: vec![XmlElement {
                        name: String::from("foo"),
                        attrs: hashmap! {
                            String::from("x") => String::from("1"),
                        },
                        text: None,
                        children: vec![],
                    }],
                }]
            }
        );
    }

    #[test]
    fn verify_xml_decode_single_tag_text() {
        let doc = decode_raw("<body><foo x=\"1\">hello world</foo></body>").unwrap();
        assert_eq!(
            doc,
            XmlDocument {
                children: vec![XmlElement {
                    name: String::from("body"),
                    attrs: HashMap::new(),
                    text: None,
                    children: vec![XmlElement {
                        name: String::from("foo"),
                        attrs: hashmap! {
                            String::from("x") => String::from("1"),
                        },
                        text: Some(String::from("hello world")),
                        children: vec![],
                    }],
                }]
            }
        );
    }
}