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
pub mod prelude;
pub mod attributes;
pub mod path;
pub mod tag_name;
#[cfg(feature = "parsing")]
pub mod parser;
pub type Point2D = (f32, f32);
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use attributes::Attribute;
use tag_name::TagName;
type Attributes = HashMap<Attribute, String>;
type Children = Vec<Element>;
#[derive(Debug)]
pub struct Element {
tag_name: TagName,
attributes: Attributes,
children: Children,
inner: Option<String>,
}
impl Element {
pub fn new(tag_name: TagName) -> Element {
Element {
tag_name,
attributes: HashMap::new(),
children: Vec::new(),
inner: None,
}
}
pub fn append(mut self, child: Element) -> Self {
self.children.push(child);
self
}
fn is_allowed_inner(text: &str) -> bool {
let regular_expression =
regex::Regex::new(r#"[a-zA-Z0-9' \\-_/.!?:;(){}[\\]`~&,"]+"#).unwrap();
regular_expression.is_match(text)
}
pub fn set_inner(mut self, text: &str) -> Self {
if !Element::is_allowed_inner(text) {
return self;
}
self.inner = Some(String::from(String::from(text).trim()));
self
}
pub fn set<T>(mut self, attribute: Attribute, value: T) -> Self
where
T: ToString,
{
self.attributes.insert(attribute, value.to_string());
self
}
pub fn get_tag_name(&self) -> &TagName {
&self.tag_name
}
pub fn get_attributes(&self) -> &Attributes {
&self.attributes
}
pub fn get_children(&self) -> &Children {
&self.children
}
pub fn get_inner(&self) -> &Option<String> {
&self.inner
}
}
impl Clone for Element {
fn clone(&self) -> Self {
let mut elem = Element::new(self.tag_name);
for (key, value) in self.attributes.iter() {
elem.attributes.insert(key.clone(), value.clone());
}
for child in self.children.iter() {
elem = elem.append(child.clone());
}
elem
}
}
impl Hash for Element {
fn hash<T: Hasher>(&self, state: &mut T) {
self.tag_name.hash(state);
self.attributes.iter().for_each(|(key, value)| {
key.hash(state);
value.hash(state);
});
self.children.iter().for_each(|child| child.hash(state));
}
}
impl Into<Element> for TagName {
fn into(self) -> Element {
Element::new(self)
}
}