On this page
  1. Zero-Copy Parsing with Lifetimes
  2. Borrowing &'a str Slices Without Heap Allocation

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