-
Notifications
You must be signed in to change notification settings - Fork 69
/
node.rs
193 lines (164 loc) · 5.73 KB
/
node.rs
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
use std::io;
use html5ever::serialize;
use string_cache::{Atom, Namespace, QualName};
use tendril::StrTendril;
use document::Document;
use predicate::Predicate;
use selection::Selection;
/// The Node type specific data stored by every Node.
#[derive(Clone, Debug, PartialEq)]
pub enum Data {
Text(StrTendril),
Element(Atom, Vec<(Atom, StrTendril)>, Vec<usize>),
Comment(StrTendril),
}
/// Internal representation of a Node. Not of much use without a reference to a
/// Document.
#[derive(Clone, Debug, PartialEq)]
pub struct Raw {
pub index: usize,
pub parent: Option<usize>,
pub prev: Option<usize>,
pub next: Option<usize>,
pub data: Data,
}
/// A Node.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Node<'a> {
document: &'a Document,
index: usize,
}
impl<'a> Node<'a> {
pub fn new(document: &'a Document, index: usize) -> Option<Node<'a>> {
if index < document.nodes.len() {
Some(Node {
document: document,
index: index,
})
} else {
None
}
}
pub fn index(&self) -> usize {
self.index
}
pub fn raw(&self) -> &Raw {
&self.document.nodes[self.index]
}
pub fn data(&self) -> &Data {
&self.raw().data
}
pub fn name(&self) -> Option<&str> {
match *self.data() {
Data::Element(ref name, _, _) => Some(name),
_ => None,
}
}
pub fn attr(&self, name: &str) -> Option<&str> {
match *self.data() {
Data::Element(_, ref attrs, _) => {
let name = Atom::from(name);
attrs.iter()
.find(|&&(ref name_, _)| name == *name_)
.map(|&(_, ref value)| value.as_ref())
}
_ => None,
}
}
pub fn parent(&self) -> Option<Node<'a>> {
self.raw().parent.map(|index| self.document.nth(index).unwrap())
}
pub fn prev(&self) -> Option<Node<'a>> {
self.raw().prev.map(|index| self.document.nth(index).unwrap())
}
pub fn next(&self) -> Option<Node<'a>> {
self.raw().next.map(|index| self.document.nth(index).unwrap())
}
pub fn text(&self) -> String {
let mut string = String::new();
recur(&self.document, self.index, &mut string);
return string;
fn recur(document: &Document, index: usize, string: &mut String) {
match document.nodes[index].data {
Data::Text(ref text) => string.push_str(text),
Data::Element(_, _, ref children) => {
for &child in children {
recur(document, child, string)
}
}
Data::Comment(_) => {}
}
}
}
pub fn html(&self) -> String {
let mut buf = Vec::new();
serialize::serialize(&mut buf, self, Default::default()).unwrap();
String::from_utf8(buf).unwrap()
}
pub fn inner_html(&self) -> String {
let mut buf = Vec::new();
if let Data::Element(_, _, ref children) = *self.data() {
for &child in children {
serialize::serialize(&mut buf,
&self.document.nth(child).unwrap(),
Default::default())
.unwrap();
}
}
String::from_utf8(buf).unwrap()
}
pub fn find<P: Predicate>(&self, p: P) -> Selection<'a> {
Selection::new(self.document, [self.index].iter().cloned().collect()).find(p)
}
pub fn is<P: Predicate>(&self, p: P) -> bool {
p.matches(self)
}
pub fn as_text(&self) -> Option<&str> {
match *self.data() {
Data::Text(ref text) => Some(&text),
_ => None,
}
}
pub fn as_comment(&self) -> Option<&str> {
match *self.data() {
Data::Comment(ref comment) => Some(&comment),
_ => None,
}
}
pub fn children(&self) -> Selection<'a> {
Selection::new(self.document,
match *self.data() {
Data::Element(_, _, ref children) => children.iter().cloned().collect(),
_ => [].iter().cloned().collect(),
})
}
}
impl<'a> serialize::Serializable for Node<'a> {
fn serialize<'w, W: io::Write>(&self,
serializer: &mut serialize::Serializer<'w, W>,
traversal_scope: serialize::TraversalScope)
-> io::Result<()> {
match *self.data() {
Data::Text(ref text) => serializer.write_text(&text),
Data::Element(ref name, ref attrs, ref children) => {
let ns = Namespace("".into());
let name = QualName::new(ns.clone(), name.clone());
// FIXME: I couldn't get this to work without this awful hack.
let attrs = attrs.iter()
.map(|&(ref name, ref value)| {
(QualName::new(ns.clone(), name.clone()), value.as_ref())
})
.collect::<Vec<(QualName, &str)>>();
let attrs = attrs.iter().map(|&(ref name, ref value)| (name, *value));
try!(serializer.start_elem(name.clone(), attrs));
for &child in children {
let child = self.document.nth(child).unwrap();
try!(serialize::Serializable::serialize(&child, serializer, traversal_scope));
}
try!(serializer.end_elem(name.clone()));
Ok(())
}
Data::Comment(ref comment) => serializer.write_comment(&comment),
}
}
}