summaryrefslogtreecommitdiff
path: root/src/xml/element.rs
blob: db2878b3bd2256b346ee267146ccdd57f4eb72b2 (plain)
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
use std::fmt::Display;

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Elements
{
    elements: Vec<Element>,
}

impl Elements
{
    pub fn get_first_tagged(&self) -> Option<&Tagged>
    {
        self.elements.iter().find_map(|element| match element {
            Element::Tagged(tagged_element) => Some(tagged_element),
            _ => None,
        })
    }

    pub fn get_first_tagged_with_name(&self, tag_name: &str) -> Option<&Tagged>
    {
        self.elements.iter().find_map(|element| match element {
            Element::Tagged(tagged_element) if tagged_element.name == tag_name => {
                Some(tagged_element)
            }
            _ => None,
        })
    }

    pub fn get_all_tagged_elements(&self) -> Vec<&Tagged>
    {
        self.elements
            .iter()
            .filter_map(|element| match element {
                Element::Tagged(tagged_element) => Some(tagged_element),
                _ => None,
            })
            .collect()
    }

    pub fn get_all_tagged_elements_with_name(&self, tag_name: &str) -> Vec<&Tagged>
    {
        self.elements
            .iter()
            .filter_map(|element| match element {
                Element::Tagged(tagged_element) if tagged_element.name == tag_name => {
                    Some(tagged_element)
                }
                _ => None,
            })
            .collect()
    }

    pub fn get_all_tagged_with_name_and_attr(
        &self,
        tag_name: &str,
        attr_is_match: fn(&Attribute) -> bool,
    ) -> Vec<&Tagged>
    {
        self.elements
            .iter()
            .filter_map(|element| match element {
                Element::Tagged(tagged_element)
                    if tagged_element.name == tag_name
                        && tagged_element.attributes.iter().any(attr_is_match) =>
                {
                    Some(tagged_element)
                }
                _ => None,
            })
            .collect()
    }

    pub fn get_first_text_element(&self) -> Option<&String>
    {
        self.elements.iter().find_map(|element| match element {
            Element::Text(text) => Some(text),
            _ => None,
        })
    }

    pub fn get_all_text_elements(&self) -> Vec<&String>
    {
        self.elements
            .iter()
            .filter_map(|element| match element {
                Element::Text(text) => Some(text),
                _ => None,
            })
            .collect()
    }

    pub fn has_tagged_element(&self, tag_name: &str) -> bool
    {
        self.elements.iter().any(|element| {
            matches!(
                element,
                Element::Tagged(tagged_element) if tagged_element.name == tag_name
            )
        })
    }
}

impl<IntoIter: IntoIterator<Item = Element>> From<IntoIter> for Elements
{
    fn from(into_iter: IntoIter) -> Self
    {
        Self {
            elements: into_iter.into_iter().collect(),
        }
    }
}

impl<'elements> IntoIterator for &'elements Elements
{
    type IntoIter = Iter<'elements>;
    type Item = &'elements Element;

    fn into_iter(self) -> Self::IntoIter
    {
        Self::IntoIter {
            elements: self.elements.iter(),
        }
    }
}

pub struct Iter<'elements>
{
    elements: std::slice::Iter<'elements, Element>,
}

impl<'elements> Iterator for Iter<'elements>
{
    type Item = &'elements Element;

    fn next(&mut self) -> Option<Self::Item>
    {
        self.elements.next()
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Element
{
    Tagged(Tagged),
    Text(String),
    Comment(String),
}

impl Display for Element
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
    {
        match self {
            Self::Tagged(tagged) => tagged.fmt(formatter),
            Self::Text(text) => text.fmt(formatter),
            Self::Comment(comment) => {
                formatter.write_fmt(format_args!("<!--{comment}-->"))
            }
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Tagged
{
    name: String,
    child_elements: Elements,
    attributes: Vec<Attribute>,
}

impl Display for Tagged
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
    {
        let name = &self.name;

        let attrs = self
            .attributes
            .iter()
            .map(|attr| {
                format!("{}=\"{}\" ", attr.key, String::from_utf8_lossy(&attr.value))
            })
            .collect::<String>();

        let child_elements = self
            .child_elements
            .into_iter()
            .map(ToString::to_string)
            .collect::<String>();

        formatter.write_fmt(format_args!("<{name} {attrs}>{child_elements}</{name}>",))
    }
}

impl Tagged
{
    pub fn new<Name, ChildElements, Attrs>(
        name: &Name,
        child_elements: ChildElements,
        attributes: Attrs,
    ) -> Self
    where
        Name: ToString,
        ChildElements: Into<Elements>,
        Attrs: IntoIterator<Item = Attribute>,
    {
        Self {
            name: name.to_string(),
            child_elements: child_elements.into(),
            attributes: attributes.into_iter().collect(),
        }
    }

    pub fn name(&self) -> &str
    {
        &self.name
    }

    pub fn attributes(&self) -> &[Attribute]
    {
        &self.attributes
    }

    pub fn child_elements(&self) -> &Elements
    {
        &self.child_elements
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Attribute
{
    pub key: String,
    pub value: Vec<u8>,
}

pub trait FromElements: Sized
{
    type Error;

    fn from_elements(elements: &Elements) -> Result<Self, Self::Error>;
}