Debian Codegraph @

src/document.rs

raw symbols SCIP
1 use html5ever::tendril::{ByteTendril, ReadExt, StrTendril};
2
3 use crate::node::{self, Node};
4 use crate::predicate::Predicate;
5 use crate::selection::Selection;
6
7 use std::io;
8
9 /// An HTML document.
10 #[derive(Clone, Debug, PartialEq, Eq)]
11 pub struct Document {
12 pub nodes: Vec<node::Raw>,
13 }
14
15 impl Document {
16 /// Returns a `Selection` containing nodes passing the given predicate `p`.
17 pub fn find<P: Predicate>(&self, predicate: P) -> Find<P> {
18 Find {
19 document: self,
20 next: 0,
21 predicate,
22 }
23 }
24
25 /// Returns the `n`th node of the document as a `Some(Node)`, indexed from
26 /// 0, or `None` if n is greater than or equal to the number of nodes.
27 pub fn nth(&self, n: usize) -> Option<Node> {
28 Node::new(self, n)
29 }
30
31 pub fn from_read<R: io::Read>(mut readable: R) -> io::Result<Document> {
32 let mut byte_tendril = ByteTendril::new();
33 readable.read_to_tendril(&mut byte_tendril)?;
34
35 match byte_tendril.try_reinterpret() {
36 Ok(str_tendril) => Ok(Document::from(str_tendril)),
37 Err(_) => Err(io::Error::new(
38 io::ErrorKind::InvalidData,
39 "stream did not contain valid UTF-8",
40 )),
41 }
42 }
43 }
44
45 impl From<StrTendril> for Document {
46 /// Parses the given `StrTendril` into a `Document`.
47 fn from(tendril: StrTendril) -> Document {
48 use html5ever::parse_document;
49 use html5ever::tendril::stream::TendrilSink;
50 use markup5ever_rcdom::{Handle, NodeData, RcDom};
51
52 let mut document = Document { nodes: vec![] };
53
54 let rc_dom = parse_document(RcDom::default(), Default::default()).one(tendril);
55 recur(&mut document, &rc_dom.document, None, None);
56 return document;
57
58 fn recur(
59 document: &mut Document,
60 node: &Handle,
61 parent: Option<usize>,
62 prev: Option<usize>,
63 ) -> Option<usize> {
64 match node.data {
65 NodeData::Document => {
66 let mut prev = None;
67 for child in node.children.borrow().iter() {
68 prev = recur(document, child, None, prev)
69 }
70 None
71 }
72 NodeData::Text { ref contents } => {
73 let data = node::Data::Text(contents.borrow().clone());
74 Some(append(document, data, parent, prev))
75 }
76 NodeData::Comment { ref contents } => {
77 let data = node::Data::Comment(contents.clone());
78 Some(append(document, data, parent, prev))
79 }
80 NodeData::Element {
81 ref name,
82 ref attrs,
83 ..
84 } => {
85 let name = name.clone();
86 let attrs = attrs
87 .borrow()
88 .iter()
89 .map(|attr| (attr.name.clone(), attr.value.clone()))
90 .collect();
91 let data = node::Data::Element(name, attrs);
92 let index = append(document, data, parent, prev);
93 let mut prev = None;
94 for child in node.children.borrow().iter() {
95 prev = recur(document, child, Some(index), prev)
96 }
97 Some(index)
98 }
99 _ => None,
100 }
101 }
102
103 fn append(
104 document: &mut Document,
105 data: node::Data,
106 parent: Option<usize>,
107 prev: Option<usize>,
108 ) -> usize {
109 let index = document.nodes.len();
110
111 document.nodes.push(node::Raw {
112 index,
113 parent,
114 prev,
115 next: None,
116 first_child: None,
117 last_child: None,
118 data,
119 });
120
121 if let Some(parent) = parent {
122 let parent = &mut document.nodes[parent];
123 if parent.first_child.is_none() {
124 parent.first_child = Some(index);
125 }
126 parent.last_child = Some(index);
127 }
128
129 if let Some(prev) = prev {
130 document.nodes[prev].next = Some(index);
131 }
132
133 index
134 }
135 }
136 }
137
138 impl<'a> From<&'a str> for Document {
139 /// Parses the given `&str` into a `Document`.
140 fn from(str: &str) -> Document {
141 Document::from(StrTendril::from(str))
142 }
143 }
144
145 pub struct Find<'a, P> {
146 document: &'a Document,
147 next: usize,
148 predicate: P,
149 }
150
151 impl<'a, P: Predicate> std::fmt::Debug for Find<'a, P> {
152 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 f.debug_struct("Find")
154 .field("document", &self.document)
155 .field("next", &self.next)
156 // predicate may be closure not implementing Debug
157 .finish()
158 }
159 }
160
161 impl<'a, P: Predicate> Find<'a, P> {
162 pub fn into_selection(self) -> Selection<'a> {
163 Selection::new(self.document, self.map(|node| node.index()).collect())
164 }
165 }
166
167 impl<'a, P: Predicate> Iterator for Find<'a, P> {
168 type Item = Node<'a>;
169
170 fn next(&mut self) -> Option<Node<'a>> {
171 while self.next < self.document.nodes.len() {
172 let node = self.document.nth(self.next).unwrap();
173 self.next += 1;
174 if self.predicate.matches(&node) {
175 return Some(node);
176 }
177 }
178 None
179 }
180 }