Design zero-copy parsers with Rust borrowing
8 steps · about 4 h 20 min · Intermediate
- Represent input regions with slices (guide, The Rust Programming Language, 30 min)
A string slice identifies validated UTF-8 within an existing buffer without allocating a copy.
- Relate returned views to input lifetimes (guide, The Rust Programming Language, 40 min)
Lifetime parameters document that parsed fields cannot outlive their source text.
- Split tokens without allocating (reference, Rust standard library, 25 min)
Borrowed string operations can isolate fields while retaining slices into the original input.
- Iterate through borrowed tokens (reference, Rust standard library, 25 min)
A standard iterator handles Unicode whitespace and yields slices on demand.
- Return structured parse failures (reference, Rust standard library, 35 min)
Result forces callers to handle malformed input without panics or sentinel values.
- Copy only when normalisation requires it (reference, Rust standard library, 30 min)
Cow preserves borrowing for unchanged fields while allowing owned output for exceptional transformations.
- Test valid, partial and malformed inputs (guide, The Rust Programming Language, 35 min)
Boundary-focused examples protect both returned values and the parser's failure locations.
- Benchmark borrowed and allocating variants (guide, Criterion.rs documentation, 40 min)
Measured throughput and allocation tradeoffs show whether extra lifetime complexity is warranted.