Skip to content

Commit

Permalink
Improve request method parsing (#119)
Browse files Browse the repository at this point in the history
Special-case parsing of the GET and POST request method as that is by far the
most common. Speeds up the req_short benchmark by a fair margin:

       req_short/req_short     time:   [32.601 ns 32.737 ns 32.914 ns]
                            thrpt:  [1.9241 GiB/s 1.9345 GiB/s 1.9425 GiB/s]
                     change:
                            time:   [-4.1113% -3.5415% -3.0150%] (p = 0.00 < 0.05)
                            thrpt:  [+3.1087% +3.6715% +4.2876%]
                            Performance has improved.

Co-authored-by: Luca Casonato <hello@lcas.dev>
Co-authored-by: Ben Noordhuis <info@bnoordhuis.nl>
  • Loading branch information
3 people committed Aug 2, 2022
1 parent aa6108b commit 5f8a7b4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
26 changes: 25 additions & 1 deletion src/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,21 @@ impl<'a> Bytes<'a> {

#[inline]
pub fn peek(&self) -> Option<u8> {
self.slice.get(self.pos).cloned()
self.peek_ahead(0)
}

#[inline]
pub fn peek_ahead(&self, n: usize) -> Option<u8> {
self.slice.get(self.pos + n).cloned()
}

#[inline]
pub fn peek_4(&self) -> Option<&[u8]> {
if self.slice.len() >= self.pos + 4 {
Some(&self.slice[self.pos..=self.pos + 3])
} else {
None
}
}

#[inline]
Expand Down Expand Up @@ -62,6 +76,16 @@ impl<'a> Bytes<'a> {
head
}

#[inline]
pub unsafe fn advance_and_commit(&mut self, n: usize) {
debug_assert!(self.pos + n <= self.slice.len(), "overflow");
self.pos += n;
let ptr = self.slice.as_ptr();
let tail = slice::from_raw_parts(ptr.add(n), self.slice.len() - n);
self.pos = 0;
self.slice = tail;
}

#[inline]
pub fn next_8<'b>(&'b mut self) -> Option<Bytes8<'b, 'a>> {
if self.slice.len() >= self.pos + 8 {
Expand Down
19 changes: 17 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -475,10 +475,25 @@ impl<'h, 'b> Request<'h, 'b> {
config: &ParserConfig,
mut headers: &'h mut [MaybeUninit<Header<'b>>],
) -> Result<usize> {
let orig_len = buf.len();
let orig_len = buf.len();
let mut bytes = Bytes::new(buf);
complete!(skip_empty_lines(&mut bytes));
self.method = Some(complete!(parse_token(&mut bytes)));
let method = match bytes.peek_4() {
Some(b"GET ") => {
unsafe {
bytes.advance_and_commit(4);
}
"GET"
}
Some(b"POST") if bytes.peek_ahead(4) == Some(b' ') => {
unsafe {
bytes.advance_and_commit(5);
}
"POST"
}
_ => complete!(parse_token(&mut bytes)),
};
self.method = Some(method);
if config.allow_multiple_spaces_in_request_line_delimiters {
complete!(skip_spaces(&mut bytes));
}
Expand Down

0 comments on commit 5f8a7b4

Please sign in to comment.