use std::io::{self, Read, Cursor, Chain};
use std::net::Shutdown;
use super::data::BodyReader;
use http::hyper::net::NetworkStream;
use http::hyper::h1::HttpReader;
pub type InnerStream = Chain<Cursor<Vec<u8>>, BodyReader>;
pub struct DataStream(pub(crate) InnerStream);
impl Read for DataStream {
#[inline(always)]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
trace_!("DataStream::read()");
self.0.read(buf)
}
}
pub fn kill_stream(stream: &mut BodyReader) {
use self::HttpReader::*;
match *stream {
SizedReader(_, n) | ChunkedReader(_, Some(n)) if n > 0 => { },
_ => return
};
const FLUSH_LEN: u64 = 1024;
match io::copy(&mut stream.take(FLUSH_LEN), &mut io::sink()) {
Ok(FLUSH_LEN) | Err(_) => {
warn_!("Data left unread. Force closing network stream.");
let (_, network) = stream.get_mut().get_mut();
if let Err(e) = network.close(Shutdown::Read) {
error_!("Failed to close network stream: {:?}", e);
}
}
Ok(n) => debug!("flushed {} unread bytes", n)
}
}
impl Drop for DataStream {
fn drop(&mut self) {
kill_stream(&mut self.0.get_mut().1);
}
}