Sub topic 13
Designing for zero-copy parsing
This chapter assumes you are comfortable with lifetimes, &str versus String, and the Cow type from the earlier chapter on clone-on-write. It also assumes you can run cargo test.
What zero-copy means
A parser is zero-copy when the values it produces point into the input buffer instead of holding their own copies of the data. A typical parser reads a line, splits it, and builds a String for each field. A zero-copy parser builds &str slices of the original text. The parsed value costs two words per field (a pointer and a length) and makes no heap allocation.
The earlier chapters covered borrowing in function signatures. Zero-copy design applies the same idea to data structures. The parsed result becomes a view onto the input, so the input has to outlive the result.
A borrowing parser
The following program parses key = value lines. The Entry type borrows from the input, and the lifetime 'a ties each entry to the text it came from.
#[derive(Debug, PartialEq)]
struct Entry<'a> {
key: &'a str,
value: &'a str,
}
fn parse_line<'a>(line: &'a str) -> Option<Entry<'a>> {
let (key, value) = line.split_once('=')?;
Some(Entry {
key: key.trim(),
value: value.trim(),
})
}
fn parse_config(text: &str) -> impl Iterator<Item = Entry<'_>> {
text.lines()
.filter(|line| !line.trim_start().starts_with('#'))
.filter_map(parse_line)
}
fn main() {
let text = "name = demo\n# a comment\nport=8080\n";
for entry in parse_config(text) {
println!("{:?}", entry);
}
}Nothing in this program allocates. split_once, trim and lines all return subslices of the original &str. parse_config returns a lazy iterator, so even the collection of entries is optional. The caller decides whether to collect them.
Design rules that make zero-copy work
- Keep the input alive. Every borrowed field is valid only while the input buffer exists. Read the whole file with
std::fs::read_to_stringonce, keep thatStringin the outermost scope, and pass&strinward. - Put the lifetime on the type. Add
<'a>to the structs that hold slices. The lifetime spreads to every type that contains them. Keep the borrowed types in the parsing layer and convert to owned types at the boundary where the data needs a longer life. - Return iterators, not vectors. An iterator of
Entry<'_>lets the caller stream through the data without an intermediateVec. - Choose the right input type.
&strrequires valid UTF-8. For binary formats or text of unknown encoding, parse&[u8]and validate withstd::str::from_utf8only on the fields you need.
When the data must change: Cow in the model
Real formats contain escapes. A quoted value might need \" turned into ". Most values have no escapes, and for those a slice is enough. Use Cow in the field type so that only values needing a change allocate.
use std::borrow::Cow;
#[derive(Debug, PartialEq)]
struct Entry<'a> {
key: &'a str,
value: Cow<'a, str>,
}
fn unescape(s: &str) -> Cow<'_, str> {
if s.contains("\\\"") {
Cow::Owned(s.replace("\\\"", "\""))
} else {
Cow::Borrowed(s)
}
}
fn parse_line<'a>(line: &'a str) -> Option<Entry<'a>> {
let (key, value) = line.split_once('=')?;
Some(Entry {
key: key.trim(),
value: unescape(value.trim()),
})
}
fn main() {
let plain = parse_line("a = plain").unwrap();
let escaped = parse_line(r#"b = say \"hi\""#).unwrap();
assert!(matches!(plain.value, Cow::Borrowed(_)));
assert!(matches!(escaped.value, Cow::Owned(_)));
println!("{:?}\n{:?}", plain, escaped);
}The type stays the same in both cases, and callers read value through Deref as a &str. The cost is one extra branch per value and a slightly larger field (Cow<str> is three words, because it can hold a String).
The lifetime cost and how to handle it
Borrowing has a price. A borrowed result cannot outlive its input, and this causes three common errors.
Returning a borrow of a local buffer. The following does not compile, because text is dropped when the function returns:
fn load_first_key(path: &str) -> std::io::Result<&str> {
let text = std::fs::read_to_string(path)?;
Ok(text.lines().next().unwrap_or(""))
}The fix is to return an owned String at this boundary, or to take the buffer from the caller (fn parse<'a>(text: &'a str) -> ...).
Storing the buffer and its views together. A struct that holds a String and a &str into that same String is self-referential, and safe Rust cannot express it. Do not reach for unsafe first. Store offsets instead of references:
use std::ops::Range;
struct Record {
text: String,
key: Range<usize>,
value: Range<usize>,
}
impl Record {
fn parse(text: String) -> Option<Record> {
let eq = text.find('=')?;
let end = text.len();
Some(Record {
text,
key: 0..eq,
value: eq + 1..end,
})
}
fn key(&self) -> &str {
self.text[self.key.clone()].trim()
}
fn value(&self) -> &str {
self.text[self.value.clone()].trim()
}
}
fn main() {
let rec = Record::parse(String::from("host = example.org")).unwrap();
println!("{} -> {}", rec.key(), rec.value());
}This version has one allocation for the whole record, the same as the borrowing version would need for its input. It also moves freely between threads and across .await points, because it has no lifetime parameter. Reach for it when the record has to be stored or sent somewhere.
Keeping a large buffer alive for a small value. If you keep one &str from a 100 MB file, the whole file stays in memory. When you keep only a few fields long term, copy those with to_owned() or Cow::into_owned() and drop the buffer. This is a deliberate allocation, and it is often the right one.
Zero-copy and serde
Serde supports borrowing during deserialization. A &'a str field borrows from the input automatically. A Cow<'a, str> field needs #[serde(borrow)], otherwise serde always produces an owned value:
use serde::Deserialize;
use std::borrow::Cow;
#[derive(Deserialize)]
struct Message<'a> {
id: u32,
#[serde(borrow)]
text: Cow<'a, str>,
}This needs the serde crate with the derive feature, plus a format crate such as serde_json. With JSON, a plain &str field fails at run time if the string contains an escape sequence, because the decoded text no longer matches any slice of the input. A Cow<str> field with #[serde(borrow)] handles both cases. Note that deserializing from an io::Read (such as serde_json::from_reader) cannot borrow, because the data is not all in memory. Use from_str or from_slice for borrowing.
Where zero-copy does not fit
| Situation | Why zero-copy struggles | Alternative |
|---|---|---|
| Streaming input in small chunks | A token can straddle two reads, so slices into the first chunk are incomplete | Read the whole input, or use a buffer that grows until a full record is available |
| Data stored in long-lived caches | The input buffer would be kept alive by one small field | Convert to owned values, or `Box<str>`/`Arc<str>` |
| Results sent to other threads or tasks | A lifetime parameter makes the type harder to move | Offset ranges, or `bytes::Bytes` (a reference-counted slice of a shared buffer) |
| Formats that need decoding (base64, compressed data) | The decoded bytes do not exist in the input | Decode into a reused buffer |
Deciding whether it is worth it
Zero-copy parsing makes signatures more complex, so apply it where measurement says it matters. Use the counting allocator from the measurement chapter on the parsing function with a representative input. If allocations scale with the number of fields or lines, a borrowing design usually removes them. If the parser already allocates once per file, the remaining gain is small and the lifetime parameters are not worth adding.
Check the result as well. A benchmark with a fixed input can show the parser faster while a downstream step silently calls to_owned() on every field, which moves the allocations rather than removing them.
Exercise
A function fn parse(path: &str) -> std::io::Result<Vec<Entry<'_>>> reads the file into a local String, then returns entries that borrow from it. The compiler rejects it. Give two ways to change the design so it compiles, and say what each one costs.
Show answer
Option 1: make the caller own the buffer. Change the signature to fn parse<'a>(text: &'a str) -> Vec<Entry<'a>> (or return an iterator) and have the caller call read_to_string and keep the String alive. This keeps zero-copy parsing, but the caller must manage the buffer and the lifetime spreads to the caller's types. Option 2: return owned data. Either convert each field with to_owned() or into_owned(), or return a Record-style type that holds the String plus Range<usize> offsets. This costs one allocation per field (or one per record with offsets), but the result has no lifetime and can be stored or sent between threads.