update and tidy code

This commit is contained in:
Daniel Eades
2019-08-07 20:44:24 +01:00
committed by Sean McArthur
parent 86d9cbc66e
commit 5dc5162765
14 changed files with 46 additions and 55 deletions

View File

@@ -9,6 +9,7 @@ authors = ["Sean McArthur <sean@seanmonstar.com>"]
readme = "README.md"
license = "MIT/Apache-2.0"
categories = ["web-programming::http-client"]
edition = "2018"
publish = false

View File

@@ -42,7 +42,7 @@ use crate::{Certificate, Identity};
#[cfg(feature = "tls")]
use crate::tls::TlsBackend;
static DEFAULT_USER_AGENT: &'static str =
static DEFAULT_USER_AGENT: &str =
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
/// An asynchronous `Client` to make Requests with.
@@ -101,7 +101,7 @@ impl ClientBuilder {
ClientBuilder {
config: Config {
gzip: true,
headers: headers,
headers,
#[cfg(feature = "default-tls")]
hostname_verification: true,
#[cfg(feature = "tls")]
@@ -338,7 +338,7 @@ impl ClientBuilder {
pub fn use_sys_proxy(mut self) -> ClientBuilder {
let proxies = get_proxies();
self.config.proxies.push(Proxy::custom(move |url| {
return if proxies.contains_key(url.scheme()) {
if proxies.contains_key(url.scheme()) {
Some((*proxies.get(url.scheme()).unwrap()).clone())
} else {
None
@@ -610,16 +610,16 @@ impl Client {
Pending {
inner: PendingInner::Request(PendingRequest {
method: method,
url: url,
headers: headers,
method,
url,
headers,
body: reusable,
urls: Vec::new(),
client: self.inner.clone(),
in_flight: in_flight,
in_flight,
timeout,
}),
}
@@ -644,14 +644,11 @@ impl Client {
for proxy in self.inner.proxies.iter() {
if proxy.is_match(dst) {
match proxy.http_basic_auth(dst) {
Some(header) => {
if let Some(header) = proxy.http_basic_auth(dst) {
headers.insert(
PROXY_AUTHORIZATION,
header,
);
},
None => (),
}
break;

View File

@@ -117,12 +117,12 @@ impl Decoder {
content_encoding_gzip = headers
.get_all(CONTENT_ENCODING)
.iter()
.fold(false, |acc, enc| acc || enc == "gzip");
.any(|enc| enc == "gzip");
content_encoding_gzip ||
headers
.get_all(TRANSFER_ENCODING)
.iter()
.fold(false, |acc, enc| acc || enc == "gzip")
.any(|enc| enc == "gzip")
};
if is_gzip {
if let Some(content_length) = headers.get(CONTENT_LENGTH) {
@@ -264,7 +264,7 @@ impl<S> ReadableChunks<S> {
pub(crate) fn new(stream: S) -> Self {
ReadableChunks {
state: ReadState::NotReady,
stream: stream,
stream,
}
}
}

View File

@@ -61,7 +61,7 @@ impl Form {
/// # Examples
///
/// ```
/// let form = reqwest::async::multipart::Form::new()
/// let form = reqwest::r#async::multipart::Form::new()
/// .text("username", "seanmonstar")
/// .text("password", "secret");
/// ```
@@ -98,7 +98,7 @@ impl Form {
/// Consume this instance and transform into an instance of hyper::Body for use in a request.
pub(crate) fn stream(mut self) -> hyper::Body {
if self.inner.fields.len() == 0 {
if self.inner.fields.is_empty(){
return hyper::Body::empty();
}

View File

@@ -201,8 +201,8 @@ impl RequestBuilder {
/// # use futures::future::Future;
///
/// # fn run() -> Result<(), Error> {
/// let client = reqwest::async::Client::new();
/// let form = reqwest::async::multipart::Form::new()
/// let client = reqwest::r#async::Client::new();
/// let form = reqwest::r#async::multipart::Form::new()
/// .text("key3", "value3")
/// .text("key4", "value4");
///

View File

@@ -184,7 +184,7 @@ impl Response {
/// # Example
///
/// ```
/// # use reqwest::async::Response;
/// # use reqwest::r#async::Response;
/// fn on_response(res: Response) {
/// match res.error_for_status() {
/// Ok(_res) => (),
@@ -214,7 +214,7 @@ impl Response {
/// # Example
///
/// ```
/// # use reqwest::async::Response;
/// # use reqwest::r#async::Response;
/// fn on_response(res: &Response) {
/// match res.error_for_status_ref() {
/// Ok(_res) => (),
@@ -263,7 +263,7 @@ impl<T: Into<Body>> From<http::Response<T>> for Response {
status: parts.status,
headers: parts.headers,
url: Box::new(url),
body: body,
body,
version: parts.version,
extensions: parts.extensions,
}
@@ -307,10 +307,7 @@ impl Future for Text {
// a block because of borrow checker
{
let (text, _, _) = self.encoding.decode(&bytes);
match text {
Cow::Owned(s) => return Ok(Async::Ready(s)),
_ => (),
}
if let Cow::Owned(s) = text { return Ok(Async::Ready(s)) }
}
unsafe {
// decoding returned Cow::Borrowed, meaning these bytes
@@ -339,8 +336,8 @@ pub trait ResponseBuilderExt {
/// # use std::error::Error;
/// use url::Url;
/// use http::response::Builder;
/// use reqwest::async::ResponseBuilderExt;
/// # fn main() -> Result<(), Box<Error>> {
/// use reqwest::r#async::ResponseBuilderExt;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let response = Builder::new()
/// .status(200)
/// .url(Url::parse("http://example.com")?)

View File

@@ -99,7 +99,7 @@ impl Body {
let (tx, rx) = hyper::Body::channel();
let tx = Sender {
body: (read, len),
tx: tx,
tx,
};
(Some(tx), async_impl::Body::wrap(rx), len)
},
@@ -250,7 +250,7 @@ impl Sender {
// input stream as soon as the data received is valid JSON.
// This behaviour is questionable, but it exists and the
// fact is that there is actually no remaining data to read.
if buf.len() == 0 {
if buf.is_empty() {
if buf.remaining_mut() == 0 {
buf.reserve(8192);
}
@@ -285,7 +285,7 @@ impl Sender {
written += buf.len() as u64;
let tx = tx.as_mut().expect("tx only taken on error");
if let Err(_) = tx.send_data(buf.take().freeze().into()) {
if tx.send_data(buf.take().freeze().into()).is_err() {
return Err(crate::error::timedout(None));
}
})

View File

@@ -561,7 +561,7 @@ impl ClientHandle {
let (mut rt, client) = match built {
Ok((rt, c)) => {
if let Err(_) = spawn_tx.send(Ok(())) {
if spawn_tx.send(Ok(())).is_err() {
return;
}
(rt, c)
@@ -626,7 +626,7 @@ impl ClientHandle {
Ok(ClientHandle {
timeout: timeout,
timeout,
inner: inner_handle,
})
}

View File

@@ -394,14 +394,11 @@ fn tunnel<T>(conn: T, host: String, port: u16, auth: Option<::http::header::Head
Host: {0}:{1}\r\n\
", host, port).into_bytes();
match auth {
Some(value) => {
if let Some(value) = auth {
debug!("tunnel to {}:{} using basic auth", host, port);
buf.extend_from_slice(b"Proxy-Authorization: ");
buf.extend_from_slice(value.as_bytes());
buf.extend_from_slice(b"\r\n");
},
None => (),
}
// headers end
@@ -699,7 +696,7 @@ mod tests {
use super::tunnel;
use crate::proxy;
static TUNNEL_OK: &'static [u8] = b"\
static TUNNEL_OK: &[u8] = b"\
HTTP/1.1 200 OK\r\n\
\r\n\
";

View File

@@ -248,7 +248,7 @@ impl fmt::Debug for Error {
}
}
static BLOCK_IN_FUTURE: &'static str = "blocking Client used inside a Future context";
static BLOCK_IN_FUTURE: &str = "blocking Client used inside a Future context";
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

View File

@@ -296,7 +296,7 @@ impl fmt::Debug for Reader {
impl Reader {
fn new(form: Form) -> Reader {
let mut reader = Reader {
form: form,
form,
active_reader: None,
};
reader.next_reader();
@@ -304,13 +304,13 @@ impl Reader {
}
fn next_reader(&mut self) {
self.active_reader = if self.form.inner.fields.len() != 0 {
self.active_reader = if !self.form.inner.fields.is_empty() {
// We need to move out of the vector here because we are consuming the field's reader
let (name, field) = self.form.inner.fields.remove(0);
let boundary = Cursor::new(format!("--{}\r\n", self.form.boundary()));
let header = Cursor::new({
// Try to use cached headers created by compute_length
let mut h = if self.form.inner.computed_headers.len() > 0 {
let mut h = if !self.form.inner.computed_headers.is_empty() {
self.form.inner.computed_headers.remove(0)
} else {
self.form.inner.percent_encoding.encode_headers(&name, field.metadata())
@@ -324,7 +324,7 @@ impl Reader {
.chain(Cursor::new("\r\n"));
// According to https://tools.ietf.org/html/rfc2046#section-5.1.1
// the very last field has a special boundary
if self.form.inner.fields.len() != 0 {
if !self.form.inner.fields.is_empty() {
Some(Box::new(reader))
} else {
Some(Box::new(reader.chain(Cursor::new(
@@ -352,7 +352,7 @@ impl Read for Reader {
}
None => return Ok(total_bytes_read),
};
if last_read_bytes == 0 && buf.len() != 0 {
if last_read_bytes == 0 && !buf.is_empty() {
self.next_reader();
}
}

View File

@@ -397,8 +397,7 @@ impl Custom {
uri.scheme(),
uri.host(),
uri.port().map(|_| ":").unwrap_or(""),
uri.port().map(|p| p.to_string()).unwrap_or(String::new())
)
uri.port().map(|p| p.to_string()).unwrap_or_default())
.parse()
.expect("should be valid Url");
@@ -517,7 +516,7 @@ fn get_from_environment() -> HashMap<String, Url> {
if key.ends_with(PROXY_KEY_ENDS) {
let end_indx = key.len() - PROXY_KEY_ENDS.len();
let schema = &key[..end_indx];
insert_proxy(&mut proxies, String::from(schema), String::from(value));
insert_proxy(&mut proxies, String::from(schema), value);
}
}
proxies

View File

@@ -149,9 +149,9 @@ impl RedirectPolicy {
) -> Action {
self
.redirect(RedirectAttempt {
status: status,
next: next,
previous: previous,
status,
next,
previous,
})
.inner
}

View File

@@ -20,7 +20,7 @@ pub(crate) fn stream<S>(stream: S, timeout: Option<Duration>) -> WaitStream<S>
where S: Stream {
WaitStream {
stream: executor::spawn(stream),
timeout: timeout,
timeout,
}
}