Rustrustparsingzero-copyperformanceproduction-ready
Zero-Copy Parsing
Efficient parsing patterns that reference the original input buffer without allocating, using lifetimes and slice references.
/// A parsed HTTP request that borrows from the input buffer
#[derive(Debug)]
pub struct Request<'a> {
pub method: &'a str,
pub path: &'a str,
pub version: &'a str,
pub headers: Vec<Header<'a>>,
pub body: &'a [u8],
}
#[derive(Debug)]
pub struct Header<'a> {
pub name: &'a str,
pub value: &'a str,
}
/// Parse HTTP request without allocating strings
pub fn parse_request(input: &[u8]) -> Result<Request<'_>, ParseError> {
let input_str = std::str::from_utf8(input)
.map_err(|_| ParseError::InvalidUtf8)?;
let (request_line, rest) = input_str
.split_once("
")
.ok_or(ParseError::MalformedRequest)?;
// Parse request line: "GET /path HTTP/1.1"
let mut parts = request_line.splitn(3, ' ');
let method = parts.next().ok_or(ParseError::MalformedRequest)?;
let path = parts.next().ok_or(ParseError::MalformedRequest)?;
let version = parts.next().ok_or(ParseError::MalformedRequest)?;
// Parse headers
let (header_section, body_str) = rest
.split_once("
")
.unwrap_or((rest, ""));
let headers: Vec<Header<'_>> = header_section
.lines()
.filter(|line| !line.is_empty())
.filter_map(|line| {
let (name, value) = line.split_once(':')?;
Some(Header {
name: name.trim(),
value: value.trim(),
})
})
.collect();
Ok(Request {
method,
path,
version,
headers,
body: body_str.as_bytes(),
})
}
/// CSV row parser that borrows from the line
#[derive(Debug)]
pub struct CsvRow<'a> {
fields: Vec<&'a str>,
}
impl<'a> CsvRow<'a> {
pub fn parse(line: &'a str) -> Self {
let fields = line.split(',').map(|f| f.trim()).collect();
CsvRow { fields }
}
pub fn get(&self, index: usize) -> Option<&'a str> {
self.fields.get(index).copied()
}
pub fn len(&self) -> usize {
self.fields.len()
}
}
/// Stream CSV rows with zero allocation per row
pub fn iter_csv_rows(data: &str) -> impl Iterator<Item = CsvRow<'_>> {
data.lines()
.filter(|line| !line.is_empty())
.map(CsvRow::parse)
}
#[derive(Debug)]
pub enum ParseError {
InvalidUtf8,
MalformedRequest,
}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidUtf8 => write!(f, "Invalid UTF-8 in request"),
Self::MalformedRequest => write!(f, "Malformed HTTP request"),
}
}
}title: "Zero-Copy Parsing" description: "Efficient parsing patterns that reference the original input buffer without allocating, using lifetimes and slice references." category: "Rust" language: "rust" tags: ["rust", "parsing", "zero-copy", "performance", "production-ready"] createdAt: "2025-03-25" updatedAt: "2025-04-10"
Overview
Zero-copy parsing leverages Rust's lifetime system to produce parsed structures that reference slices of the original input buffer rather than allocating new strings. This dramatically reduces memory allocations in high-throughput parsers.
Code
pub struct Request<'a> {
pub method: &'a str, // Points into the input buffer
pub path: &'a str, // No allocation
}
let request = parse_request(&buffer)?;Notes
- The
'alifetime ties the parsed output to the input buffer's lifetime - No
Stringallocations occur; all fields are&strslices into the original bytes - The tradeoff: parsed data cannot outlive the input buffer
- Use
into_owned()or.to_string()when you need the parsed data to outlive the source - This pattern is used by high-performance parsers like
nom,httparse, andserdewith&str