[web] [WIP] Optimize IO slightly

This commit is contained in:
Emi Simpson 2021-11-01 18:28:47 -04:00
parent 5d47635ce8
commit e55442c47f
Signed by: Emi
GPG Key ID: A12F2C2FFDC3D847
1 changed files with 20 additions and 19 deletions

View File

@ -3,6 +3,7 @@ pub mod contrast;
pub mod statics;
pub mod configuration;
use std::io::IoSlice;
use crate::statics::StaticAsset;
use smol::io::AsyncWriteExt;
use smol::stream::StreamExt;
@ -151,10 +152,10 @@ async fn handle_request(
},
};
if let Err(e) = stream.write_all(
if let Err(e) = stream.write_vectored(
route_request(&req)
.generate_response(settings)
.into_bytes()
.into_io_slices()
.as_ref()
).await {
log::warn!(
@ -484,32 +485,32 @@ pub struct Response {
}
impl Response {
fn into_bytes(self) -> Vec<u8> {
fn into_io_slices(&self) -> Vec<IoSlice<'_>> {
let mut output = Vec::with_capacity(
// Is computing the exact length of the output necessary? No.
// Do we gain any even vaguely measurable performance gain by preventing reallocation? No.
// Am I doing it anyway? Yes.
// It is late and I am tired and you are nothing to me you can't tell me what to do
14 + // HTTP/1.1 200\r\n
self.headers
.iter()
.map(|(h1, h2)| h1.len() + h2.len() + 4)
.sum::<usize>() +
2 + // \r\n
self.body.len()
5 + 4 * self.headers.len()
);
output.extend_from_slice(b"HTTP/1.1 ");
output.extend_from_slice(self.status.to_string().as_bytes());
output.extend_from_slice(b"\r\n");
output.extend_from_slice(&[
IoSlice::new(b"HTTP/1.1 "),
IoSlice::new(self.status.to_string().as_bytes()),
IoSlice::new(b"\r\n"),
]);
for (h1, h2) in self.headers.iter() {
output.extend_from_slice(h1);
output.extend_from_slice(b": ");
output.extend_from_slice(h2);
output.extend_from_slice(b"\r\n");
output.extend_from_slice(&[
IoSlice::new(h1),
IoSlice::new(b": "),
IoSlice::new(h2),
IoSlice::new(b"\r\n"),
]);
}
output.extend_from_slice(b"\r\n");
output.extend_from_slice(&*self.body);
output.extend_from_slice(&[
IoSlice::new(b"\r\n"),
IoSlice::new(&*self.body),
]);
return output;
}
}