Encoding
A page in Shift_JIS whose `<meta>` says UTF-8 is a normal day for a crawler. Parsec picks the encoding the way a browser does and tells you how sure it is.
What it does
- The browser’s algorithm: byte order mark, the transport’s charset, the
<meta>prescan, a UTF-8 check and a locale default. - A second parse when a
<meta>turns up late and changes the answer, as browsers do. ByteParser, for bytes as they arrive, which gives the same document as parsing them whole, for any split.Offsets, to turn a position in the decoded text back into a position in the bytes.- With its default features off, sniffing and decoding alone, without the HTML parser.
Add it
In Rust, add parsec-web-encoding (0.3.1 on crates.io); the library inside isparsec_encoding. Bytes in, the encoding found and streaming all work from Python, JavaScript and C as well.
use parsec_encoding::Encoding;
let sjis = Encoding::for_label(b"sjis").unwrap();
assert_eq!(sjis.name(), "Shift_JIS");
let (text, _, had_errors) = sjis.decode(b"\x93\xfa\x96\x7b");
assert_eq!((&*text, had_errors), ("日本", false));
let (bytes, _, _) = sjis.encode("日本");
assert_eq!(&*bytes, b"\x93\xfa\x96\x7b");That's the first example in the crate's own documentation at the v0.3.1 tag, unchanged.cargo test runs it on every change, so it compiles and passes against the release you'd install. The API reference on docs.rs has the rest, and the getting started guide goes step by step.
Checked against the standards
These counts are the conformance baseline on Parsec's main branch, read when this page was built. Each release has to match or beat them: a suite that passes fewer cases, or fails more, stops the release.
| Suite | Pass | Fail | Skipped |
|---|---|---|---|
| html5lib encoding | 82 | 0 | 1 |
| web-platform-tests encoding labels | 228 | 0 | 0 |
| web-platform-tests single-byte decoders | 168 | 0 | 0 |
| web-platform-tests legacy multi-byte pages | 62,352 | 0 | 0 |
| web-platform-tests GB18030 and GBK | 357 | 0 | 0 |
| web-platform-tests ISO-2022-JP | 38 | 0 | 0 |
| encoder round trips | 53,813 | 0 | 0 |
| streamed in pieces, html5lib pages | 369,396 | 0 | 0 |
| streamed in pieces, web-platform-tests pages | 49,422 | 0 | 0 |
Standards has every suite, where its data comes from, and why the failures and skips are what they are.
Where it stops
- The decoders themselves are encoding_rs, Firefox’s implementation of the Encoding Standard, re-exported. Parsec’s part is choosing the encoding and parsing what it decodes.
The Encoding page in the docs goes through the API, the limits and the conformance details in full.