1use std::borrow::Cow;
15
16use crate::{Error, TextPos};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum Encoding {
22 Utf8,
24 Utf16Le,
26 Utf16Be,
28 UsAscii,
30 Iso8859_1,
32 Iso8859_15,
34 Windows1252,
37}
38
39impl Encoding {
40 #[must_use]
42 pub const fn name(self) -> &'static str {
43 match self {
44 Self::Utf8 => "UTF-8",
45 Self::Utf16Le => "UTF-16LE",
46 Self::Utf16Be => "UTF-16BE",
47 Self::UsAscii => "US-ASCII",
48 Self::Iso8859_1 => "ISO-8859-1",
49 Self::Iso8859_15 => "ISO-8859-15",
50 Self::Windows1252 => "windows-1252",
51 }
52 }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57enum Named {
58 Is(Encoding),
60 Utf16,
62 Invalid,
64 Other,
66}
67
68const NAMES: &[(&str, Named)] = &[
71 ("UTF-8", Named::Is(Encoding::Utf8)),
72 ("UTF8", Named::Is(Encoding::Utf8)),
73 ("unicode-1-1-utf-8", Named::Is(Encoding::Utf8)),
74 ("UTF-16", Named::Utf16),
75 ("UTF-16LE", Named::Is(Encoding::Utf16Le)),
76 ("UTF-16BE", Named::Is(Encoding::Utf16Be)),
77 ("US-ASCII", Named::Is(Encoding::UsAscii)),
78 ("ASCII", Named::Is(Encoding::UsAscii)),
79 ("ANSI_X3.4-1968", Named::Is(Encoding::UsAscii)),
80 ("ANSI_X3.4-1986", Named::Is(Encoding::UsAscii)),
81 ("ISO646-US", Named::Is(Encoding::UsAscii)),
82 ("ISO-IR-6", Named::Is(Encoding::UsAscii)),
83 ("CP367", Named::Is(Encoding::UsAscii)),
84 ("IBM367", Named::Is(Encoding::UsAscii)),
85 ("US", Named::Is(Encoding::UsAscii)),
86 ("csASCII", Named::Is(Encoding::UsAscii)),
87 ("ISO-8859-1", Named::Is(Encoding::Iso8859_1)),
88 ("ISO_8859-1", Named::Is(Encoding::Iso8859_1)),
89 ("ISO8859-1", Named::Is(Encoding::Iso8859_1)),
90 ("ISO-IR-100", Named::Is(Encoding::Iso8859_1)),
91 ("latin1", Named::Is(Encoding::Iso8859_1)),
92 ("l1", Named::Is(Encoding::Iso8859_1)),
93 ("CP819", Named::Is(Encoding::Iso8859_1)),
94 ("IBM819", Named::Is(Encoding::Iso8859_1)),
95 ("csISOLatin1", Named::Is(Encoding::Iso8859_1)),
96 ("ISO8859_1", Named::Is(Encoding::Iso8859_1)),
97 ("ISO_8859_1", Named::Is(Encoding::Iso8859_1)),
98 ("ISO-8859-15", Named::Is(Encoding::Iso8859_15)),
99 ("ISO_8859-15", Named::Is(Encoding::Iso8859_15)),
100 ("ISO8859-15", Named::Is(Encoding::Iso8859_15)),
101 ("LATIN-9", Named::Is(Encoding::Iso8859_15)),
102 ("latin9", Named::Is(Encoding::Iso8859_15)),
103 ("csISOLatin9", Named::Is(Encoding::Iso8859_15)),
104 ("L9", Named::Is(Encoding::Iso8859_15)),
105 ("LATIN0", Named::Is(Encoding::Iso8859_15)),
106 ("windows-1252", Named::Is(Encoding::Windows1252)),
107 ("cp1252", Named::Is(Encoding::Windows1252)),
108];
109
110pub fn encoding_names() -> impl Iterator<Item = (&'static str, Option<Encoding>)> {
114 NAMES.iter().map(|&(name, named)| {
115 (
116 name,
117 match named {
118 Named::Is(encoding) => Some(encoding),
119 _ => None,
120 },
121 )
122 })
123}
124
125fn named(name: &str) -> Named {
127 let valid = name.bytes().next().is_some_and(|b| b.is_ascii_alphabetic())
128 && name
129 .bytes()
130 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
131 if !valid {
132 return Named::Invalid;
133 }
134 NAMES
135 .iter()
136 .find(|(n, _)| n.eq_ignore_ascii_case(name))
137 .map_or(Named::Other, |&(_, named)| named)
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142enum Signature {
143 Utf8Bom,
145 Utf16Bom(Encoding),
147 Utf16(Encoding),
149 None,
151}
152
153fn signature(bytes: &[u8]) -> Result<Signature, Error> {
157 let unsupported = |name: &str| Err(Error::UnsupportedEncoding(name.to_owned()));
158 match bytes {
159 [0xEF, 0xBB, 0xBF, ..] => Ok(Signature::Utf8Bom),
160 [0xFE, 0xFF, ..] => Ok(Signature::Utf16Bom(Encoding::Utf16Be)),
161 [0xFF, 0xFE, ..] => Ok(Signature::Utf16Bom(Encoding::Utf16Le)),
162 [0x00, 0x00, 0xFE, 0xFF, ..]
163 | [0x00, 0x00, 0x00, 0x3C, ..]
164 | [0x3C, 0x00, 0x00, 0x00, ..]
165 | [0x00, 0x00, 0x3C, 0x00, ..]
166 | [0x00, 0x3C, 0x00, 0x00, ..] => unsupported("UCS-4"),
167 [0x4C, 0x6F, 0xA7, 0x94, ..] => unsupported("EBCDIC"),
168 [0x3C, 0x00, 0x3F, 0x00, ..] => Ok(Signature::Utf16(Encoding::Utf16Le)),
169 [0x00, 0x3C, 0x00, 0x3F, ..] => Ok(Signature::Utf16(Encoding::Utf16Be)),
170 _ => Ok(Signature::None),
171 }
172}
173
174const fn is_space(b: u8) -> bool {
176 matches!(b, b' ' | b'\t' | b'\r' | b'\n')
177}
178
179fn declared_encoding(text: &[u8]) -> Option<&[u8]> {
185 let rest = text.strip_prefix(b"<?xml")?;
186 let rest = spaces(rest)?;
187 let rest = pseudo_attribute(rest, b"version")?.1;
188 let rest = spaces(rest)?;
189 pseudo_attribute(rest, b"encoding").map(|(value, _)| value)
190}
191
192fn spaces(bytes: &[u8]) -> Option<&[u8]> {
194 let n = bytes.iter().take_while(|&&b| is_space(b)).count();
195 (n > 0).then(|| &bytes[n..])
196}
197
198fn pseudo_attribute<'b>(bytes: &'b [u8], name: &[u8]) -> Option<(&'b [u8], &'b [u8])> {
201 let rest = bytes.strip_prefix(name)?;
202 let rest = &rest[rest.iter().take_while(|&&b| is_space(b)).count()..];
203 let rest = rest.strip_prefix(b"=")?;
204 let rest = &rest[rest.iter().take_while(|&&b| is_space(b)).count()..];
205 let ("e, rest) = rest.split_first()?;
206 if quote != b'"' && quote != b'\'' {
207 return None;
208 }
209 let end = rest.iter().position(|&b| b == quote)?;
210 Some((&rest[..end], &rest[end + 1..]))
211}
212
213fn resolve(bytes: &[u8]) -> Result<(Encoding, usize), Error> {
216 match signature(bytes)? {
217 Signature::Utf16Bom(encoding) => Ok((encoding, 2)),
218 Signature::Utf16(encoding) => Ok((encoding, 0)),
219 Signature::Utf8Bom => Ok((declared(&bytes[3..], "a UTF-8 byte order mark")?, 3)),
220 Signature::None => Ok((declared(bytes, "UTF-8 (no byte order mark)")?, 0)),
221 }
222}
223
224fn declared(bytes: &[u8], found: &'static str) -> Result<Encoding, Error> {
228 let Some(name) = declared_encoding(bytes) else {
229 return Ok(Encoding::Utf8);
230 };
231 let name = String::from_utf8_lossy(name);
232 match named(&name) {
233 Named::Is(Encoding::Utf16Le | Encoding::Utf16Be) | Named::Utf16 => {
234 Err(Error::EncodingMismatch {
235 found,
236 declared: name.into_owned(),
237 })
238 }
239 Named::Is(encoding) => Ok(encoding),
240 Named::Invalid => Ok(Encoding::Utf8),
242 Named::Other => Err(Error::UnsupportedEncoding(name.into_owned())),
243 }
244}
245
246fn check_utf16_declaration(text: &str, encoding: Encoding, bom: bool) -> Result<(), Error> {
249 let Some(name) = declared_encoding(text.as_bytes()) else {
250 return Ok(());
251 };
252 let name = String::from_utf8_lossy(name);
254 match named(&name) {
255 Named::Utf16 | Named::Invalid => Ok(()),
256 Named::Is(declared) if declared == encoding => Ok(()),
257 Named::Other => Err(Error::UnsupportedEncoding(name.into_owned())),
258 Named::Is(_) => Err(Error::EncodingMismatch {
259 found: match (bom, encoding) {
260 (true, Encoding::Utf16Le) => "a UTF-16LE byte order mark",
261 (true, _) => "a UTF-16BE byte order mark",
262 (false, Encoding::Utf16Le) => "UTF-16LE (from the first bytes)",
263 (false, _) => "UTF-16BE (from the first bytes)",
264 },
265 declared: name.into_owned(),
266 }),
267 }
268}
269
270pub fn decode(bytes: &[u8]) -> Result<Cow<'_, str>, Error> {
294 let (encoding, start) = resolve(bytes)?;
295 let rest = &bytes[start..];
296 let text = match encoding {
297 Encoding::Utf8 => Cow::Borrowed(utf8(rest)?),
298 _ => Cow::Owned(decode_other(rest, encoding, start > 0)?),
299 };
300 no_second_bom(&text)?;
301 Ok(text)
302}
303
304pub fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
311 let (encoding, start) = resolve(&bytes)?;
312 let text = if encoding == Encoding::Utf8 {
313 bytes.drain(..start);
314 String::from_utf8(bytes).map_err(|e| {
315 let valid = &e.as_bytes()[..e.utf8_error().valid_up_to()];
316 invalid(Encoding::Utf8, &String::from_utf8_lossy(valid))
318 })?
319 } else {
320 decode_other(&bytes[start..], encoding, start > 0)?
321 };
322 no_second_bom(&text)?;
323 Ok(text)
324}
325
326pub fn encoding_of(bytes: &[u8]) -> Result<Encoding, Error> {
335 resolve(bytes).map(|(encoding, _)| encoding)
336}
337
338fn utf8(bytes: &[u8]) -> Result<&str, Error> {
340 std::str::from_utf8(bytes).map_err(|e| {
341 let valid = &bytes[..e.valid_up_to()];
342 invalid(Encoding::Utf8, &String::from_utf8_lossy(valid))
344 })
345}
346
347fn invalid(encoding: Encoding, before: &str) -> Error {
349 Error::InvalidEncodedBytes {
350 encoding: encoding.name(),
351 pos: TextPos::at(before, before.len()),
352 }
353}
354
355fn no_second_bom(text: &str) -> Result<(), Error> {
357 if text.starts_with('\u{FEFF}') {
358 return Err(Error::UnknownToken(TextPos::new(1, 1)));
359 }
360 Ok(())
361}
362
363fn decode_other(bytes: &[u8], encoding: Encoding, bom: bool) -> Result<String, Error> {
365 let single: fn(u8) -> Option<char> = match encoding {
366 Encoding::Utf16Le | Encoding::Utf16Be => {
367 let text = utf16(bytes, encoding)?;
368 check_utf16_declaration(&text, encoding, bom)?;
369 return Ok(text);
370 }
371 Encoding::Utf8 => return utf8(bytes).map(str::to_owned),
372 Encoding::UsAscii => |b| b.is_ascii().then_some(char::from(b)),
373 Encoding::Iso8859_1 => |b| Some(char::from(b)),
374 Encoding::Iso8859_15 => |b| Some(iso_8859_15(b)),
375 Encoding::Windows1252 => windows_1252,
376 };
377 let mut text = String::with_capacity(bytes.len() + bytes.len() / 2);
379 for &b in bytes {
380 match single(b) {
381 Some(c) => text.push(c),
382 None => return Err(invalid(encoding, &text)),
383 }
384 }
385 Ok(text)
386}
387
388fn utf16(bytes: &[u8], encoding: Encoding) -> Result<String, Error> {
391 let (pairs, odd) = bytes.as_chunks::<2>();
392 let unit = |pair: &[u8; 2]| {
393 if encoding == Encoding::Utf16Le {
394 u16::from_le_bytes(*pair)
395 } else {
396 u16::from_be_bytes(*pair)
397 }
398 };
399 let mut text = String::with_capacity(bytes.len() + bytes.len() / 2);
400 for c in char::decode_utf16(pairs.iter().map(unit)) {
401 match c {
402 Ok(c) => text.push(c),
403 Err(_) => return Err(invalid(encoding, &text)),
404 }
405 }
406 if !odd.is_empty() {
407 return Err(invalid(encoding, &text));
408 }
409 Ok(text)
410}
411
412fn iso_8859_15(b: u8) -> char {
414 match b {
415 0xA4 => '\u{20AC}',
416 0xA6 => '\u{0160}',
417 0xA8 => '\u{0161}',
418 0xB4 => '\u{017D}',
419 0xB8 => '\u{017E}',
420 0xBC => '\u{0152}',
421 0xBD => '\u{0153}',
422 0xBE => '\u{0178}',
423 _ => char::from(b),
424 }
425}
426
427const WINDOWS_1252_80: [Option<char>; 32] = [
430 Some('\u{20AC}'),
431 None,
432 Some('\u{201A}'),
433 Some('\u{0192}'),
434 Some('\u{201E}'),
435 Some('\u{2026}'),
436 Some('\u{2020}'),
437 Some('\u{2021}'),
438 Some('\u{02C6}'),
439 Some('\u{2030}'),
440 Some('\u{0160}'),
441 Some('\u{2039}'),
442 Some('\u{0152}'),
443 None,
444 Some('\u{017D}'),
445 None,
446 None,
447 Some('\u{2018}'),
448 Some('\u{2019}'),
449 Some('\u{201C}'),
450 Some('\u{201D}'),
451 Some('\u{2022}'),
452 Some('\u{2013}'),
453 Some('\u{2014}'),
454 Some('\u{02DC}'),
455 Some('\u{2122}'),
456 Some('\u{0161}'),
457 Some('\u{203A}'),
458 Some('\u{0153}'),
459 None,
460 Some('\u{017E}'),
461 Some('\u{0178}'),
462];
463
464fn windows_1252(b: u8) -> Option<char> {
466 match b {
467 0x80..=0x9F => WINDOWS_1252_80[usize::from(b - 0x80)],
468 _ => Some(char::from(b)),
469 }
470}
471
472#[cfg(test)]
473mod tests {
474 use super::*;
475
476 fn utf16le(text: &str) -> Vec<u8> {
477 text.encode_utf16().flat_map(u16::to_le_bytes).collect()
478 }
479
480 fn utf16be(text: &str) -> Vec<u8> {
481 text.encode_utf16().flat_map(u16::to_be_bytes).collect()
482 }
483
484 #[test]
485 fn utf8_is_borrowed() {
486 assert!(matches!(decode(b"<a/>").unwrap(), Cow::Borrowed("<a/>")));
487 assert!(matches!(
488 decode(b"\xEF\xBB\xBF<a>\xC3\xA9</a>").unwrap(),
489 Cow::Borrowed("<a>\u{e9}</a>")
490 ));
491 let declared = "<?xml version='1.0' encoding='utf8'?><a/>";
492 assert!(matches!(decode(declared.as_bytes()).unwrap(), Cow::Borrowed(t) if t == declared));
493 assert_eq!(decode_owned(b"\xEF\xBB\xBF<a/>".to_vec()).unwrap(), "<a/>");
494 }
495
496 #[test]
497 fn utf16_with_and_without_a_byte_order_mark() {
498 let text = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><a>\u{e9}\u{1F600}</a>";
499 for (bytes, bom) in [
500 ([&[0xFF, 0xFE][..], &utf16le(text)].concat(), true),
501 ([&[0xFE, 0xFF][..], &utf16be(text)].concat(), true),
502 (utf16le(text), false),
503 (utf16be(text), false),
504 ] {
505 assert_eq!(decode(&bytes).unwrap(), text, "{bom}");
506 assert_eq!(decode_owned(bytes).unwrap(), text);
507 }
508 let bytes = [&[0xFF, 0xFE][..], &utf16le("<a/>")].concat();
510 assert_eq!(decode(&bytes).unwrap(), "<a/>");
511 assert_eq!(encoding_of(&bytes).unwrap(), Encoding::Utf16Le);
512 let le = "<?xml version='1.0' encoding='utf-16le'?><a/>";
514 assert_eq!(decode(&utf16le(le)).unwrap(), le);
515 let be = "<?xml version='1.0' encoding='UTF-16BE'?><a/>";
517 assert!(matches!(
518 decode(&utf16le(be)),
519 Err(Error::EncodingMismatch { declared, .. }) if declared == "UTF-16BE"
520 ));
521 let latin = "<?xml version='1.0' encoding='ISO-8859-1'?><a/>";
522 assert!(matches!(
523 decode(&[&[0xFF, 0xFE][..], &utf16le(latin)].concat()),
524 Err(Error::EncodingMismatch { .. })
525 ));
526 for name in ["ISO-10646-UCS-2", "UCS-2"] {
527 let ucs2 = format!("<?xml version='1.0' encoding='{name}'?><a/>");
528 assert_eq!(
529 decode(&[&[0xFE, 0xFF][..], &utf16be(&ucs2)].concat()),
530 Err(Error::UnsupportedEncoding(name.to_owned()))
531 );
532 }
533 }
534
535 #[test]
536 fn malformed_utf16() {
537 let bytes = [&[0xFF, 0xFE][..], &utf16le("<a>\n\u{e9}x")].concat();
538 let mut lone = bytes.clone();
539 lone.extend([0x00, 0xD8, b'<', 0]);
540 assert_eq!(
541 decode(&lone),
542 Err(Error::InvalidEncodedBytes {
543 encoding: "UTF-16LE",
544 pos: TextPos::new(2, 3)
545 })
546 );
547 let mut odd = bytes;
548 odd.push(b'>');
549 assert_eq!(
550 decode(&odd),
551 Err(Error::InvalidEncodedBytes {
552 encoding: "UTF-16LE",
553 pos: TextPos::new(2, 3)
554 })
555 );
556 let low = [&[0xFE, 0xFF][..], &[0xDC, 0x00]].concat();
558 assert!(matches!(
559 decode(&low),
560 Err(Error::InvalidEncodedBytes { pos, .. }) if pos == TextPos::new(1, 1)
561 ));
562 }
563
564 #[test]
565 fn single_byte_encodings() {
566 let decl = |name: &str| format!("<?xml version=\"1.0\" encoding=\"{name}\"?>");
567 let latin1 = [decl("ISO-8859-1").as_bytes(), b"<a>\xE9\x80\xA4</a>"].concat();
568 assert_eq!(
569 decode(&latin1).unwrap(),
570 format!("{}<a>\u{e9}\u{80}\u{a4}</a>", decl("ISO-8859-1"))
571 );
572 for name in ["latin9", "L9", "LATIN0", "csISOLatin9"] {
573 let latin9 = [decl(name).as_bytes(), b"<a>\xA4\xBE\xE9</a>"].concat();
574 assert_eq!(
575 decode(&latin9).unwrap(),
576 format!("{}<a>\u{20AC}\u{178}\u{e9}</a>", decl(name))
577 );
578 }
579 let cp1252 = [decl("Windows-1252").as_bytes(), b"<a>\x80\x9F\xFF</a>"].concat();
580 assert_eq!(
581 decode(&cp1252).unwrap(),
582 format!("{}<a>\u{20AC}\u{178}\u{ff}</a>", decl("Windows-1252"))
583 );
584 for b in [0x81, 0x8D, 0x8F, 0x90, 0x9D] {
585 let bytes = [decl("cp1252").as_bytes(), b"\n<a>x", &[b], b"</a>"].concat();
586 assert_eq!(
587 decode(&bytes),
588 Err(Error::InvalidEncodedBytes {
589 encoding: "windows-1252",
590 pos: TextPos::new(2, 5)
591 })
592 );
593 }
594 let ascii = [decl("US-ASCII").as_bytes(), b"<a>\xE9</a>"].concat();
595 assert!(matches!(
596 decode(&ascii),
597 Err(Error::InvalidEncodedBytes {
598 encoding: "US-ASCII",
599 ..
600 })
601 ));
602 let after_bom = [
604 b"\xEF\xBB\xBF",
605 decl("ISO-8859-1").as_bytes(),
606 b"<a>\xC3\xA9</a>",
607 ]
608 .concat();
609 assert_eq!(
610 decode_owned(after_bom).unwrap(),
611 format!("{}<a>\u{c3}\u{a9}</a>", decl("ISO-8859-1"))
612 );
613 }
614
615 #[test]
616 fn declarations() {
617 assert_eq!(
618 declared_encoding(b"<?xml version='1.0' encoding = \"latin1\" ?><a/>"),
619 Some(&b"latin1"[..])
620 );
621 assert_eq!(
622 declared_encoding(b"<?xml\nversion=\"1.0\"\r\n\tencoding='x'?>"),
623 Some(&b"x"[..])
624 );
625 for text in [
626 &b"<?xml version='1.0'?><a/>"[..],
627 b"<?xml version='1.0' standalone='yes'?>",
628 b"<?xml encoding='latin1'?>",
629 b"<?xml version='1.0'encoding='latin1'?>",
630 b"<?xmlversion='1.0' encoding='latin1'?>",
631 b" <?xml version='1.0' encoding='latin1'?>",
632 b"<?xml version='1.0' encoding='latin1",
633 b"<?xml version='1.0' encoding=latin1?>",
634 b"<a/>",
635 b"",
636 ] {
637 assert_eq!(declared_encoding(text), None, "{text:?}");
638 }
639 }
640
641 #[test]
642 fn names() {
643 assert_eq!(named("utf-8"), Named::Is(Encoding::Utf8));
644 assert_eq!(named("Latin1"), Named::Is(Encoding::Iso8859_1));
645 assert_eq!(named("WINDOWS-1252"), Named::Is(Encoding::Windows1252));
646 assert_eq!(named("utf-16"), Named::Utf16);
647 assert_eq!(named("ISO-10646-UCS-2"), Named::Other);
648 assert_eq!(named("UCS-2"), Named::Other);
649 assert_eq!(named("l9"), Named::Is(Encoding::Iso8859_15));
650 assert_eq!(named("iso8859_1"), Named::Is(Encoding::Iso8859_1));
651 assert_eq!(named("UNICODE-1-1-UTF-8"), Named::Is(Encoding::Utf8));
652 assert_eq!(named("UTF_8"), Named::Other);
653 assert_eq!(named("x-cp1252"), Named::Other);
654 assert_eq!(named("Shift_JIS"), Named::Other);
655 assert_eq!(named("ISO-8859-2"), Named::Other);
656 assert_eq!(named(""), Named::Invalid);
657 assert_eq!(named("1SO"), Named::Invalid);
658 assert_eq!(named(" UTF-8"), Named::Invalid);
659 assert_eq!(encoding_names().count(), NAMES.len());
660 for (name, encoding) in encoding_names() {
661 assert_eq!(encoding.is_none(), name == "UTF-16", "{name}");
662 }
663 }
664
665 #[test]
666 fn unsupported_and_mismatched() {
667 let decl = |name: &str| format!("<?xml version=\"1.0\" encoding=\"{name}\"?><a/>");
668 assert_eq!(
669 decode(decl("Shift_JIS").as_bytes()),
670 Err(Error::UnsupportedEncoding("Shift_JIS".to_owned()))
671 );
672 assert!(matches!(
673 decode(decl("UTF-16").as_bytes()),
674 Err(Error::EncodingMismatch { declared, .. }) if declared == "UTF-16"
675 ));
676 assert!(decode(decl("1SO-8859-1").as_bytes()).is_ok());
678 assert_eq!(
679 decode(&[0x4C, 0x6F, 0xA7, 0x94, 0x40]),
680 Err(Error::UnsupportedEncoding("EBCDIC".to_owned()))
681 );
682 assert_eq!(
683 decode(b"<\0\0\0a\0\0\0"),
684 Err(Error::UnsupportedEncoding("UCS-4".to_owned()))
685 );
686 assert_eq!(
688 decode(b"\xEF\xBB\xBF\xEF\xBB\xBF<a/>"),
689 Err(Error::UnknownToken(TextPos::new(1, 1)))
690 );
691 assert_eq!(
692 decode_owned(b"\xFF\xFE\xFF\xFE<\0a\0/\0>\0".to_vec()),
693 Err(Error::UnknownToken(TextPos::new(1, 1)))
694 );
695 assert_eq!(
696 decode(b"<a>\n \xC3\xA9\xFF</a>"),
697 Err(Error::InvalidEncodedBytes {
698 encoding: "UTF-8",
699 pos: TextPos::new(2, 4)
700 })
701 );
702 assert_eq!(
703 decode_owned(b"\xEF\xBB\xBF<a>\n\xFF</a>".to_vec()),
704 Err(Error::InvalidEncodedBytes {
705 encoding: "UTF-8",
706 pos: TextPos::new(2, 1)
707 })
708 );
709 }
710}