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
use std::{fmt, io};

use html5ever::{serialize, LocalName, QualName};
use html5ever::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(QualName, Vec<(QualName, StrTendril)>),
    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 first_child: Option<usize>,
    pub last_child: Option<usize>,
    pub data: Data,
}

/// A Node.
#[derive(Copy, Clone, 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) -> &'a Raw {
        &self.document.nodes[self.index]
    }

    pub fn data(&self) -> &'a Data {
        &self.raw().data
    }

    pub fn name(&self) -> Option<&'a str> {
        match *self.data() {
            Data::Element(ref name, _) => Some(&name.local),
            _ => None,
        }
    }

    pub fn attr(&self, name: &str) -> Option<&'a str> {
        match *self.data() {
            Data::Element(_, ref attrs) => {
                let name = LocalName::from(name);
                attrs.iter()
                    .find(|&&(ref name_, _)| name == name_.local)
                    .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 first_child(&self) -> Option<Node<'a>> {
        self.raw().first_child.map(|index| self.document.nth(index).unwrap())
    }

    pub fn last_child(&self) -> Option<Node<'a>> {
        self.raw().last_child.map(|index| self.document.nth(index).unwrap())
    }

    pub fn text(&self) -> String {
        let mut string = String::new();
        recur(self, &mut string);
        return string;

        fn recur(node: &Node, string: &mut String) {
            if let Some(text) = node.as_text() {
                string.push_str(text);
            }
            for child in node.children() {
                recur(&child, string)
            }
        }
    }

    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();
        for child in self.children() {
            serialize::serialize(&mut buf, &child, Default::default()).unwrap();
        }
        String::from_utf8(buf).unwrap()
    }

    pub fn find<P: Predicate>(&self, predicate: P) -> Find<'a, P> {
        Find {
            document: self.document,
            descendants: self.descendants(),
            predicate: predicate,
        }
    }

    pub fn is<P: Predicate>(&self, p: P) -> bool {
        p.matches(self)
    }

    pub fn as_text(&self) -> Option<&'a str> {
        match *self.data() {
            Data::Text(ref text) => Some(&text),
            _ => None,
        }
    }

    pub fn as_comment(&self) -> Option<&'a str> {
        match *self.data() {
            Data::Comment(ref comment) => Some(&comment),
            _ => None,
        }
    }

    pub fn children(&self) -> Children<'a> {
        Children {
            document: self.document,
            next: self.first_child(),
        }
    }

    pub fn descendants(&self) -> Descendants<'a> {
        Descendants {
            start: *self,
            current: *self,
            done: false,
        }
    }
}

impl<'a> fmt::Debug for Node<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        struct Attrs<'a>(&'a [(QualName, StrTendril)]);

        impl<'a> fmt::Debug for Attrs<'a> {
            fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                self.0
                    .iter()
                    .fold(f.debug_list(), |mut f, &(ref name, ref value)| {
                        f.entry(&(&*name.local, &&**value));
                        f
                    })
                    .finish()
            }
        }

        struct Children<'a>(&'a Node<'a>);

        impl<'a> fmt::Debug for Children<'a> {
            fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                f.debug_list().entries(self.0.children()).finish()
            }
        }

        match *self.data() {
            Data::Text(ref text) => f.debug_tuple("Text").field(&&**text).finish(),
            Data::Element(ref name, ref attrs) => {
                f.debug_struct("Element")
                    .field("name", &&*name.local)
                    .field("attrs", &Attrs(attrs))
                    .field("children", &Children(self))
                    .finish()
            }
            Data::Comment(ref comment) => f.debug_tuple("Comment").field(&&**comment).finish(),
        }
    }
}

impl<'a> serialize::Serialize for Node<'a> {
    fn serialize<S: serialize::Serializer>(&self,
                                           serializer: &mut S,
                                           traversal_scope: serialize::TraversalScope)
                                           -> io::Result<()> {
        match *self.data() {
            Data::Text(ref text) => serializer.write_text(&text),
            Data::Element(ref name, ref attrs) => {
                let attrs = attrs.iter().map(|&(ref name, ref value)| (name, &**value));

                try!(serializer.start_elem(name.clone(), attrs));

                for child in self.children() {
                    try!(serialize::Serialize::serialize(&child, serializer, traversal_scope));
                }

                try!(serializer.end_elem(name.clone()));

                Ok(())
            }
            Data::Comment(ref comment) => serializer.write_comment(&comment),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Descendants<'a> {
    start: Node<'a>,
    current: Node<'a>,
    done: bool,
}

impl<'a> Iterator for Descendants<'a> {
    type Item = Node<'a>;

    fn next(&mut self) -> Option<Node<'a>> {
        if self.done {
            return None;
        }

        // If this is the start, we can only descdend into children.
        if self.start.index() == self.current.index() {
            if let Some(first_child) = self.current.first_child() {
                self.current = first_child;
            } else {
                self.done = true;
                return None;
            }
        } else {
            // Otherwise we can also go to next sibling.
            if let Some(first_child) = self.current.first_child() {
                self.current = first_child;
            } else if let Some(next) = self.current.next() {
                self.current = next;
            } else {
                loop {
                    // This unwrap should never fail.
                    let parent = self.current.parent().unwrap();
                    if parent.index() == self.start.index() {
                        self.done = true;
                        return None;
                    }
                    if let Some(next) = parent.next() {
                        self.current = next;
                        break;
                    }
                    self.current = parent;
                }
            }
        }

        Some(self.current)
    }
}

pub struct Find<'a, P: Predicate> {
    document: &'a Document,
    descendants: Descendants<'a>,
    predicate: P,
}

impl<'a, P: Predicate> Find<'a, P> {
    pub fn into_selection(self) -> Selection<'a> {
        Selection::new(self.document, self.map(|node| node.index()).collect())
    }
}

impl<'a, P: Predicate> Iterator for Find<'a, P> {
    type Item = Node<'a>;

    fn next(&mut self) -> Option<Node<'a>> {
        for node in &mut self.descendants {
            if self.predicate.matches(&node) {
                return Some(node);
            }
        }
        None
    }
}

pub struct Children<'a> {
    document: &'a Document,
    next: Option<Node<'a>>,
}

impl<'a> Children<'a> {
    pub fn into_selection(self) -> Selection<'a> {
        Selection::new(self.document, self.map(|node| node.index()).collect())
    }
}

impl<'a> Iterator for Children<'a> {
    type Item = Node<'a>;

    fn next(&mut self) -> Option<Node<'a>> {
        if let Some(next) = self.next {
            self.next = next.next();
            Some(next)
        } else {
            None
        }
    }
}