Zero-Copy Parsing with Lifetimes
Prev: Concurrent Worker Pool with Channels | Up: tutorials | Next: third_party
Rel: Ownership, Borrowing & Lifetimes, str
Ref: The Rust Book — Validating References with Lifetimes
Tags: #public #prog #rust #tutorials #lifetimes
Borrowing &'a str Slices Without Heap Allocation
By tying Header<'a> to the input buffer's lifetime 'a, parsing HTTP-style Key: Value lines performs zero heap allocations:
#[derive(Debug, PartialEq)]
struct Header<'a> {
name: &'a str,
value: &'a str,
}
fn parse_header<'a>(line: &'a str) -> Option<Header<'a>> {
let (name, value) = line.split_once(':')?;
Some(Header {
name: name.trim(),
value: value.trim(),
})
}
fn main() {
let raw = "Content-Type: application/json";
let hdr = parse_header(raw).unwrap();
println!("{hdr:?}");
}
Linked from
Related notes
- tuts/rust/tutorials Linked here; links to this page; shared tags: #prog, #rust, #tutorials
- tuts/rust/tutorials/concurrent_worker_pool_channels Linked here; links to this page; shared tags: #prog, #rust, #tutorials
- tuts/rust/builtins/str Linked here; shared tags: #prog, #rust
- tuts/rust/ownership_and_internals/ownership_borrowing_and_lifetimes Linked here; shared tags: #prog, #rust
- tuts/third_party Linked here; shared tags: #prog
- tuts/interop/rust_and_python_pyo3_maturin shared tags: #prog, #rust, #tutorials
- tuts/rust/tutorials/cli_file_processor_with_result shared tags: #prog, #rust, #tutorials
- tuts/c/tutorials shared tags: #prog, #tutorials
- tuts/c/tutorials/arena_allocator_pattern shared tags: #prog, #tutorials
- tuts/c/tutorials/c_shared_library_with_python_ctypes shared tags: #prog, #tutorials