Skip to main content

Crate ntex_httparse

Crate ntex_httparse 

Source
Expand description

§ntex-httparse

A push library for parsing HTTP/1.x requests and responses, used by ntex. It is a fork of httparse with a lower level API.

Parsers do not borrow the input. Parsed parts are returned as SlicePos ranges into the buffer passed to parse. The start line and the headers are parsed separately:

Incomplete input is not an error, the parsers return Status::Partial. The parse_with_state variants save their progress in a State, so the next call with more data continues where the previous one stopped instead of starting over.

The focus is on speed and safety. Parsing is bounds-checked, unsafe code is limited to the SIMD matchers in a submodule.

SIMD optimizations are enabled automatically when available. If building an executable to be run on multiple platforms, and thus not passing target_feature or target_cpu flags to the compiler, runtime detection can still detect SSE4.2 or AVX2 support to provide massive wins.

If compiling for a specific target, remembering to include -C target_cpu=native allows the detection to become compile time checks, making it even faster.

§Example

use ntex_httparse::{Header, HeaderParsed, Request, Status};

let buf = b"GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\nbody";

let mut req = Request::default();
let Status::Complete(mut pos) = req.parse(buf).unwrap() else {
    unreachable!("the request line is complete")
};
assert_eq!(&buf[req.path.start..req.path.end], b"/index.html");
assert_eq!(req.version, 1);

let mut header = Header::default();
loop {
    let src = &buf[pos..];
    match header.parse(src).unwrap() {
        Status::Complete(HeaderParsed::Header(len)) => {
            assert_eq!(&src[header.name.start..header.name.end], b"Host");
            assert_eq!(&src[header.value.start..header.value.end], b"example.com");
            pos += len;
        }
        Status::Complete(HeaderParsed::Eof(len)) => {
            pos += len;
            break;
        }
        // wait for more data, then parse again
        Status::Partial => unreachable!(),
    }
}
assert_eq!(&buf[pos..], b"body");

Structs§

Header
A parsed header.
InvalidChunkSize
An error in parsing a chunk size.
Request
A parsed request line.
Response
A parsed status line.
SlicePos
A range of the buffer passed to parse, i.e. &src[pos.start..pos.end].
State
Progress of a resumable parse, used by the parse_with_state methods.

Enums§

Error
An error in parsing.
HeaderParsed
Header parse result.
Status
The result of a successful parse pass.

Functions§

parse_chunk_size
Parse a buffer of bytes as a chunk size line.
parse_version
Parse an HTTP version, HTTP/1.0 or HTTP/1.1.

Type Aliases§

Result
A Result of any parsing action.