Thread safety and memory safety
Two questions come up first from anyone moving off a C parser: can I share a document between threads, and can a bad page make it touch memory it shouldn’t? Here’s what’s true, what the build guarantees, and what’s planned.
- Threads: What’s true today, What the build guarantees, On every core
- Memory: Node handles can’t dangle, The one
unsafeblock, Dependencies, Panics, Memory use - Reporting a problem
Threads
Section titled “Threads”What’s true today
Section titled “What’s true today”Document is plain owned data. Inside it are vectors, a boxed string, a String, and Copy enums and integers: no Rc, no RefCell or Cell, no raw pointers, no interior mutability of any kind. Rust therefore makes it Send and Sync automatically, and the same goes for SelectorList. You can check it yourself:
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<parsec::Document>();assert_send_sync::<parsec::css::SelectorList>();assert_send_sync::<parsec::css::SelectorError>();assert_send_sync::<parsec::ParseError>();That compiles on main. What it means in practice:
- Parse on as many threads as you like. Each parse builds its own document and shares nothing. There’s no global parser state to lock.
- Read one document from many threads. All the read methods (
kind,attrs,children,text,inner_html, selector matching…) take&self, so you can share a&Documentthrough scoped threads or anArc<Document>. - Write from one place at a time. Every edit takes
&mut self, so the compiler stops you editing while anyone else holds a reference. To mix readers and writers across threads, put the document in aRwLockorMutex. - Move a document to another thread once it’s parsed, or send it down a channel.
use parsec::css::SelectorList;use std::sync::Arc;
fn main() { let pages = ["<p>a</p>", "<p>b</p><p>c</p>", "<div><p>d</p></div>"];
// Parse on several threads at once. let docs: Vec<parsec::Document> = std::thread::scope(|s| { let handles: Vec<_> = pages .iter() .map(|html| s.spawn(move || parsec::parse(html, false))) .collect(); handles.into_iter().map(|h| h.join().unwrap()).collect() });
// Query one shared document from several threads at once. let doc = Arc::new(parsec::parse(&"<p>x</p>".repeat(1000), false)); let list = Arc::new(SelectorList::parse("p").unwrap()); let counts: Vec<usize> = (0..4) .map(|_| { let (doc, list) = (Arc::clone(&doc), Arc::clone(&list)); std::thread::spawn(move || list.select(&doc, doc.root()).len()) }) .map(|h| h.join().unwrap()) .collect();
assert_eq!(docs.len(), 3); assert_eq!(counts, [1000, 1000, 1000, 1000]);}There’s one piece of state shared by all documents: the table the parser uses to look up tag names, built on first use inside a std::sync::OnceLock (tags.rs). OnceLock makes that first use safe from any number of threads.
What the build guarantees
Section titled “What the build guarantees”None of this is luck any more. lib.rs asserts it at compile time:
const _: () = { const fn shareable<T: Send + Sync>() {} shareable::<Document>(); shareable::<css::SelectorList>();};If a change ever slips an Rc or a Cell into either type, the crate stops building, so you can lean on Send + Sync the way you lean on any other part of the API. tests/threads.rs goes a step further. It parses one document, then runs the same selector on it from eight threads at once and checks that every thread gets the same 500 matches a single thread does.
The model in one line: many readers, or one writer, never both. Reads take &Document, so any number of threads can read at once with no locking. Edits take &mut Document, so the borrow checker lets one thread write and nobody read while it does. Need both from different threads? Wrap the document in an RwLock.
A SelectorList is shareable too. Parse a selector once and use it from every thread.
On every core
Section titled “On every core”Separate pages parse without touching each other, so throughput grows with cores. examples/parallel.rs measures it: it parses a file on every core at once and compares the rate with one thread.
cargo run --release --example parallel page.htmlOn a machine with 16 logical cores, for a 200 KB page, it printed this, in the pull request that added it:
1 thread: 3316 pages/s16 threads: 29212 pages/s (8.8x)Logical cores share physical ones, so don’t expect 16 threads to give 16x. Your numbers will differ, so run it on your own pages.
For comparison, Lexbor has no thread-safety story: an old answer that it was thread-safe was followed by a user pointing out that mutations aren’t atomic (lexbor#105), and selectolax documents its Lexbor parsers as not thread-safe (selectolax docs).
Memory
Section titled “Memory”Node handles can’t dangle
Section titled “Node handles can’t dangle”In Lexbor a node is a pointer, and a pointer to a node that’s been destroyed is a use-after-free; there’s no reference counting, which has been an open issue since 2021 (lexbor#132). In Parsec a node is a NodeId, an index into the document’s vector of nodes. A removed node stays in the vector until the document is dropped, and ids are never reused, so using a stale id is safe. It’s also not misleading: remove marks the node and everything in it, and from then on each of their ids reads as nothing (no parent, children, attributes, text or markup) and can’t be inserted again. detach is the one that keeps a subtree whole, to move it.
doc.is_removed(id) tells you whether its node was removed, and doc.parent(id) whether a live one is in the tree. An id is only meaningful with the document it came from: an id from another document won’t crash anything, but it names a different node.
The one unsafe block
Section titled “The one unsafe block”All of Parsec’s own code is safe Rust except one block, in crates/parsec/src/tree.rs, in the function source:
/// Gives the document its preprocessed source, and returns it for the/// tokenizer to read.fn source<'a>(builder: &mut TreeBuilder, html: &str) -> &'a str { builder.doc.src = match tokenizer::preprocess(html) { std::borrow::Cow::Borrowed(s) => s.into(), std::borrow::Cow::Owned(s) => s.into_boxed_str(), }; // SAFETY: the source is a boxed str the document never changes or // drops while it's parsed, so its bytes stay where they are while the // tokenizer reads them, even though the builder holding them moves. // The returned reference doesn't outlive the parse functions above. unsafe { &*(builder.doc.src.as_ref() as *const str) }}Why it’s there: the tokenizer reads the source, and the tree builder, which owns the document that owns the source, is lent to the tokenizer mutably as its Sink. The borrow checker can’t express “this one field won’t change while the rest is mutated”, so the reference is made by hand.
Why it’s sound:
srcis aBox<str>. Its bytes live on the heap, and moving the builder or the document moves the box’s pointer, not the bytes.- Nothing writes to
srcor replaces it after this function, for the rest of the parse. The tree builder only reads it, to check whether a string is a slice of it. - The reference is used only by the tokenizer inside
runintree.rs, and the tokenizer doesn’t outlive that function. The document is handed back to you after the tokenizer’s last use.
Everything else (the arena, the spans, the tokenizer’s slices of the input) is index arithmetic on vectors and strings, checked by the compiler and, where indexes are computed, bounds-checked at run time.
The C API, in crates/parsec-capi, is the other place with unsafe, and it’s all at the boundary with C: reading the pointers and lengths C passes in, writing through its out pointers, and turning handles back into the documents and selectors they stand for. Each block says what it relies on beside it. Past the boundary it calls the same safe code Rust does, and every node number is checked against the document before it’s used. CI runs the C test under AddressSanitizer, LeakSanitizer and UndefinedBehaviorSanitizer.
Dependencies
Section titled “Dependencies”Parsec has two dependencies: memchr, for fast byte searches, and url, which :valid and :invalid use to check an <input type=url>. memchr uses unsafe internally for its SIMD code, so “one unsafe block” describes Parsec’s own code, not everything it links. The test-only dependency, serde_json, reads the html5lib test files and isn’t part of the library. CI runs cargo deny on licences, bans, sources and advisories.
Panics
Section titled “Panics”The parser isn’t meant to panic on any input under the size cap, and the fuzz target checks that nightly on inputs of up to 4,096 bytes (see Limits and hostile input). The panics you can cause are documented on the functions:
parseandparse_fragmentpanic on input overMAX_INPUTbytes.parse_withandparse_fragment_withreturn an error instead.- Every method that takes a
NodeIdpanics on an id that’sdoc.len()or more.
Serialization, text and select don’t recurse on the depth of the tree, matching a complex selector is a loop however many compounds it has, and functional pseudo-classes nest at most 32 deep, so neither a deep page nor a long or deep selector exhausts the stack in those paths. The Security review has the case that showed the chain length needed this too.
Memory use
Section titled “Memory use”A document’s memory is proportional to its input, reserved up front from the input’s length and grown as needed. There’s no limit apart from MAX_INPUT, and edits never give memory back until the document is dropped (see Editing).
Reporting a problem
Section titled “Reporting a problem”If you find input that crashes Parsec, hangs it, or makes it touch memory it shouldn’t, please report it privately, as SECURITY.md explains, not in a public issue.
See also
Section titled “See also”- Limits and hostile input, for time and size limits on untrusted pages.
- Architecture, for the layout that makes ids safe.
- Editing, for what happens to a removed node.