Skip to content

parser: slice input text instead of re-validating UTF-8 - #75

Merged
jonwiggins merged 1 commit into
jonwiggins:mainfrom
dkam:feature/parser-utf8-slices
Nov 20, 2026
Merged

jonwiggins merged 1 commit into
jonwiggins:mainfrom
dkam:feature/parser-utf8-slices

Conversation

@dkam

@dkam dkam commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Summary

ParserInput is always built from a &str, so its bytes are known to be valid UTF-8. Despite that, the XML parser turned every name, attribute value, run of character data, comment, CDATA section and PI back into a &str with std::str::from_utf8, which scans every byte a second time. The HTML parser did the same with String::from_utf8_lossy.

This PR keeps the original &str in ParserInput and slices it with str::get(start..end), which only checks that the two offsets fall on character boundaries:

  • ParserInput::str_slice(start, end) -> Option<&str> replaces each from_utf8(&input[a..b]). The existing "invalid UTF-8" errors are kept for a split character, which can't happen when the offsets come from the parser.
  • peek_char's multi-byte path decodes from the &str as well.
  • The HTML parser gets an input_text helper that falls back to from_utf8_lossy if a slice ever splits a character, so its output is byte-for-byte unchanged.

The HTML5 parser has its own input handling and isn't touched.

Results

Change in time per iteration against main (negative is faster), measured two ways on an Apple M4 (details below):

parser_bench fixture cargo bench (round 1, round 2) min-of-batches
parse_small −6.8%, −12.2% −7.7% [−9.8, +0.4]
parse_medium −16.1%, −15.0% −9.2% [−11.8, −3.9]
parse_large −9.4%, −8.5% −8.3% [−9.7, −5.6]
parse_deeply_nested −4.3%, −3.3% −4.7% [−6.1, +3.1]
parse_many_attributes −6.6%, −6.8% −6.5% [−7.9, −4.9]
parse_namespace_heavy −9.4%, −7.5% −9.0% [−17.3, −7.1]
parse_html −12.0%, −11.4% −3.9% [−7.2, −0.8] †
sax_parse −7.4%, −6.9% −9.5% [−13.9, −1.9]
reader_parse −8.8%, −6.3% −10.0% [−10.8, −8.5]
push_parser −9.4%, −3.6% −10.6% [−11.9, −9.7]
roundtrip −12.1%, −12.2% −10.1% [−11.1, −4.0]
validate_dtd −5.9%, −6.8% −5.7% [−6.3, −3.4]
Not touched by this PR
parse_html5 +0.7%, +0.1% −0.1% [−3.4, +1.2] †
serialize_large +4.3%, +3.5% +1.4% [+0.1, +2.9] †
xpath_simple +2.3%, −0.4% not measured

How these were measured:

  • cargo bench: cargo bench --bench parser_bench with criterion's defaults. For each benchmark, main, this branch and main again ran back to back, in two rounds with the order changed. Each figure compares one round's run of this branch with the mean of that round's two main runs. Those two main runs agreed within 3%, except on parse_small (+13.8% in round 2) and push_parser (+6.0% in round 2).
  • min-of-batches: an earlier criterion run on a busier machine moved by up to ±30% between identical runs of main, so I also copied the fixtures verbatim into a small harness that records the fastest of 25 batches of about 10 ms. main and this branch alternated over 15 cycles, and each figure is the median of the per-cycle ratios, with the interquartile range in brackets. Rows marked † come from a separate 30-cycle run of just those benchmarks.

serialize_large never reaches the parser's timed path, yet it came out 1–4% slower. I can't attribute that to anything but code layout differing between the two builds, which is also the likeliest reason the two methods disagree on parse_medium and parse_html. Differences of a few percent between builds shouldn't be read as real.

Type of Change

  • Bug fix (corrects an existing issue)
  • New feature (adds new functionality)
  • Conformance fix (aligns behavior with the W3C spec or libxml2)
  • Refactoring (no functional change)
  • Documentation (docs, comments, examples)
  • CI / tooling (build scripts, workflows, hooks)

Test Plan

New tests:

  • test_str_slice_respects_char_boundaries: a slice that splits a multi-byte character returns None.
  • test_peek_char_multibyte: multi-byte characters are peeked correctly.
  • test_parse_non_ascii_in_every_construct: non-ASCII text in each construct that now goes through str_slice (DOCTYPE name and internal subset, element and attribute names, attribute values with entity references, comments, CDATA, PIs, and character data including a 4-byte character) parses to the expected strings.
  • test_parse_non_ascii_text_and_attribute_values: the same for the HTML parser.

Each of the CI jobs was run locally on macOS (aarch64):

  • cargo fmt --all -- --check: passes
  • cargo test --all-features on 1.100.0: passes, including the W3C, libxml2-compat and html5lib suites
  • cargo test --features cli,ffi on 1.81.0: passes
  • RUSTDOCFLAGS="-D warnings" cargo doc --all-features --no-deps: passes
  • cargo clippy --all-targets --all-features -- -D warnings: clean apart from the assert_is_empty/needless_bool errors already on main, which fix: resolve clippy assert_is_empty and needless_bool warnings #74 fixes

Checklist

  • Code is formatted (cargo fmt --all)
  • No clippy warnings (cargo clippy --all-targets --all-features -- -D warnings), once fix: resolve clippy assert_is_empty and needless_bool warnings #74 is merged
  • All tests pass (cargo test --all-features)
  • Documentation updated for any public API changes (ParserInput is crate-internal)
  • Commit messages follow the <module>: <summary> convention
  • No new dependencies added

🤖 Generated with Claude Code

ParserInput is always built from a &str, so its bytes are already valid
UTF-8, yet names, attribute values, character data, comments, CDATA and
PIs were each converted back with std::str::from_utf8, which scans every
byte again. Keep the &str alongside the bytes and slice it instead:
str::get only checks that the two offsets fall on character boundaries.

The HTML parser's from_utf8_lossy calls take the same route, falling
back to a lossy conversion only if a bound splits a character, so its
output is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jonwiggins
jonwiggins force-pushed the feature/parser-utf8-slices branch from 7e16408 to ee83eef Compare November 20, 2026 21:46
@jonwiggins
jonwiggins merged commit f73e13c into jonwiggins:main Nov 20, 2026
6 checks passed
@jonwiggins

Copy link
Copy Markdown
Owner

Thanks, merged. I rebased onto current main to pick up the clippy 1.100 fixes. I also checked that every ParserInput is built from a &str (the push parser and parse_bytes transcode to a String first), so str::get returning None on a bad boundary is a recoverable error where the old code could panic. A differential run over about 20k generated inputs (multi-byte characters at token boundaries, recover mode, SAX, reader, the HTML parser, push-parser chunks split mid-codepoint, Latin-1 and invalid UTF-8 via parse_bytes) gave byte-identical output to main, with no panics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants