script/dom/servoparser/encoding.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::Cow;
6use std::mem;
7use std::time::{Duration, Instant};
8
9use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1252, X_USER_DEFINED};
10use tendril::fmt::UTF8;
11use tendril::stream::LossyDecoder;
12use tendril::{ByteTendril, StrTendril, TendrilSink};
13
14use crate::dom::document::Document;
15
16#[derive(JSTraceable, MallocSizeOf)]
17pub(super) struct DetectingState {
18 /// The `charset` that was specified in the `Content-Type` header, if any.
19 #[no_trace]
20 encoding_hint_from_content_type: Option<&'static Encoding>,
21 /// The encoding of a same-origin container document, if this document is in an
22 /// `<iframe>`.
23 #[no_trace]
24 encoding_of_container_document: Option<&'static Encoding>,
25 start_timestamp: Instant,
26 attempted_bom_sniffing: bool,
27 buffered_bytes: Vec<u8>,
28}
29
30#[derive(JSTraceable, MallocSizeOf)]
31pub(super) struct DecodingState {
32 /// The actual decoder.
33 ///
34 /// This field is `None` after we've finished parsing, because `LossyDecoder::finish`
35 /// takes ownership of the decoder.
36 #[ignore_malloc_size_of = "Defined in tendril"]
37 #[no_trace]
38 decoder: Option<LossyDecoder<NetworkSink>>,
39 #[no_trace]
40 pub(super) encoding: &'static Encoding,
41}
42
43#[derive(JSTraceable, MallocSizeOf)]
44pub(super) enum NetworkDecoderState {
45 /// In this stage the decoder is buffering bytes until it has enough to determine the encoding.
46 Detecting(DetectingState),
47 Decoding(DecodingState),
48}
49
50impl DetectingState {
51 /// The maximum amount of bytes to buffer before attempting to determine the encoding
52 const BUFFER_THRESHOLD: usize = 1024;
53
54 /// The time threshold after which we will attempt to determine the encoding and start decoding,
55 /// even if there are less than [BUFFER_THRESHOLD] bytes in the buffer.
56 const MAX_TIME_TO_BUFFER: Duration = Duration::from_secs(1);
57
58 /// Appends some data to the internal buffer and attempts to [determine the character encoding].
59 ///
60 /// If an encoding was detected then it is returned. A return value of `None` indicates that
61 /// more bytes are required.
62 ///
63 /// [determine the character encoding]: https://html.spec.whatwg.org/multipage/#determining-the-character-encoding
64 fn buffer(
65 &mut self,
66 data: &[u8],
67 document: &Document,
68 is_at_end_of_file: AtEndOfFile,
69 ) -> Option<&'static Encoding> {
70 self.buffered_bytes.extend_from_slice(data);
71 let can_wait_longer = self.start_timestamp.elapsed() < Self::MAX_TIME_TO_BUFFER;
72 self.determine_the_character_encoding(document, can_wait_longer, is_at_end_of_file)
73 }
74
75 /// <https://html.spec.whatwg.org/multipage/#determining-the-character-encoding>
76 fn determine_the_character_encoding(
77 &mut self,
78 document: &Document,
79 potentially_wait_for_more_data: bool,
80 is_at_end_of_file: AtEndOfFile,
81 ) -> Option<&'static Encoding> {
82 // Step 1. If the result of BOM sniffing is an encoding, return that encoding with confidence certain.
83 if !self.attempted_bom_sniffing && self.buffered_bytes.len() > 2 {
84 self.attempted_bom_sniffing = true;
85
86 if let Some((encoding, _)) = Encoding::for_bom(self.buffered_bytes.as_slice()) {
87 log::debug!(
88 "Determined that the document is {} via BOM-sniffing",
89 encoding.name()
90 );
91 return Some(encoding);
92 }
93 }
94
95 // Step 2. If the user has explicitly instructed the user agent to override the document's character
96 // encoding with a specific encoding, optionally return that encoding with the confidence certain.
97 // NOTE: Our users have no way to do that.
98
99 // Step 3. The user agent may wait for more bytes of the resource to be available, either in this
100 // step or at any later step in this algorithm.
101 if potentially_wait_for_more_data && self.buffered_bytes.len() < Self::BUFFER_THRESHOLD {
102 return None;
103 }
104
105 // TODO: Step 4. If the transport layer specifies a character encoding, and it is supported, return that
106 // encoding with the confidence certain.
107 if let Some(encoding_hint_from_content_type) = self.encoding_hint_from_content_type {
108 log::debug!(
109 "Inferred encoding to be {} from the Content-Type header",
110 encoding_hint_from_content_type.name()
111 );
112 return Some(encoding_hint_from_content_type);
113 }
114
115 // Step 5. Optionally, prescan the byte stream to determine its encoding, with the end condition
116 // being when the user agent decides that scanning further bytes would not be efficient.
117 // NOTE: According to the spec, we should always try to get an xml encoding right after failing
118 // to prescan the byte stream
119 let bytes_to_prescan =
120 &self.buffered_bytes[..Self::BUFFER_THRESHOLD.min(self.buffered_bytes.len())];
121 let sniffed_encoding = if document.is_html_document() {
122 prescan_the_byte_stream_to_determine_the_encoding(bytes_to_prescan)
123 .or_else(|| get_xml_encoding(bytes_to_prescan))
124 } else {
125 get_xml_encoding(bytes_to_prescan)
126 };
127 if let Some(encoding) = sniffed_encoding {
128 log::debug!(
129 "Prescanning the byte stream determined that the encoding is {}",
130 encoding.name()
131 );
132 return Some(encoding);
133 }
134
135 if document.is_html_document() {
136 // Step 6. If the HTML parser for which this algorithm is being run is associated with a Document d
137 // whose container document is non-null, then:
138 // Step 6.1 Let parentDocument be d's container document.
139 // Step 6.2 If parentDocument's origin is same origin with d's origin and parentDocument's character encoding
140 // is not UTF-16BE/LE, then return parentDocument's character encoding, with the confidence tentative.
141 // NOTE: This should not happen for XML documents
142 if let Some(encoding) = self.encoding_of_container_document {
143 if encoding != UTF_16LE && encoding != UTF_16BE {
144 log::debug!(
145 "Inferred encoding to be that of the container document, which is {}",
146 encoding.name()
147 );
148 return Some(encoding);
149 }
150 }
151
152 // Step 7. Otherwise, if the user agent has information on the likely encoding for this page, e.g.
153 // based on the encoding of the page when it was last visited, then return that encoding,
154 // with the confidence tentative.
155 // NOTE: We have no such information.
156
157 // Step 8. The user agent may attempt to autodetect the character encoding from applying frequency analysis
158 // or other algorithms to the data stream.
159 let mut encoding_detector = chardetng::EncodingDetector::new();
160 encoding_detector.feed(&self.buffered_bytes, is_at_end_of_file == AtEndOfFile::Yes);
161 let url = document.url();
162 let tld = url
163 .as_url()
164 .domain()
165 .and_then(|domain| domain.rsplit('.').next())
166 .map(|tld| tld.as_bytes());
167 let (guessed_encoding, is_probably_right) = encoding_detector.guess_assess(tld, true);
168 if is_probably_right {
169 log::debug!(
170 "chardetng determined that the document encoding is {}",
171 guessed_encoding.name()
172 );
173 return Some(guessed_encoding);
174 }
175 }
176
177 // Step 9. Otherwise, return an implementation-defined or user-specified default character encoding,
178 // with the confidence tentative.
179 // TODO: The spec has a cool table here for determining an appropriate fallback encoding based on the
180 // user locale. Use it!
181 log::debug!("Failed to determine encoding of byte stream, falling back to UTF-8");
182 Some(UTF_8)
183 }
184
185 fn finish(&mut self, document: &Document) -> &'static Encoding {
186 self.determine_the_character_encoding(document, false, AtEndOfFile::Yes)
187 .expect("Should always return character encoding when we're not allowed to wait")
188 }
189}
190
191impl NetworkDecoderState {
192 pub(super) fn new(
193 encoding_hint_from_content_type: Option<&'static Encoding>,
194 encoding_of_container_document: Option<&'static Encoding>,
195 ) -> Self {
196 Self::Detecting(DetectingState {
197 encoding_hint_from_content_type,
198 encoding_of_container_document,
199 start_timestamp: Instant::now(),
200 attempted_bom_sniffing: false,
201 buffered_bytes: vec![],
202 })
203 }
204
205 /// Feeds the network decoder a chunk of bytes.
206 ///
207 /// If a new encoding is detected, then the encoding of `document` is updated appropriately.
208 ///
209 /// The decoded bytes are returned to the caller. Note that there is not necessarily a 1:1
210 /// relation between `chunk` and the return value. In the beginning, the decoder will buffer
211 /// bytes and return `None`, then later it will flush them and return a large `StrTendril` all
212 /// at once.
213 pub(super) fn push(&mut self, chunk: &[u8], document: &Document) -> Option<StrTendril> {
214 match self {
215 Self::Detecting(encoding_detector) => {
216 if let Some(encoding) = encoding_detector.buffer(chunk, document, AtEndOfFile::No) {
217 document.set_encoding(encoding);
218 let buffered_bytes = mem::take(&mut encoding_detector.buffered_bytes);
219 *self = Self::Decoding(DecodingState {
220 decoder: Some(LossyDecoder::new_encoding_rs(
221 encoding,
222 NetworkSink::default(),
223 )),
224 encoding,
225 });
226 return self.push(&buffered_bytes, document);
227 }
228
229 None
230 },
231 Self::Decoding(network_decoder) => {
232 let decoder = network_decoder
233 .decoder
234 .as_mut()
235 .expect("Can't push after call to finish()");
236 decoder.process(ByteTendril::from(chunk));
237 Some(std::mem::take(&mut decoder.inner_sink_mut().output))
238 },
239 }
240 }
241
242 pub(super) fn finish(&mut self, document: &Document) -> StrTendril {
243 match self {
244 Self::Detecting(encoding_detector) => {
245 let encoding = encoding_detector.finish(document);
246 document.set_encoding(encoding);
247 let buffered_bytes = mem::take(&mut encoding_detector.buffered_bytes);
248 let mut decoder = LossyDecoder::new_encoding_rs(encoding, NetworkSink::default());
249 decoder.process(ByteTendril::from(&*buffered_bytes));
250 *self = Self::Decoding(DecodingState {
251 // Important to set `None` here to indicate that we're done decoding
252 decoder: None,
253 encoding,
254 });
255 let mut chunk = std::mem::take(&mut decoder.inner_sink_mut().output);
256 chunk.push_tendril(&decoder.finish());
257 chunk
258 },
259 Self::Decoding(network_decoder) => network_decoder
260 .decoder
261 .take()
262 .map(|decoder| decoder.finish())
263 .unwrap_or_default(),
264 }
265 }
266
267 pub(super) fn is_finished(&self) -> bool {
268 match self {
269 Self::Detecting(_) => false,
270 Self::Decoding(network_decoder) => network_decoder.decoder.is_none(),
271 }
272 }
273
274 pub(super) fn decoder(&mut self) -> &mut DecodingState {
275 match self {
276 Self::Detecting(_) => unreachable!("Cannot access decoder before decoding"),
277 Self::Decoding(decoder) => decoder,
278 }
279 }
280}
281
282/// An implementor of `TendrilSink` with the sole purpose of buffering decoded data
283/// so we can take it later.
284#[derive(Default, JSTraceable)]
285pub(crate) struct NetworkSink {
286 #[no_trace]
287 pub(crate) output: StrTendril,
288}
289
290impl TendrilSink<UTF8> for NetworkSink {
291 type Output = StrTendril;
292
293 fn process(&mut self, tendril: StrTendril) {
294 if self.output.is_empty() {
295 self.output = tendril;
296 } else {
297 self.output.push_tendril(&tendril);
298 }
299 }
300
301 fn error(&mut self, _desc: Cow<'static, str>) {}
302
303 fn finish(self) -> Self::Output {
304 self.output
305 }
306}
307
308#[derive(Default)]
309struct Attribute {
310 name: Vec<u8>,
311 value: Vec<u8>,
312}
313
314/// <https://html.spec.whatwg.org/multipage/#prescan-a-byte-stream-to-determine-its-encoding>
315pub fn prescan_the_byte_stream_to_determine_the_encoding(
316 byte_stream: &[u8],
317) -> Option<&'static Encoding> {
318 // Step 1. Let position be a pointer to a byte in the input byte stream,
319 // initially pointing at the first byte.
320 let mut position = 0;
321
322 // Step 2. Prescan for UTF-16 XML declarations: If position points to:
323 match byte_stream {
324 // A sequence of bytes starting with: 0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0
325 // (case-sensitive UTF-16 little-endian '<?x')
326 [0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0, ..] => {
327 // Return UTF-16LE.
328 return Some(UTF_16LE);
329 },
330
331 // A sequence of bytes starting with: 0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78
332 // (case-sensitive UTF-16 big-endian '<?x')
333 [0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78, ..] => {
334 // Return UTF-16BE.
335 return Some(UTF_16BE);
336 },
337 _ => {},
338 }
339
340 loop {
341 // Step 3. Loop: If position points to:
342 let remaining_byte_stream = byte_stream.get(position..)?;
343
344 // A sequence of bytes starting with: 0x3C 0x21 0x2D 0x2D (`<!--`)
345 if remaining_byte_stream.starts_with(b"<!--") {
346 // Advance the position pointer so that it points at the first 0x3E byte which is preceded by two 0x2D bytes
347 // (i.e. at the end of an ASCII '-->' sequence) and comes after the 0x3C byte that was found.
348 // (The two 0x2D bytes can be the same as those in the '<!--' sequence.)
349 // NOTE: This is not very efficient, but likely not an issue...
350 position += remaining_byte_stream
351 .windows(3)
352 .position(|window| window == b"-->")?;
353 }
354 // A sequence of bytes starting with: 0x3C, 0x4D or 0x6D, 0x45 or 0x65, 0x54 or 0x74, 0x41 or 0x61,
355 // and one of 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x2F (case-insensitive ASCII '<meta' followed by a space or slash)
356 else if remaining_byte_stream
357 .get(..b"<meta ".len())
358 .is_some_and(|candidate| {
359 candidate[..b"<meta".len()].eq_ignore_ascii_case(b"<meta") &&
360 candidate.last().is_some_and(|byte| {
361 matches!(byte, 0x09 | 0x0A | 0x0C | 0x0D | 0x20 | 0x2F)
362 })
363 })
364 {
365 // Step 1. Advance the position pointer so that it points at the next 0x09, 0x0A, 0x0C, 0x0D, 0x20,
366 // or 0x2F byte (the one in sequence of characters matched above).
367 position += b"<meta".len();
368
369 // Step 2. Let attribute list be an empty list of strings.
370 // NOTE: This is used to track which attributes we have already seen. As there are only
371 // three attributes that we care about, we instead use three booleans.
372 let mut have_seen_http_equiv_attribute = false;
373 let mut have_seen_content_attribute = false;
374 let mut have_seen_charset_attribute = false;
375
376 // Step 3. Let got pragma be false.
377 let mut got_pragma = false;
378
379 // Step 4. Let need pragma be null.
380 let mut need_pragma = None;
381
382 // Step 5. Let charset be the null value (which, for the purposes of this algorithm,
383 // is distinct from an unrecognized encoding or the empty string).
384 let mut charset = None;
385
386 // Step 6. Attributes: Get an attribute and its value. If no attribute was sniffed,
387 // then jump to the processing step below.
388 while let Some(attribute) = get_an_attribute(byte_stream, &mut position) {
389 // Step 7 If the attribute's name is already in attribute list,
390 // then return to the step labeled attributes.
391 // Step 8. Add the attribute's name to attribute list.
392 // NOTE: This happens in the match arms below
393 // Step 9. Run the appropriate step from the following list, if one applies:
394 match attribute.name.as_slice() {
395 // If the attribute's name is "http-equiv"
396 b"http-equiv" if !have_seen_http_equiv_attribute => {
397 have_seen_http_equiv_attribute = true;
398
399 // If the attribute's value is "content-type", then set got pragma to true.
400 if attribute.value == b"content-type" {
401 got_pragma = true;
402 }
403 },
404 // If the attribute's name is "content"
405 b"content" if !have_seen_content_attribute => {
406 have_seen_content_attribute = true;
407
408 // Apply the algorithm for extracting a character encoding from a meta element,
409 // giving the attribute's value as the string to parse. If a character encoding
410 // is returned, and if charset is still set to null, let charset be the encoding
411 // returned, and set need pragma to true.
412 if charset.is_none() {
413 if let Some(extracted_charset) =
414 extract_a_character_encoding_from_a_meta_element(&attribute.value)
415 {
416 need_pragma = Some(true);
417 charset = Some(extracted_charset);
418 }
419 }
420 },
421 // If the attribute's name is "charset"
422 b"charset" if !have_seen_charset_attribute => {
423 have_seen_charset_attribute = true;
424
425 // Let charset be the result of getting an encoding from the attribute's value,
426 // and set need pragma to false.
427 if let Some(extracted_charset) = Encoding::for_label(&attribute.value) {
428 charset = Some(extracted_charset);
429 }
430
431 need_pragma = Some(false);
432 },
433 _ => {},
434 }
435
436 // Step 10. Return to the step labeled attributes.
437 }
438
439 // Step 11. Processing: If need pragma is null, then jump to the step below labeled next byte.
440 if let Some(need_pragma) = need_pragma {
441 // Step 12. If need pragma is true but got pragma is false,
442 // then jump to the step below labeled next byte.
443 if !need_pragma || got_pragma {
444 // Step 13. If charset is UTF-16BE/LE, then set charset to UTF-8.
445 if charset.is_some_and(|charset| charset == UTF_16BE || charset == UTF_16LE) {
446 charset = Some(UTF_8);
447 }
448 // Step 14. If charset is x-user-defined, then set charset to windows-1252.
449 else if charset.is_some_and(|charset| charset == X_USER_DEFINED) {
450 charset = Some(WINDOWS_1252);
451 }
452
453 // Step 15. Return charset.
454 return charset;
455 }
456 }
457 }
458 // A sequence of bytes starting with a 0x3C byte (<), optionally a 0x2F byte (/),
459 // and finally a byte in the range 0x41-0x5A or 0x61-0x7A (A-Z or a-z)
460 else if *remaining_byte_stream.first()? == b'<' &&
461 remaining_byte_stream
462 .get(1)
463 .filter(|byte| **byte != b'=')
464 .or(remaining_byte_stream.get(2))?
465 .is_ascii_alphabetic()
466 {
467 // Step 1. Advance the position pointer so that it points at the next 0x09 (HT),
468 // 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x3E (>) byte.
469 position += remaining_byte_stream
470 .iter()
471 .position(|byte| byte.is_ascii_whitespace() || *byte == b'>')?;
472
473 // Step 2. Repeatedly get an attribute until no further attributes can be found,
474 // then jump to the step below labeled next byte.
475 while get_an_attribute(byte_stream, &mut position).is_some() {}
476 }
477 // A sequence of bytes starting with: 0x3C 0x21 (`<!`)
478 // A sequence of bytes starting with: 0x3C 0x2F (`</`)
479 // A sequence of bytes starting with: 0x3C 0x3F (`<?`)
480 else if remaining_byte_stream.starts_with(b"<!") ||
481 remaining_byte_stream.starts_with(b"</") ||
482 remaining_byte_stream.starts_with(b"<?")
483 {
484 // Advance the position pointer so that it points at the first 0x3E byte (>) that comes after the 0x3C byte that was found.
485 position += remaining_byte_stream
486 .iter()
487 .position(|byte| *byte == b'>')?;
488 }
489 // Any other byte
490 else {
491 // Do nothing with that byte.
492 }
493
494 // Next byte: Move position so it points at the next byte in the input byte stream,
495 // and return to the step above labeled loop.
496 position += 1;
497 }
498}
499
500/// <https://html.spec.whatwg.org/multipage/#concept-get-attributes-when-sniffing>
501fn get_an_attribute(input: &[u8], position: &mut usize) -> Option<Attribute> {
502 // NOTE: If we reach the end of the input during parsing then we return "None"
503 // (because there obviously is no attribute). The caller will then also run
504 // out of bytes and invoke "get an xml encoding" as mandated by the spec.
505
506 // Step 1. If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR),
507 // 0x20 (SP), or 0x2F (/), then advance position to the next byte and redo this step.
508 *position += &input[*position..]
509 .iter()
510 .position(|b| !matches!(b, 0x09 | 0x0A | 0x0C | 0x0D | 0x20 | 0x2F))?;
511
512 // Step 2. If the byte at position is 0x3E (>), then abort the get an attribute algorithm.
513 // There isn't one.
514 if input[*position] == 0x3E {
515 return None;
516 }
517
518 // Step 3. Otherwise, the byte at position is the start of the attribute name.
519 // Let attribute name and attribute value be the empty string.
520 let mut attribute = Attribute::default();
521 let mut have_spaces = false;
522 loop {
523 // Step 4. Process the byte at position as follows:
524 match *input.get(*position)? {
525 // If it is 0x3D (=), and the attribute name is longer than the empty string
526 b'=' if !attribute.name.is_empty() => {
527 // Advance position to the next byte and jump to the step below labeled value.
528 *position += 1;
529 break;
530 },
531
532 // If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP)
533 0x09 | 0x0A | 0x0C | 0x0D | 0x20 => {
534 // Jump to the step below labeled spaces.
535 have_spaces = true;
536 break;
537 },
538
539 // If it is 0x2F (/) or 0x3E (>)
540 b'/' | b'>' => {
541 // Abort the get an attribute algorithm.
542 // The attribute's name is the value of attribute name, its value is the empty string.
543 return Some(attribute);
544 },
545
546 // If it is in the range 0x41 (A) to 0x5A (Z)
547 byte @ (b'A'..=b'Z') => {
548 // Append the code point b+0x20 to attribute name (where b is the value of the byte at position).
549 // (This converts the input to lowercase.)
550 attribute.name.push(byte + 0x20);
551 },
552
553 // Anything else
554 byte => {
555 // Append the code point with the same value as the byte at position to attribute name.
556 // (It doesn't actually matter how bytes outside the ASCII range are handled here, since only
557 // ASCII bytes can contribute to the detection of a character encoding.)
558 attribute.name.push(byte);
559 },
560 }
561
562 // Step 5. Advance position to the next byte and return to the previous step.
563 *position += 1;
564 }
565
566 if have_spaces {
567 // Step 6. Spaces: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR),
568 // or 0x20 (SP), then advance position to the next byte, then, repeat this step.
569 *position += &input[*position..]
570 .iter()
571 .position(|b| !b.is_ascii_whitespace())?;
572
573 // Step 7. If the byte at position is not 0x3D (=), abort the get an attribute algorithm.
574 // The attribute's name is the value of attribute name, its value is the empty string.
575 if input[*position] != b'=' {
576 return Some(attribute);
577 }
578
579 // Step 8. Advance position past the 0x3D (=) byte.
580 *position += 1;
581 }
582
583 // Step 9. Value: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP),
584 // then advance position to the next byte, then, repeat this step.
585 *position += &input[*position..]
586 .iter()
587 .position(|b| !b.is_ascii_whitespace())?;
588
589 // Step 10. Process the byte at position as follows:
590 match input[*position] {
591 // If it is 0x22 (") or 0x27 (')
592 b @ (b'"' | b'\'') => {
593 // Step 1. Let b be the value of the byte at position.
594 // NOTE: We already have b.
595 loop {
596 // Step 2. Quote loop: Advance position to the next byte.
597 *position += 1;
598
599 // Step 3. If the value of the byte at position is the value of b, then advance position to the next byte
600 // and abort the "get an attribute" algorithm. The attribute's name is the value of attribute name, and
601 // its value is the value of attribute value.
602 let byte_at_position = *input.get(*position)?;
603 if byte_at_position == b {
604 *position += 1;
605 return Some(attribute);
606 }
607 // Step 4. Otherwise, if the value of the byte at position is in the range 0x41 (A) to 0x5A (Z),
608 // then append a code point to attribute value whose value is 0x20 more than the value of the byte
609 // at position.
610 else if byte_at_position.is_ascii_uppercase() {
611 attribute.value.push(byte_at_position + 0x20);
612 }
613 // Step 5. Otherwise, append a code point to attribute value whose value is the same
614 // as the value of the byte at position.
615 else {
616 attribute.value.push(byte_at_position);
617 }
618
619 // Step 6. Return to the step above labeled quote loop.
620 }
621 },
622
623 // If it is 0x3E (>)
624 b'>' => {
625 // Abort the get an attribute algorithm. The attribute's name is the value of attribute name,
626 // its value is the empty string.
627 return Some(attribute);
628 },
629
630 // If it is in the range 0x41 (A) to 0x5A (Z)
631 b @ (b'A'..=b'Z') => {
632 // Append a code point b+0x20 to attribute value (where b is the value of the byte at position).
633 // Advance position to the next byte.
634 attribute.value.push(b + 0x20);
635 *position += 1;
636 },
637
638 // Anything else
639 b => {
640 // Append a code point with the same value as the byte at position to attribute value.
641 // Advance position to the next byte.
642 attribute.value.push(b);
643 *position += 1
644 },
645 }
646
647 loop {
648 // Step 11. Process the byte at position as follows:
649 match *input.get(*position)? {
650 // If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x3E (>)
651 0x09 | 0x0A | 0x0C | 0x0D | 0x20 | 0x3E => {
652 // Abort the get an attribute algorithm. The attribute's name is the value of attribute name and
653 // its value is the value of attribute value.
654 return Some(attribute);
655 },
656
657 // If it is in the range 0x41 (A) to 0x5A (Z)
658 byte if byte.is_ascii_uppercase() => {
659 // Append a code point b+0x20 to attribute value (where b is the value of the byte at position).
660 attribute.value.push(byte + 0x20);
661 },
662
663 // Anything else
664 byte => {
665 // Append a code point with the same value as the byte at position to attribute value.
666 attribute.value.push(byte);
667 },
668 }
669
670 // Step 12. Advance position to the next byte and return to the previous step.
671 *position += 1;
672 }
673}
674
675/// <https://html.spec.whatwg.org/multipage/#algorithm-for-extracting-a-character-encoding-from-a-meta-element>
676fn extract_a_character_encoding_from_a_meta_element(input: &[u8]) -> Option<&'static Encoding> {
677 // Step 1. Let position be a pointer into s, initially pointing at the start of the string.
678 let mut position = 0;
679
680 loop {
681 // Step 2. Loop: Find the first seven characters in s after position that are an ASCII case-insensitive
682 // match for the word "charset". If no such match is found, return nothing.
683 // NOTE: In our case, the attribute value always comes from "get_an_attribute" and is already lowercased.
684 position += input[position..]
685 .windows(7)
686 .position(|window| window == b"charset")? +
687 b"charset".len();
688
689 // Step 3. Skip any ASCII whitespace that immediately follow the word "charset" (there might not be any).
690 position += &input[position..]
691 .iter()
692 .position(|byte| !byte.is_ascii_whitespace())?;
693
694 // Step 4. If the next character is not a U+003D EQUALS SIGN (=), then move position to point just before
695 // that next character, and jump back to the step labeled loop.
696 // NOTE: This is phrased very oddly, because position is already pointing to that character.
697 if *input.get(position)? == b'=' {
698 position += 1;
699 break;
700 }
701 }
702
703 // Step 5. Skip any ASCII whitespace that immediately follow the equals sign (there might not be any).
704 position += &input[position..]
705 .iter()
706 .position(|byte| !byte.is_ascii_whitespace())?;
707
708 // Step 6. Process the next character as follows:
709 let next_character = input.get(position)?;
710
711 // If it is a U+0022 QUOTATION MARK character (") and there is a later U+0022 QUOTATION MARK character (") in s
712 // If it is a U+0027 APOSTROPHE character (') and there is a later U+0027 APOSTROPHE character (') in s
713 if matches!(*next_character, b'"' | b'\'') {
714 // Return the result of getting an encoding from the substring that is between
715 // this character and the next earliest occurrence of this character.
716 let remaining = input.get(position + 1..)?;
717 let end = remaining.iter().position(|byte| byte == next_character)?;
718 Encoding::for_label(&remaining[..end])
719 }
720 // If it is an unmatched U+0022 QUOTATION MARK character (")
721 // If it is an unmatched U+0027 APOSTROPHE character (')
722 // If there is no next character
723 // NOTE: All of these cases are already covered above
724
725 // Otherwise
726 else {
727 // Return the result of getting an encoding from the substring that consists of this character up
728 // to but not including the first ASCII whitespace or U+003B SEMICOLON character (;), or the end of s,
729 // whichever comes first.
730 let remaining = input.get(position..)?;
731 let end = remaining
732 .iter()
733 .position(|byte| byte.is_ascii_whitespace() || *byte == b';')
734 .unwrap_or(remaining.len());
735
736 Encoding::for_label(&remaining[..end])
737 }
738}
739
740/// <https://html.spec.whatwg.org/multipage/#concept-get-xml-encoding-when-sniffing>
741pub fn get_xml_encoding(input: &[u8]) -> Option<&'static Encoding> {
742 // Step 1. Let encodingPosition be a pointer to the start of the stream.
743 // NOTE: We don't need this variable yet.
744 // Step 2. If encodingPosition does not point to the start of a byte sequence 0x3C, 0x3F, 0x78,
745 // 0x6D, 0x6C (`<?xml`), then return failure.
746 if !input.starts_with(b"<?xml") {
747 return None;
748 }
749
750 // Step 3. Let xmlDeclarationEnd be a pointer to the next byte in the input byte stream which is 0x3E (>).
751 // If there is no such byte, then return failure.
752 // NOTE: The spec does not use this variable but the intention is clear.
753 let xml_declaration_end = input.iter().position(|byte| *byte == b'>')?;
754 let input = &input[..xml_declaration_end];
755
756 // Step 4. Set encodingPosition to the position of the first occurrence of the subsequence of bytes 0x65, 0x6E,
757 // 0x63, 0x6F, 0x64, 0x69, 0x6E, 0x67 (`encoding`) at or after the current encodingPosition. If there is no
758 // such sequence, then return failure.
759 let mut encoding_position = input
760 .windows(b"encoding".len())
761 .position(|window| window == b"encoding")?;
762
763 // Step 5. Advance encodingPosition past the 0x67 (g) byte.
764 encoding_position += b"encoding".len();
765
766 // Step 6. While the byte at encodingPosition is less than or equal to 0x20 (i.e., it is either an
767 // ASCII space or control character), advance encodingPosition to the next byte.
768 while *input.get(encoding_position)? <= 0x20 {
769 encoding_position += 1;
770 }
771
772 // Step 7. If the byte at encodingPosition is not 0x3D (=), then return failure.
773 if *input.get(encoding_position)? != b'=' {
774 return None;
775 }
776
777 // Step 8. Advance encodingPosition to the next byte.
778 encoding_position += 1;
779
780 // Step 9. While the byte at encodingPosition is less than or equal to 0x20 (i.e., it is either an
781 // ASCII space or control character), advance encodingPosition to the next byte.
782 while *input.get(encoding_position)? <= 0x20 {
783 encoding_position += 1;
784 }
785
786 // Step 10. Let quoteMark be the byte at encodingPosition.
787 let quote_mark = *input.get(encoding_position)?;
788
789 // Step 11. If quoteMark is not either 0x22 (") or 0x27 ('), then return failure.
790 if !matches!(quote_mark, b'"' | b'\'') {
791 return None;
792 }
793
794 // Step 12. Advance encodingPosition to the next byte.
795 encoding_position += 1;
796
797 // Step 13. Let encodingEndPosition be the position of the next occurrence of quoteMark at or after
798 // encodingPosition. If quoteMark does not occur again, then return failure.
799 let encoding_end_position = input[encoding_position..]
800 .iter()
801 .position(|byte| *byte == quote_mark)?;
802
803 // Step 14. Let potentialEncoding be the sequence of the bytes between encodingPosition
804 // (inclusive) and encodingEndPosition (exclusive).
805 let potential_encoding = &input[encoding_position..][..encoding_end_position];
806
807 // Step 15. If potentialEncoding contains one or more bytes whose byte value is 0x20 or below,
808 // then return failure.
809 if potential_encoding.iter().any(|byte| *byte <= 0x20) {
810 return None;
811 }
812
813 // Step 16. Let encoding be the result of getting an encoding given potentialEncoding isomorphic decoded.
814 let encoding = Encoding::for_label(potential_encoding)?;
815
816 // Step 17. If the encoding is UTF-16BE/LE, then change it to UTF-8.
817 // Step 18. Return encoding.
818 if encoding == UTF_16BE || encoding == UTF_16LE {
819 Some(UTF_8)
820 } else {
821 Some(encoding)
822 }
823}
824
825#[derive(PartialEq)]
826enum AtEndOfFile {
827 Yes,
828 No,
829}