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
use tokenizer::{Attribute, Tokenizer, TokenizerOpts};
use tree_builder::{TreeBuilderOpts, TreeBuilder, TreeSink};
use std::borrow::Cow;
use std::mem;
use encoding::{self, EncodingRef};
use string_cache::QualName;
use tendril;
use tendril::{StrTendril, ByteTendril};
use tendril::stream::{TendrilSink, Utf8LossyDecoder, LossyDecoder};
#[derive(Clone, Default)]
pub struct ParseOpts {
pub tokenizer: TokenizerOpts,
pub tree_builder: TreeBuilderOpts,
}
pub fn parse_document<Sink>(sink: Sink, opts: ParseOpts) -> Parser<Sink> where Sink: TreeSink {
let tb = TreeBuilder::new(sink, opts.tree_builder);
let tok = Tokenizer::new(tb, opts.tokenizer);
Parser { tokenizer: tok }
}
pub fn parse_fragment<Sink>(mut sink: Sink, opts: ParseOpts,
context_name: QualName, context_attrs: Vec<Attribute>)
-> Parser<Sink>
where Sink: TreeSink {
let context_elem = sink.create_element(context_name, context_attrs);
parse_fragment_for_element(sink, opts, context_elem, None)
}
pub fn parse_fragment_for_element<Sink>(sink: Sink, opts: ParseOpts,
context_element: Sink::Handle,
form_element: Option<Sink::Handle>)
-> Parser<Sink>
where Sink: TreeSink {
let tb = TreeBuilder::new_for_fragment(sink, context_element, form_element, opts.tree_builder);
let tok_opts = TokenizerOpts {
initial_state: Some(tb.tokenizer_state_for_context_elem()),
.. opts.tokenizer
};
let tok = Tokenizer::new(tb, tok_opts);
Parser { tokenizer: tok }
}
pub struct Parser<Sink> where Sink: TreeSink {
pub tokenizer: Tokenizer<TreeBuilder<Sink::Handle, Sink>>,
}
impl<Sink: TreeSink> TendrilSink<tendril::fmt::UTF8> for Parser<Sink> {
fn process(&mut self, t: StrTendril) {
self.tokenizer.feed(t)
}
fn error(&mut self, desc: Cow<'static, str>) {
self.tokenizer.sink_mut().sink_mut().parse_error(desc)
}
type Output = Sink::Output;
fn finish(mut self) -> Self::Output {
self.tokenizer.end();
self.tokenizer.unwrap().unwrap().finish()
}
}
impl<Sink: TreeSink> Parser<Sink> {
pub fn from_utf8(self) -> Utf8LossyDecoder<Self> {
Utf8LossyDecoder::new(self)
}
pub fn from_bytes(self, opts: BytesOpts) -> BytesParser<Sink> {
BytesParser {
state: BytesParserState::Initial { parser: self },
opts: opts,
}
}
}
#[derive(Clone, Default)]
pub struct BytesOpts {
pub transport_layer_encoding: Option<EncodingRef>,
}
pub struct BytesParser<Sink> where Sink: TreeSink {
state: BytesParserState<Sink>,
opts: BytesOpts,
}
enum BytesParserState<Sink> where Sink: TreeSink {
Initial {
parser: Parser<Sink>,
},
Buffering {
parser: Parser<Sink>,
buffer: ByteTendril
},
Parsing {
decoder: LossyDecoder<Parser<Sink>>,
},
Transient
}
impl<Sink: TreeSink> BytesParser<Sink> {
pub fn str_parser(&self) -> &Parser<Sink> {
match self.state {
BytesParserState::Initial { ref parser } => parser,
BytesParserState::Buffering { ref parser, .. } => parser,
BytesParserState::Parsing { ref decoder } => decoder.inner_sink(),
BytesParserState::Transient => unreachable!(),
}
}
pub fn str_parser_mut(&mut self) -> &mut Parser<Sink> {
match self.state {
BytesParserState::Initial { ref mut parser } => parser,
BytesParserState::Buffering { ref mut parser, .. } => parser,
BytesParserState::Parsing { ref mut decoder } => decoder.inner_sink_mut(),
BytesParserState::Transient => unreachable!(),
}
}
pub fn process_unicode(&mut self, t: StrTendril) {
if t.is_empty() {
return
}
if let BytesParserState::Parsing { ref mut decoder } = self.state {
decoder.inner_sink_mut().process(t)
} else {
match mem::replace(&mut self.state, BytesParserState::Transient) {
BytesParserState::Initial { mut parser } => {
parser.process(t);
self.start_parsing(parser, ByteTendril::new())
}
BytesParserState::Buffering { parser, buffer } => {
self.start_parsing(parser, buffer);
if let BytesParserState::Parsing { ref mut decoder } = self.state {
decoder.inner_sink_mut().process(t)
} else {
unreachable!()
}
}
BytesParserState::Parsing { .. } | BytesParserState::Transient => unreachable!(),
}
}
}
fn start_parsing(&mut self, parser: Parser<Sink>, buffer: ByteTendril) {
let encoding = detect_encoding(&buffer, &self.opts);
let mut decoder = LossyDecoder::new(encoding, parser);
decoder.process(buffer);
self.state = BytesParserState::Parsing { decoder: decoder }
}
}
impl<Sink: TreeSink> TendrilSink<tendril::fmt::Bytes> for BytesParser<Sink> {
fn process(&mut self, t: ByteTendril) {
if let &mut BytesParserState::Parsing { ref mut decoder } = &mut self.state {
return decoder.process(t)
}
let (parser, buffer) = match mem::replace(&mut self.state, BytesParserState::Transient) {
BytesParserState::Initial{ parser } => (parser, t),
BytesParserState::Buffering { parser, mut buffer } => {
buffer.push_tendril(&t);
(parser, buffer)
}
BytesParserState::Parsing { .. } | BytesParserState::Transient => unreachable!(),
};
if buffer.len32() >= PRESCAN_BYTES {
self.start_parsing(parser, buffer)
} else {
self.state = BytesParserState::Buffering {
parser: parser,
buffer: buffer,
}
}
}
fn error(&mut self, desc: Cow<'static, str>) {
match self.state {
BytesParserState::Initial { ref mut parser } => parser.error(desc),
BytesParserState::Buffering { ref mut parser, .. } => parser.error(desc),
BytesParserState::Parsing { ref mut decoder } => decoder.error(desc),
BytesParserState::Transient => unreachable!(),
}
}
type Output = Sink::Output;
fn finish(self) -> Self::Output {
match self.state {
BytesParserState::Initial { parser } => parser.finish(),
BytesParserState::Buffering { parser, buffer } => {
let encoding = detect_encoding(&buffer, &self.opts);
let mut decoder = LossyDecoder::new(encoding, parser);
decoder.process(buffer);
decoder.finish()
},
BytesParserState::Parsing { decoder } => decoder.finish(),
BytesParserState::Transient => unreachable!(),
}
}
}
const PRESCAN_BYTES: u32 = 3;
fn detect_encoding(bytes: &ByteTendril, opts: &BytesOpts) -> EncodingRef {
if bytes.starts_with(b"\xEF\xBB\xBF") {
return encoding::all::UTF_8
}
if bytes.starts_with(b"\xFE\xFF") {
return encoding::all::UTF_16BE
}
if bytes.starts_with(b"\xFF\xFE") {
return encoding::all::UTF_16LE
}
if let Some(encoding) = opts.transport_layer_encoding {
return encoding
}
return encoding::all::UTF_8
}
#[cfg(test)]
mod tests {
use rcdom::RcDom;
use serialize::serialize;
use std::iter::repeat;
use tendril::TendrilSink;
use super::*;
#[test]
fn from_utf8() {
assert_serialization(
parse_document(RcDom::default(), ParseOpts::default())
.from_utf8()
.one("<title>Test".as_bytes()));
}
#[test]
fn from_bytes_one() {
assert_serialization(
parse_document(RcDom::default(), ParseOpts::default())
.from_bytes(BytesOpts::default())
.one("<title>Test".as_bytes()));
}
#[test]
fn from_bytes_iter() {
assert_serialization(
parse_document(RcDom::default(), ParseOpts::default())
.from_bytes(BytesOpts::default())
.from_iter([
"<title>Test".as_bytes(),
repeat(' ').take(1200).collect::<String>().as_bytes(),
].iter().cloned()));
}
fn assert_serialization(dom: RcDom) {
let mut serialized = Vec::new();
serialize(&mut serialized, &dom.document, Default::default()).unwrap();
assert_eq!(String::from_utf8(serialized).unwrap().replace(" ", ""),
"<html><head><title>Test</title></head><body></body></html>");
}
}