Sub topic 13
Designing for zero-copy parsing
This chapter assumes you are comfortable with lifetimes, &str slices and iterator chains. It also assumes you have read the earlier chapters on borrowing and Cow.
What zero-copy means
A parser is zero-copy when its output points into the input buffer instead of copying pieces out of it. A String field costs one heap allocation per value. A &str field is a pointer and a length into memory that already exists.
The input buffer is read once, for example with std::fs::read_to_string. After that, the parsed values only borrow from it.
A borrowing record type
Add a lifetime parameter to the output type. It ties each record to the buffer it came from.
#[derive(Debug)]
struct Record<'a> {
name: &'a str,
value: &'a str,
}
fn parse_line(line: &str) -> Option<Record<'_>> {
let (name, value) = line.split_once('=')?;
Some(Record {
name: name.trim(),
value: value.trim(),
})
}
fn records(input: &str) -> impl Iterator<Item = Record<'_>> + '_ {
input.lines().filter_map(parse_line)
}
fn main() {
let input = String::from("host = example.com\nport = 8080\nbad line\n");
for r in records(&input) {
println!("{} -> {}", r.name, r.value);
}
}split_once, trim and lines all return sub-slices of their input, so no field is copied. Returning an iterator instead of a Vec<Record> also removes the allocation for the collection. Callers who need a Vec can call collect() themselves.
Design rules
- Put the lifetime in the output types, such as
Record<'a>, and let the compiler enforce that the buffer outlives every record. - Return iterators from parsing functions when callers usually process records one at a time.
- Use
&[u8]for binary or not-yet-validated text, and validate withstd::str::from_utf8once per field.from_utf8borrows and does not allocate. - Use
Cow<'a, str>for fields that are usually verbatim but sometimes need rewriting, such as unescaping. The common case stays borrowed and only the rare case allocates.
Costs and failure modes
Zero-copy spreads lifetimes through your types. Every struct that holds a Record<'a> also needs 'a, and the buffer must stay alive and unmoved while any record exists.
You cannot store a record and its buffer in the same struct without self-referential tricks. That is usually a sign to keep the buffer in a caller-owned variable. If a value must outlive the buffer, copy it at that boundary with to_owned(). Copying only the few values you keep is cheaper than copying everything.
Holding one small slice also keeps the whole buffer alive. A cache that keeps a 10-byte &str into a 100 MB file pins the entire file. Copy small long-lived values.
Some formats need a copy anyway. Escape sequences, character encoding conversions and decompression all produce bytes that are not present in the input.
When it is worth it
Measure first, as in the earlier chapter. Zero-copy pays off when you parse large inputs with many small fields, such as logs or CSV files. It is rarely worth the lifetime complexity for a small config file read once at startup.
Exercise
The function fn parse_owned(input: &str) -> Vec<(String, String)> splits each line into a name and a value. Which changes remove its allocations, and what does the caller have to guarantee afterwards?
Show answer
Return impl Iterator<Item = (&str, &str)> + '_ built from input.lines() and split_once('='). Use &str instead of String for the fields, and do not collect into a Vec. This removes the per-field allocations and the collection allocation. The caller must keep input alive and unchanged for as long as any returned slice is used.