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
use std::fmt::Write;
use crate::*;
fn escape(s: &str) -> String {
s.chars().fold(String::new(), |mut s, ch| match ch {
'<' => s + "<",
'>' => s + ">",
'&' => s + "&",
'\'' => s + "'",
'"' => s + """,
_ => { write!(&mut s, "{ch}").unwrap(); s },
})
}
impl ToXml for Xml {
fn to_xml(&self) -> Xml {
self.clone()
}
}
impl ToXml for &str {
fn to_xml(&self) -> Xml {
Xml(vec![Content::Word(escape(self))])
}
}
impl ToXml for String {
fn to_xml(&self) -> Xml {
self.as_str().to_xml()
}
}
impl ToXml for char {
fn to_xml(&self) -> Xml {
Xml(vec![Content::Word(escape(&self.to_string()))])
}
}
impl<T: ToXml> ToXml for Vec<T> {
fn to_xml(&self) -> Xml {
let contents = self.iter()
.map(|x| x.to_xml())
.map(|mut x| {
if x.0.len() == 1 {
x.0.drain(0..1).next().unwrap()
} else {
Content::Nested(x)
}
})
.collect();
Xml(contents)
}
}
impl<T: ToXml> ToXml for Option<T> {
fn to_xml(&self) -> Xml {
match self {
Some(x) => x.to_xml(),
None => Xml::default(),
}
}
}
impl<T: ToXml, E: ToXml> ToXml for Result<T, E> {
fn to_xml(&self) -> Xml {
match self {
Ok(x) => x.to_xml(),
Err(x) => x.to_xml(),
}
}
}
impl<T: ToXml> ToXml for &T {
fn to_xml(&self) -> Xml {
(*self).to_xml()
}
}
macro_rules! simple_impl {
($t:ty) => {
impl ToXml for $t {
fn to_xml(&self) -> Xml {
Xml(vec![Content::Word(self.to_string())])
}
}
};
}
simple_impl!(u8);
simple_impl!(u16);
simple_impl!(u32);
simple_impl!(u64);
simple_impl!(u128);
simple_impl!(usize);
simple_impl!(i8);
simple_impl!(i16);
simple_impl!(i32);
simple_impl!(i64);
simple_impl!(i128);
simple_impl!(isize);
simple_impl!(bool);