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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use std::fmt::Debug;
use std::io::Write;
use std::usize;

type Result<T> = std::result::Result<T, XMLError>;

/// Error type thrown by this crate
pub enum XMLError {
    WrongInsert(String),
    WriteError(String),
}

impl From<std::io::Error> for XMLError {
    fn from(e: std::io::Error) -> Self {
        XMLError::WriteError(e.to_string())
    }
}

impl Debug for XMLError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XMLError::WrongInsert(e) => write!(f, "Error encountered during insertion: {}", e),
            XMLError::WriteError(e) => write!(f, "Error encountered during write: {}", e),
        }
    }
}

impl Default for XML {
    fn default() -> Self {
        XML {
            version: "1.0".into(),
            encoding: "UTF-8".into(),
            should_render_header: true,
            should_sort_attributes: false,
            custom_header: None,
            root: None,
        }
    }
}

/// Structure representing a XML document.
/// It must be used to create a XML document.
pub struct XML {
    version: String,
    encoding: String,
    should_render_header: bool,
    should_sort_attributes: bool,
    custom_header: Option<String>,
    root: Option<XMLElement>,
}

impl XML {
    /// Instantiates a XML object.
    pub fn new() -> Self {
        XML::default()
    }

    /// Does not render XML header for this document
    ///
    /// Can be used in case of a custom XML implementation such as XMLTV
    pub fn set_header_rendering(&mut self, asked: bool) {
        self.should_render_header = asked;
    }

    /// Sets the XML version attribute field.
    pub fn set_version(&mut self, version: String) {
        self.version = version;
    }

    /// Sets the XML encoding attribute field.
    pub fn set_encoding(&mut self, encoding: String) {
        self.encoding = encoding;
    }

    /// Sets the header attribute sort.
    pub fn set_attribute_sorting(&mut self, should_sort: bool) {
        self.should_sort_attributes = should_sort;
    }

    /// Sets a custom XML header.
    ///
    /// Be careful, no syntax and semantic verifications are made on this header.
    pub fn set_custom_header(&mut self, header: String) {
        self.custom_header = Some(header);
    }

    /// Sets the XML document root element.
    pub fn set_root_element(&mut self, element: XMLElement) {
        self.root = Some(element);
    }

    /// Builds an XML document into the specified writer implementing Write trait.
    ///
    /// Consumes the XML object.
    pub fn build<W: Write>(self, mut writer: W) -> Result<()> {
        // Rendering first XML header line if asked...
        if self.should_render_header {
            if let Some(header) = &self.custom_header {
                writeln!(writer, r#"<{}>"#, header)?;
            } else {
                writeln!(
                    writer,
                    r#"<?xml encoding="{}" version="{}"?>"#,
                    self.encoding, self.version
                )?;
            }
        }

        // And then XML elements if present...
        if let Some(elem) = &self.root {
            elem.render(&mut writer, self.should_sort_attributes)?;
        }

        Ok(())
    }
}

/// Structure representing an XML element field.
pub struct XMLElement {
    name: String,
    attributes: Vec<(String, String)>,
    should_sort_attributes: Option<bool>,
    content: XMLElementContent,
}

impl XMLElement {
    /// Instantiates a XMLElement object.
    ///
    /// # Arguments
    ///
    /// * `name` - A string slice that holds the name of the XML element.
    pub fn new(name: &str) -> Self {
        XMLElement {
            name: name.into(),
            attributes: Vec::new(),
            should_sort_attributes: None,
            content: XMLElementContent::Empty,
        }
    }

    pub fn set_attribute_sorting(&mut self, should_sort: bool) {
        self.should_sort_attributes = Some(should_sort);
    }

    /// Adds the given name/value attribute to the XMLElement.
    ///
    /// # Arguments
    ///
    /// * `name` - A string slice that holds the name of the attribute
    /// * `value` - A string slice that holds the value of the attribute
    pub fn add_attribute(&mut self, name: &str, value: &str) {
        self.attributes.push((name.into(), escape_str(value)));
    }

    /// Adds a new XMLElement child object to the references XMLElement.
    /// Raises a XMLError if trying to add a child to a text XMLElement.
    ///
    /// # Arguments
    ///
    /// * `element` - A XMLElement object to add as child
    pub fn add_child(&mut self, element: XMLElement) -> Result<()> {
        match self.content {
            XMLElementContent::Empty => {
                self.content = XMLElementContent::Elements(vec![element]);
            }
            XMLElementContent::Elements(ref mut e) => {
                e.push(element);
            }
            XMLElementContent::Text(_) => {
                return Err(XMLError::WrongInsert(
                    "Cannot insert child inside an element with text".into(),
                ))
            }
        };

        Ok(())
    }

    /// Adds text content to a XMLElement object.
    /// Raises a XMLError if trying to add text to a non-empty object.
    ///
    /// # Arguments
    ///
    /// * `text` - A string containing the text to add to the object
    pub fn add_text(&mut self, text: String) -> Result<()> {
        match self.content {
            XMLElementContent::Empty => {
                self.content = XMLElementContent::Text(text);
            }
            _ => {
                return Err(XMLError::WrongInsert(
                    "Cannot insert text in a non-empty element".into(),
                ))
            }
        };

        Ok(())
    }

    /// Internal method rendering an attribute list to a String.
    fn attributes_as_string(&self, should_sort: bool) -> String {
        if self.attributes.is_empty() {
            "".to_owned()
        } else {
            let mut attributes = self.attributes.clone();

            // Giving priority to the element boolean, and taking the global xml if not set
            let should_sort_attributes = self.should_sort_attributes.unwrap_or(should_sort);

            if should_sort_attributes {
                attributes.sort();
            }

            let mut result = "".into();

            for (k, v) in &attributes {
                result = format!("{} {}", result, format!(r#"{}="{}""#, k, v));
            }
            result
        }
    }

    /// Renders an XMLElement object into the specified writer implementing Write trait.
    /// Does not take ownership of the object.
    ///
    /// # Arguments
    ///
    /// * `writer` - An object to render the referenced XMLElement to
    pub fn render<W: Write>(&self, writer: &mut W, should_sort: bool) -> Result<()> {
        self.render_level(writer, 0, should_sort)
    }

    /// Internal method rendering and indenting a XMLELement object
    ///
    /// # Arguments
    ///
    /// * `writer` - An object to render the referenced XMLElement to
    /// * `level` - An usize representing the depth of the XML tree. Used to indent the object.
    fn render_level<W: Write>(
        &self,
        writer: &mut W,
        level: usize,
        should_sort: bool,
    ) -> Result<()> {
        let indent = "\t".repeat(level);
        let attributes = self.attributes_as_string(should_sort);

        match &self.content {
            XMLElementContent::Empty => {
                writeln!(writer, "{}<{}{} />", indent, self.name, attributes)?;
            }
            XMLElementContent::Elements(elements) => {
                writeln!(writer, "{}<{}{}>", indent, self.name, attributes)?;
                for elem in elements {
                    elem.render_level(writer, level + 1, should_sort)?;
                }
                writeln!(writer, "{}</{}>", indent, self.name)?;
            }
            XMLElementContent::Text(text) => {
                writeln!(
                    writer,
                    "{}<{}{}>{}</{}>",
                    indent, self.name, attributes, text, self.name
                )?;
            }
        };

        Ok(())
    }
}

fn escape_str(input: &str) -> String {
    input
        .to_owned()
        .replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

enum XMLElementContent {
    Empty,
    Elements(Vec<XMLElement>),
    Text(String),
}

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

    #[test]
    fn test_xml_default_creation() {
        let xml = XML::new();
        let writer = std::io::sink();
        xml.build(writer).unwrap();
    }

    #[test]
    fn test_xml_file_write() {
        let xml = XML::new();

        let mut writer: Vec<u8> = Vec::new();
        xml.build(&mut writer).unwrap();
    }

    #[test]
    fn test_xml_version() {
        let mut xml = XML::new();
        xml.set_version("1.1".into());

        let mut writer: Vec<u8> = Vec::new();
        xml.build(&mut writer).unwrap();

        let expected = "<?xml encoding=\"UTF-8\" version=\"1.1\"?>\n";
        let res = std::str::from_utf8(&writer).unwrap();

        assert_eq!(res, expected, "Both values does not match...");
    }

    #[test]
    fn test_xml_encoding() {
        let mut xml = XML::new();
        xml.set_encoding("UTF-16".into());

        let mut writer: Vec<u8> = Vec::new();
        xml.build(&mut writer).unwrap();

        let expected = "<?xml encoding=\"UTF-16\" version=\"1.0\"?>\n";
        let res = std::str::from_utf8(&writer).unwrap();

        assert_eq!(res, expected, "Both values does not match...");
    }

    #[test]
    fn test_custom_header() {
        let mut xml = XML::new();
        let header = "tv generator-info-name=\"my listings generator\"".into(); // XMLTV header example

        xml.set_custom_header(header);

        let mut writer: Vec<u8> = Vec::new();
        xml.build(&mut writer).unwrap();

        let expected = "<tv generator-info-name=\"my listings generator\">\n";
        let res = std::str::from_utf8(&writer).unwrap();

        assert_eq!(res, expected, "Both values does not match...");
    }

    #[test]
    fn test_complex_xml() {
        let mut xml = XML::new();
        xml.set_version("1.1".into());
        xml.set_encoding("UTF-8".into());

        let mut house = XMLElement::new("house");
        house.add_attribute("rooms", "2");

        for i in 1..=2 {
            let mut room = XMLElement::new("room");
            room.add_attribute("number", &i.to_string());
            room.add_text(format!("This is room number {}", i)).unwrap();

            house.add_child(room).unwrap();
        }

        xml.set_root_element(house);

        let mut writer: Vec<u8> = Vec::new();
        xml.build(&mut writer).unwrap();

        let expected = "<?xml encoding=\"UTF-8\" version=\"1.1\"?>
<house rooms=\"2\">
\t<room number=\"1\">This is room number 1</room>
\t<room number=\"2\">This is room number 2</room>
</house>\n";
        let res = std::str::from_utf8(&writer).unwrap();

        assert_eq!(res, expected, "Both values does not match...")
    }

    // Here the `sort` attribute is set to the root, so everything should be sorted
    #[test]
    fn test_complex_sorted_root_xml() {
        let mut xml = XML::new();
        xml.set_attribute_sorting(true);
        xml.set_version("1.1".into());
        xml.set_encoding("UTF-8".into());

        let mut house = XMLElement::new("house");
        house.add_attribute("rooms", "2");

        for i in 1..=2 {
            let mut room = XMLElement::new("room");
            room.add_attribute("size", &(i * 27).to_string());
            room.add_attribute("number", &i.to_string());
            room.add_text(format!("This is room number {}", i)).unwrap();

            house.add_child(room).unwrap();
        }

        xml.set_root_element(house);

        let mut writer: Vec<u8> = Vec::new();
        xml.build(&mut writer).unwrap();

        let expected = "<?xml encoding=\"UTF-8\" version=\"1.1\"?>
<house rooms=\"2\">
\t<room number=\"1\" size=\"27\">This is room number 1</room>
\t<room number=\"2\" size=\"54\">This is room number 2</room>
</house>\n";
        let res = std::str::from_utf8(&writer).unwrap();

        assert_eq!(res, expected, "Both values does not match...")
    }

    // Here the `sort` attribute is set to the an element only, so everything should not be sorted
    #[test]
    fn test_complex_sorted_element_xml() {
        let mut xml = XML::new();
        xml.set_version("1.1".into());
        xml.set_encoding("UTF-8".into());

        let mut house = XMLElement::new("house");
        house.add_attribute("rooms", "2");

        for i in 1..=2 {
            let mut room = XMLElement::new("room");
            room.add_attribute("size", &(i * 27).to_string());
            room.add_attribute("city", ["Paris", "LA"][i - 1]);
            room.add_attribute("number", &i.to_string());
            room.add_text(format!("This is room number {}", i)).unwrap();

            if i % 2 == 0 {
                room.set_attribute_sorting(true);
            }

            house.add_child(room).unwrap();
        }

        xml.set_root_element(house);

        let mut writer: Vec<u8> = Vec::new();
        xml.build(&mut writer).unwrap();

        let expected = "<?xml encoding=\"UTF-8\" version=\"1.1\"?>
<house rooms=\"2\">
\t<room size=\"27\" city=\"Paris\" number=\"1\">This is room number 1</room>
\t<room city=\"LA\" number=\"2\" size=\"54\">This is room number 2</room>
</house>\n";

        let res = std::str::from_utf8(&writer).unwrap();

        assert_eq!(res, expected, "Both values does not match...")
    }

    #[test]
    #[should_panic]
    fn test_panic_child_for_text_element() {
        let xml = XML::new();

        let mut xml_child = XMLElement::new("panic");
        xml_child
            .add_text("This should panic right after this...".into())
            .unwrap();

        let xml_child2 = XMLElement::new("sorry");
        xml_child.add_child(xml_child2).unwrap();

        xml.build(std::io::stdout()).unwrap();
    }
}