Skip to content

Commit

Permalink
perf(http): encoder headers with a faster fmt::Write
Browse files Browse the repository at this point in the history
  • Loading branch information
seanmonstar committed Aug 6, 2016
1 parent 81e7bf4 commit 12dac9b
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions src/http/h1/parse.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::borrow::Cow;
use std::io::Write;
use std::fmt::{self, Write};

use httparse;

Expand Down Expand Up @@ -95,8 +95,12 @@ impl Http1Message for ServerMessage {
let init_cap = 30 + head.headers.len() * AVERAGE_HEADER_SIZE;
dst.reserve(init_cap);
debug!("writing {:#?}", head.headers);
let _ = write!(dst, "{} {}\r\n{}\r\n", head.version, head.subject, head.headers);

if head.version == ::HttpVersion::Http11 && head.subject == ::StatusCode::Ok {
extend(dst, b"HTTP/1.1 200 OK\r\n");
let _ = write!(FastWrite(dst), "{}\r\n", head.headers);
} else {
let _ = write!(FastWrite(dst), "{} {}\r\n{}\r\n", head.version, head.subject, head.headers);
}
body
}
}
Expand Down Expand Up @@ -195,12 +199,37 @@ impl Http1Message for ClientMessage {
let init_cap = 30 + head.headers.len() * AVERAGE_HEADER_SIZE;
dst.reserve(init_cap);
debug!("writing {:#?}", head.headers);
let _ = write!(dst, "{} {}\r\n{}\r\n", head.subject, head.version, head.headers);
let _ = write!(FastWrite(dst), "{} {}\r\n{}\r\n", head.subject, head.version, head.headers);

body
}
}

struct FastWrite<'a>(&'a mut Vec<u8>);

impl<'a> fmt::Write for FastWrite<'a> {
fn write_str(&mut self, s: &str) -> fmt::Result {
extend(self.0, s.as_bytes());
Ok(())
}

fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result {
fmt::write(self, args)
}
}

fn extend(dst: &mut Vec<u8>, data: &[u8]) {
use std::ptr;
dst.reserve(data.len());
let prev = dst.len();
unsafe {
ptr::copy_nonoverlapping(data.as_ptr(),
dst.as_mut_ptr().offset(prev as isize),
data.len());
dst.set_len(prev + data.len());
}
}

#[cfg(test)]
mod tests {
use http;
Expand Down

0 comments on commit 12dac9b

Please sign in to comment.