Replace IoResult and IoError with io:: versions. (#161)
This commit is contained in:
committed by
GitHub
parent
e8c3403f7b
commit
7046b07518
@@ -1,6 +1,6 @@
|
|||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::io::{copy, empty, Cursor, Read, Result as IoResult, Write};
|
use std::io::{self, copy, empty, Cursor, Read, Write};
|
||||||
|
|
||||||
#[cfg(feature = "charset")]
|
#[cfg(feature = "charset")]
|
||||||
use crate::response::DEFAULT_CHARACTER_SET;
|
use crate::response::DEFAULT_CHARACTER_SET;
|
||||||
@@ -119,7 +119,7 @@ const CHUNK_MAX_PAYLOAD_SIZE: usize = CHUNK_MAX_SIZE - CHUNK_HEADER_MAX_SIZE - C
|
|||||||
// 2) chunked_transfer's Encoder issues 4 separate write() per chunk. This is costly
|
// 2) chunked_transfer's Encoder issues 4 separate write() per chunk. This is costly
|
||||||
// overhead. Instead, we do a single write() per chunk.
|
// overhead. Instead, we do a single write() per chunk.
|
||||||
// The measured benefit on a Linux machine is a 50% reduction in CPU usage on a https connection.
|
// The measured benefit on a Linux machine is a 50% reduction in CPU usage on a https connection.
|
||||||
fn copy_chunked<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> IoResult<u64> {
|
fn copy_chunked<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> io::Result<u64> {
|
||||||
// The chunk layout is:
|
// The chunk layout is:
|
||||||
// header:header_max_size | payload:max_payload_size | footer:footer_size
|
// header:header_max_size | payload:max_payload_size | footer:footer_size
|
||||||
let mut chunk = Vec::with_capacity(CHUNK_MAX_SIZE);
|
let mut chunk = Vec::with_capacity(CHUNK_MAX_SIZE);
|
||||||
@@ -177,7 +177,7 @@ pub(crate) fn send_body(
|
|||||||
mut body: SizedReader,
|
mut body: SizedReader,
|
||||||
do_chunk: bool,
|
do_chunk: bool,
|
||||||
stream: &mut Stream,
|
stream: &mut Stream,
|
||||||
) -> IoResult<()> {
|
) -> io::Result<()> {
|
||||||
if do_chunk {
|
if do_chunk {
|
||||||
copy_chunked(&mut body.reader, stream)?;
|
copy_chunked(&mut body.reader, stream)?;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::io::Error as IoError;
|
use std::io;
|
||||||
|
|
||||||
/// Errors that are translated to ["synthetic" responses](struct.Response.html#method.synthetic).
|
/// Errors that are translated to ["synthetic" responses](struct.Response.html#method.synthetic).
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -22,7 +22,7 @@ pub enum Error {
|
|||||||
/// A header line that couldn't be parsed. Synthetic error `500`.
|
/// A header line that couldn't be parsed. Synthetic error `500`.
|
||||||
BadHeader,
|
BadHeader,
|
||||||
/// Some unspecified `std::io::Error`. Synthetic error `500`.
|
/// Some unspecified `std::io::Error`. Synthetic error `500`.
|
||||||
Io(IoError),
|
Io(io::Error),
|
||||||
/// Proxy information was not properly formatted
|
/// Proxy information was not properly formatted
|
||||||
BadProxy,
|
BadProxy,
|
||||||
/// Proxy credentials were not properly formatted
|
/// Proxy credentials were not properly formatted
|
||||||
@@ -110,8 +110,8 @@ impl Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<IoError> for Error {
|
impl From<io::Error> for Error {
|
||||||
fn from(err: IoError) -> Error {
|
fn from(err: io::Error) -> Error {
|
||||||
Error::Io(err)
|
Error::Io(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::collections::hash_map::Entry;
|
use std::collections::hash_map::Entry;
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
use std::io::{Read, Result as IoResult};
|
use std::io::{self, Read};
|
||||||
|
|
||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use crate::unit::Unit;
|
use crate::unit::Unit;
|
||||||
@@ -395,7 +395,7 @@ impl<R: Read + Sized + Into<Stream>> PoolReturnRead<R> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn do_read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
|
fn do_read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
match self.reader.as_mut() {
|
match self.reader.as_mut() {
|
||||||
None => Ok(0),
|
None => Ok(0),
|
||||||
Some(reader) => reader.read(buf),
|
Some(reader) => reader.read(buf),
|
||||||
@@ -404,7 +404,7 @@ impl<R: Read + Sized + Into<Stream>> PoolReturnRead<R> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read + Sized + Into<Stream>> Read for PoolReturnRead<R> {
|
impl<R: Read + Sized + Into<Stream>> Read for PoolReturnRead<R> {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
let amount = self.do_read(buf)?;
|
let amount = self.do_read(buf)?;
|
||||||
// only if the underlying reader is exhausted can we send a new
|
// only if the underlying reader is exhausted can we send a new
|
||||||
// request to the same socket. hence, we only return it now.
|
// request to the same socket. hence, we only return it now.
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::io::{Cursor, Error as IoError, ErrorKind, Read, Result as IoResult};
|
use std::io::{self, Cursor, ErrorKind, Read};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
@@ -366,7 +366,7 @@ impl Response {
|
|||||||
///
|
///
|
||||||
/// I.e. `Content-Length: text/plain; charset=iso-8859-1` would be decoded in latin-1.
|
/// I.e. `Content-Length: text/plain; charset=iso-8859-1` would be decoded in latin-1.
|
||||||
///
|
///
|
||||||
pub fn into_string(self) -> IoResult<String> {
|
pub fn into_string(self) -> io::Result<String> {
|
||||||
#[cfg(feature = "charset")]
|
#[cfg(feature = "charset")]
|
||||||
{
|
{
|
||||||
let encoding = encoding_from_whatwg_label(self.charset())
|
let encoding = encoding_from_whatwg_label(self.charset())
|
||||||
@@ -400,22 +400,22 @@ impl Response {
|
|||||||
/// assert_eq!(json["hello"], "world");
|
/// assert_eq!(json["hello"], "world");
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(feature = "json")]
|
#[cfg(feature = "json")]
|
||||||
pub fn into_json(self) -> IoResult<serde_json::Value> {
|
pub fn into_json(self) -> io::Result<serde_json::Value> {
|
||||||
use crate::stream::io_err_timeout;
|
use crate::stream::io_err_timeout;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
let reader = self.into_reader();
|
let reader = self.into_reader();
|
||||||
serde_json::from_reader(reader).map_err(|e| {
|
serde_json::from_reader(reader).map_err(|e| {
|
||||||
// This is to unify TimedOut IoError in the API.
|
// This is to unify TimedOut io::Error in the API.
|
||||||
// We make a clone of the original error since serde_json::Error doesn't
|
// We make a clone of the original error since serde_json::Error doesn't
|
||||||
// let us get the wrapped error instance back.
|
// let us get the wrapped error instance back.
|
||||||
if let Some(ioe) = e.source().and_then(|s| s.downcast_ref::<IoError>()) {
|
if let Some(ioe) = e.source().and_then(|s| s.downcast_ref::<io::Error>()) {
|
||||||
if ioe.kind() == ErrorKind::TimedOut {
|
if ioe.kind() == ErrorKind::TimedOut {
|
||||||
return io_err_timeout(ioe.to_string());
|
return io_err_timeout(ioe.to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
IoError::new(
|
io::Error::new(
|
||||||
ErrorKind::InvalidData,
|
ErrorKind::InvalidData,
|
||||||
format!("Failed to read JSON: {}", e),
|
format!("Failed to read JSON: {}", e),
|
||||||
)
|
)
|
||||||
@@ -445,10 +445,10 @@ impl Response {
|
|||||||
/// assert_eq!(json.hello, "world");
|
/// assert_eq!(json.hello, "world");
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(feature = "json")]
|
#[cfg(feature = "json")]
|
||||||
pub fn into_json_deserialize<T: DeserializeOwned>(self) -> IoResult<T> {
|
pub fn into_json_deserialize<T: DeserializeOwned>(self) -> io::Result<T> {
|
||||||
let reader = self.into_reader();
|
let reader = self.into_reader();
|
||||||
serde_json::from_reader(reader).map_err(|e| {
|
serde_json::from_reader(reader).map_err(|e| {
|
||||||
IoError::new(
|
io::Error::new(
|
||||||
ErrorKind::InvalidData,
|
ErrorKind::InvalidData,
|
||||||
format!("Failed to read JSON: {}", e),
|
format!("Failed to read JSON: {}", e),
|
||||||
)
|
)
|
||||||
@@ -591,7 +591,7 @@ pub(crate) fn set_stream(resp: &mut Response, url: String, unit: Option<Unit>, s
|
|||||||
resp.stream = Some(stream);
|
resp.stream = Some(stream);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_next_line<R: Read>(reader: &mut R) -> IoResult<String> {
|
fn read_next_line<R: Read>(reader: &mut R) -> io::Result<String> {
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
let mut prev_byte_was_cr = false;
|
let mut prev_byte_was_cr = false;
|
||||||
let mut one = [0_u8];
|
let mut one = [0_u8];
|
||||||
@@ -600,7 +600,10 @@ fn read_next_line<R: Read>(reader: &mut R) -> IoResult<String> {
|
|||||||
let amt = reader.read(&mut one[..])?;
|
let amt = reader.read(&mut one[..])?;
|
||||||
|
|
||||||
if amt == 0 {
|
if amt == 0 {
|
||||||
return Err(IoError::new(ErrorKind::ConnectionAborted, "Unexpected EOF"));
|
return Err(io::Error::new(
|
||||||
|
ErrorKind::ConnectionAborted,
|
||||||
|
"Unexpected EOF",
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let byte = one[0];
|
let byte = one[0];
|
||||||
@@ -608,7 +611,7 @@ fn read_next_line<R: Read>(reader: &mut R) -> IoResult<String> {
|
|||||||
if byte == b'\n' && prev_byte_was_cr {
|
if byte == b'\n' && prev_byte_was_cr {
|
||||||
buf.pop(); // removing the '\r'
|
buf.pop(); // removing the '\r'
|
||||||
return String::from_utf8(buf)
|
return String::from_utf8(buf)
|
||||||
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "Header is not in ASCII"));
|
.map_err(|_| io::Error::new(ErrorKind::InvalidInput, "Header is not in ASCII"));
|
||||||
}
|
}
|
||||||
|
|
||||||
prev_byte_was_cr = byte == b'\r';
|
prev_byte_was_cr = byte == b'\r';
|
||||||
@@ -635,7 +638,7 @@ impl<R: Read> LimitedRead<R> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read> Read for LimitedRead<R> {
|
impl<R: Read> Read for LimitedRead<R> {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
let left = self.limit - self.position;
|
let left = self.limit - self.position;
|
||||||
if left == 0 {
|
if left == 0 {
|
||||||
return Ok(0);
|
return Ok(0);
|
||||||
@@ -651,7 +654,7 @@ impl<R: Read> Read for LimitedRead<R> {
|
|||||||
// the recipient times out before the indicated number of octets are
|
// the recipient times out before the indicated number of octets are
|
||||||
// received, the recipient MUST consider the message to be
|
// received, the recipient MUST consider the message to be
|
||||||
// incomplete and close the connection.
|
// incomplete and close the connection.
|
||||||
Ok(0) => Err(IoError::new(
|
Ok(0) => Err(io::Error::new(
|
||||||
ErrorKind::InvalidData,
|
ErrorKind::InvalidData,
|
||||||
"response body closed before all bytes were read",
|
"response body closed before all bytes were read",
|
||||||
)),
|
)),
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::io::{
|
use std::io::{self, BufRead, BufReader, Cursor, ErrorKind, Read, Write};
|
||||||
BufRead, BufReader, Cursor, Error as IoError, ErrorKind, Read, Result as IoResult, Write,
|
|
||||||
};
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::net::TcpStream;
|
use std::net::TcpStream;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -67,7 +65,7 @@ impl From<DeadlineStream> for Stream {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Read for DeadlineStream {
|
impl Read for DeadlineStream {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
if let Some(deadline) = self.deadline {
|
if let Some(deadline) = self.deadline {
|
||||||
let timeout = time_until_deadline(deadline)?;
|
let timeout = time_until_deadline(deadline)?;
|
||||||
if let Some(socket) = self.stream.socket() {
|
if let Some(socket) = self.stream.socket() {
|
||||||
@@ -90,7 +88,7 @@ impl Read for DeadlineStream {
|
|||||||
|
|
||||||
// If the deadline is in the future, return the remaining time until
|
// If the deadline is in the future, return the remaining time until
|
||||||
// then. Otherwise return a TimedOut error.
|
// then. Otherwise return a TimedOut error.
|
||||||
fn time_until_deadline(deadline: Instant) -> IoResult<Duration> {
|
fn time_until_deadline(deadline: Instant) -> io::Result<Duration> {
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
match deadline.checked_duration_since(now) {
|
match deadline.checked_duration_since(now) {
|
||||||
None => Err(io_err_timeout("timed out reading response".to_string())),
|
None => Err(io_err_timeout("timed out reading response".to_string())),
|
||||||
@@ -98,8 +96,8 @@ fn time_until_deadline(deadline: Instant) -> IoResult<Duration> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn io_err_timeout(error: String) -> IoError {
|
pub(crate) fn io_err_timeout(error: String) -> io::Error {
|
||||||
IoError::new(ErrorKind::TimedOut, error)
|
io::Error::new(ErrorKind::TimedOut, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for Stream {
|
impl fmt::Debug for Stream {
|
||||||
@@ -128,7 +126,7 @@ impl Stream {
|
|||||||
// connection: return true. If this returns WouldBlock (aka EAGAIN),
|
// connection: return true. If this returns WouldBlock (aka EAGAIN),
|
||||||
// that means the connection is still open: return false. Otherwise
|
// that means the connection is still open: return false. Otherwise
|
||||||
// return an error.
|
// return an error.
|
||||||
fn serverclosed_stream(stream: &std::net::TcpStream) -> IoResult<bool> {
|
fn serverclosed_stream(stream: &std::net::TcpStream) -> io::Result<bool> {
|
||||||
let mut buf = [0; 1];
|
let mut buf = [0; 1];
|
||||||
stream.set_nonblocking(true)?;
|
stream.set_nonblocking(true)?;
|
||||||
|
|
||||||
@@ -143,7 +141,7 @@ impl Stream {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
// Return true if the server has closed this connection.
|
// Return true if the server has closed this connection.
|
||||||
pub(crate) fn server_closed(&self) -> IoResult<bool> {
|
pub(crate) fn server_closed(&self) -> io::Result<bool> {
|
||||||
match self.socket() {
|
match self.socket() {
|
||||||
Some(socket) => Stream::serverclosed_stream(socket),
|
Some(socket) => Stream::serverclosed_stream(socket),
|
||||||
None => Ok(false),
|
None => Ok(false),
|
||||||
@@ -180,7 +178,7 @@ impl Stream {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Read for Stream {
|
impl Read for Stream {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
match self {
|
match self {
|
||||||
Stream::Http(sock) => sock.read(buf),
|
Stream::Http(sock) => sock.read(buf),
|
||||||
#[cfg(any(
|
#[cfg(any(
|
||||||
@@ -196,7 +194,7 @@ impl Read for Stream {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl BufRead for Stream {
|
impl BufRead for Stream {
|
||||||
fn fill_buf(&mut self) -> IoResult<&[u8]> {
|
fn fill_buf(&mut self) -> io::Result<&[u8]> {
|
||||||
match self {
|
match self {
|
||||||
Stream::Http(r) => r.fill_buf(),
|
Stream::Http(r) => r.fill_buf(),
|
||||||
#[cfg(any(
|
#[cfg(any(
|
||||||
@@ -239,7 +237,7 @@ where
|
|||||||
fn read_https(
|
fn read_https(
|
||||||
stream: &mut BufReader<StreamOwned<ClientSession, TcpStream>>,
|
stream: &mut BufReader<StreamOwned<ClientSession, TcpStream>>,
|
||||||
buf: &mut [u8],
|
buf: &mut [u8],
|
||||||
) -> IoResult<usize> {
|
) -> io::Result<usize> {
|
||||||
match stream.read(buf) {
|
match stream.read(buf) {
|
||||||
Ok(size) => Ok(size),
|
Ok(size) => Ok(size),
|
||||||
Err(ref e) if is_close_notify(e) => Ok(0),
|
Err(ref e) if is_close_notify(e) => Ok(0),
|
||||||
@@ -248,7 +246,7 @@ fn read_https(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(feature = "native-tls", not(feature = "tls")))]
|
#[cfg(all(feature = "native-tls", not(feature = "tls")))]
|
||||||
fn read_https(stream: &mut BufReader<TlsStream<TcpStream>>, buf: &mut [u8]) -> IoResult<usize> {
|
fn read_https(stream: &mut BufReader<TlsStream<TcpStream>>, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
match stream.read(buf) {
|
match stream.read(buf) {
|
||||||
Ok(size) => Ok(size),
|
Ok(size) => Ok(size),
|
||||||
Err(ref e) if is_close_notify(e) => Ok(0),
|
Err(ref e) if is_close_notify(e) => Ok(0),
|
||||||
@@ -273,7 +271,7 @@ fn is_close_notify(e: &std::io::Error) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Write for Stream {
|
impl Write for Stream {
|
||||||
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
match self {
|
match self {
|
||||||
Stream::Http(sock) => sock.get_mut().write(buf),
|
Stream::Http(sock) => sock.get_mut().write(buf),
|
||||||
#[cfg(any(
|
#[cfg(any(
|
||||||
@@ -286,7 +284,7 @@ impl Write for Stream {
|
|||||||
Stream::Test(_, writer) => writer.write(buf),
|
Stream::Test(_, writer) => writer.write(buf),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn flush(&mut self) -> IoResult<()> {
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
match self {
|
match self {
|
||||||
Stream::Http(sock) => sock.get_mut().flush(),
|
Stream::Http(sock) => sock.get_mut().flush(),
|
||||||
#[cfg(any(
|
#[cfg(any(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::io::{Result as IoResult, Write};
|
use std::io::{self, Write};
|
||||||
use std::time;
|
use std::time;
|
||||||
|
|
||||||
use qstring::QString;
|
use qstring::QString;
|
||||||
@@ -335,7 +335,7 @@ fn connect_socket(unit: &Unit, hostname: &str, use_pooled: bool) -> Result<(Stre
|
|||||||
|
|
||||||
/// Send request line + headers (all up until the body).
|
/// Send request line + headers (all up until the body).
|
||||||
#[allow(clippy::write_with_newline)]
|
#[allow(clippy::write_with_newline)]
|
||||||
fn send_prelude(unit: &Unit, stream: &mut Stream, redir: bool) -> IoResult<()> {
|
fn send_prelude(unit: &Unit, stream: &mut Stream, redir: bool) -> io::Result<()> {
|
||||||
//
|
//
|
||||||
|
|
||||||
// build into a buffer and send in one go.
|
// build into a buffer and send in one go.
|
||||||
|
|||||||
Reference in New Issue
Block a user