1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 07:53:00 +01:00

fmt & clippy

This commit is contained in:
Nikolay Kim 2019-09-12 21:52:46 +06:00
parent 45d2fd4299
commit 60b7aebd0a
15 changed files with 95 additions and 62 deletions

View File

@ -66,7 +66,7 @@ hashbrown = "0.5.0"
h2 = "0.1.16" h2 = "0.1.16"
http = "0.1.17" http = "0.1.17"
httparse = "1.3" httparse = "1.3"
indexmap = "1.0" indexmap = "1.2"
lazy_static = "1.0" lazy_static = "1.0"
language-tags = "0.2" language-tags = "0.2"
log = "0.4" log = "0.4"

View File

@ -147,4 +147,4 @@ impl From<FreezeRequestError> for SendRequestError {
FreezeRequestError::Http(e) => e.into(), FreezeRequestError::Http(e) => e.into(),
} }
} }
} }

View File

@ -8,10 +8,10 @@ use futures::{Async, Future, Poll, Sink, Stream};
use crate::error::PayloadError; use crate::error::PayloadError;
use crate::h1; use crate::h1;
use crate::header::HeaderMap;
use crate::http::header::{IntoHeaderValue, HOST}; use crate::http::header::{IntoHeaderValue, HOST};
use crate::message::{RequestHeadType, ResponseHead}; use crate::message::{RequestHeadType, ResponseHead};
use crate::payload::{Payload, PayloadStream}; use crate::payload::{Payload, PayloadStream};
use crate::header::HeaderMap;
use super::connection::{ConnectionLifetime, ConnectionType, IoConnection}; use super::connection::{ConnectionLifetime, ConnectionType, IoConnection};
use super::error::{ConnectError, SendRequestError}; use super::error::{ConnectError, SendRequestError};
@ -30,7 +30,9 @@ where
B: MessageBody, B: MessageBody,
{ {
// set request host header // set request host header
if !head.as_ref().headers.contains_key(HOST) && !head.extra_headers().iter().any(|h| h.contains_key(HOST)) { if !head.as_ref().headers.contains_key(HOST)
&& !head.extra_headers().iter().any(|h| h.contains_key(HOST))
{
if let Some(host) = head.as_ref().uri.host() { if let Some(host) = head.as_ref().uri.host() {
let mut wrt = BytesMut::with_capacity(host.len() + 5).writer(); let mut wrt = BytesMut::with_capacity(host.len() + 5).writer();
@ -40,20 +42,16 @@ where
}; };
match wrt.get_mut().take().freeze().try_into() { match wrt.get_mut().take().freeze().try_into() {
Ok(value) => { Ok(value) => match head {
match head { RequestHeadType::Owned(ref mut head) => {
RequestHeadType::Owned(ref mut head) => { head.headers.insert(HOST, value)
head.headers.insert(HOST, value)
},
RequestHeadType::Rc(_, ref mut extra_headers) => {
let headers = extra_headers.get_or_insert(HeaderMap::new());
headers.insert(HOST, value)
},
} }
} RequestHeadType::Rc(_, ref mut extra_headers) => {
Err(e) => { let headers = extra_headers.get_or_insert(HeaderMap::new());
log::error!("Can not set HOST header {}", e) headers.insert(HOST, value)
} }
},
Err(e) => log::error!("Can not set HOST header {}", e),
} }
} }
} }

View File

@ -9,9 +9,9 @@ use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
use http::{request::Request, HttpTryFrom, Method, Version}; use http::{request::Request, HttpTryFrom, Method, Version};
use crate::body::{BodySize, MessageBody}; use crate::body::{BodySize, MessageBody};
use crate::header::HeaderMap;
use crate::message::{RequestHeadType, ResponseHead}; use crate::message::{RequestHeadType, ResponseHead};
use crate::payload::Payload; use crate::payload::Payload;
use crate::header::HeaderMap;
use super::connection::{ConnectionType, IoConnection}; use super::connection::{ConnectionType, IoConnection};
use super::error::SendRequestError; use super::error::SendRequestError;
@ -69,15 +69,21 @@ where
// Extracting extra headers from RequestHeadType. HeaderMap::new() does not allocate. // Extracting extra headers from RequestHeadType. HeaderMap::new() does not allocate.
let (head, extra_headers) = match head { let (head, extra_headers) = match head {
RequestHeadType::Owned(head) => (RequestHeadType::Owned(head), HeaderMap::new()), RequestHeadType::Owned(head) => {
RequestHeadType::Rc(head, extra_headers) => (RequestHeadType::Rc(head, None), extra_headers.unwrap_or(HeaderMap::new())), (RequestHeadType::Owned(head), HeaderMap::new())
}
RequestHeadType::Rc(head, extra_headers) => (
RequestHeadType::Rc(head, None),
extra_headers.unwrap_or_else(HeaderMap::new),
),
}; };
// merging headers from head and extra headers. // merging headers from head and extra headers.
let headers = head.as_ref().headers.iter() let headers = head
.filter(|(name, _)| { .as_ref()
!extra_headers.contains_key(*name) .headers
}) .iter()
.filter(|(name, _)| !extra_headers.contains_key(*name))
.chain(extra_headers.iter()); .chain(extra_headers.iter());
// copy headers // copy headers

View File

@ -10,7 +10,7 @@ mod pool;
pub use self::connection::Connection; pub use self::connection::Connection;
pub use self::connector::Connector; pub use self::connector::Connector;
pub use self::error::{ConnectError, InvalidUrl, SendRequestError, FreezeRequestError}; pub use self::error::{ConnectError, FreezeRequestError, InvalidUrl, SendRequestError};
pub use self::pool::Protocol; pub use self::pool::Protocol;
#[derive(Clone)] #[derive(Clone)]

View File

@ -326,7 +326,7 @@ impl<Io> Inner<Io> {
fn release_waiter(&mut self, key: &Key, token: usize) { fn release_waiter(&mut self, key: &Key, token: usize) {
self.waiters.remove(token); self.waiters.remove(token);
self.waiters_queue.remove(&(key.clone(), token)); let _ = self.waiters_queue.shift_remove(&(key.clone(), token));
} }
} }

View File

@ -16,9 +16,11 @@ use super::{Message, MessageType};
use crate::body::BodySize; use crate::body::BodySize;
use crate::config::ServiceConfig; use crate::config::ServiceConfig;
use crate::error::{ParseError, PayloadError}; use crate::error::{ParseError, PayloadError};
use crate::helpers;
use crate::message::{ConnectionType, Head, MessagePool, RequestHead, RequestHeadType, ResponseHead};
use crate::header::HeaderMap; use crate::header::HeaderMap;
use crate::helpers;
use crate::message::{
ConnectionType, Head, MessagePool, RequestHead, RequestHeadType, ResponseHead,
};
bitflags! { bitflags! {
struct Flags: u8 { struct Flags: u8 {
@ -197,7 +199,9 @@ impl Encoder for ClientCodec {
Message::Item((mut head, length)) => { Message::Item((mut head, length)) => {
let inner = &mut self.inner; let inner = &mut self.inner;
inner.version = head.as_ref().version; inner.version = head.as_ref().version;
inner.flags.set(Flags::HEAD, head.as_ref().method == Method::HEAD); inner
.flags
.set(Flags::HEAD, head.as_ref().method == Method::HEAD);
// connection status // connection status
inner.ctype = match head.as_ref().connection_type() { inner.ctype = match head.as_ref().connection_type() {

View File

@ -2,9 +2,9 @@
use std::fmt::Write as FmtWrite; use std::fmt::Write as FmtWrite;
use std::io::Write; use std::io::Write;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::rc::Rc;
use std::str::FromStr; use std::str::FromStr;
use std::{cmp, fmt, io, mem}; use std::{cmp, fmt, io, mem};
use std::rc::Rc;
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
@ -16,7 +16,7 @@ use crate::http::header::{
HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING,
}; };
use crate::http::{HeaderMap, Method, StatusCode, Version}; use crate::http::{HeaderMap, Method, StatusCode, Version};
use crate::message::{ConnectionType, Head, RequestHead, ResponseHead, RequestHeadType}; use crate::message::{ConnectionType, Head, RequestHead, RequestHeadType, ResponseHead};
use crate::request::Request; use crate::request::Request;
use crate::response::Response; use crate::response::Response;
@ -134,10 +134,11 @@ pub(crate) trait MessageType: Sized {
// merging headers from head and extra headers. HeaderMap::new() does not allocate. // merging headers from head and extra headers. HeaderMap::new() does not allocate.
let empty_headers = HeaderMap::new(); let empty_headers = HeaderMap::new();
let extra_headers = self.extra_headers().unwrap_or(&empty_headers); let extra_headers = self.extra_headers().unwrap_or(&empty_headers);
let headers = self.headers().inner.iter() let headers = self
.filter(|(name, _)| { .headers()
!extra_headers.contains_key(*name) .inner
}) .iter()
.filter(|(name, _)| !extra_headers.contains_key(*name))
.chain(extra_headers.inner.iter()); .chain(extra_headers.inner.iter());
// write headers // write headers
@ -604,10 +605,16 @@ mod tests {
let mut bytes = BytesMut::with_capacity(2048); let mut bytes = BytesMut::with_capacity(2048);
let mut head = RequestHead::default(); let mut head = RequestHead::default();
head.headers.insert(AUTHORIZATION, HeaderValue::from_static("some authorization")); head.headers.insert(
AUTHORIZATION,
HeaderValue::from_static("some authorization"),
);
let mut extra_headers = HeaderMap::new(); let mut extra_headers = HeaderMap::new();
extra_headers.insert(AUTHORIZATION,HeaderValue::from_static("another authorization")); extra_headers.insert(
AUTHORIZATION,
HeaderValue::from_static("another authorization"),
);
extra_headers.insert(DATE, HeaderValue::from_static("date")); extra_headers.insert(DATE, HeaderValue::from_static("date"));
let mut head = RequestHeadType::Rc(Rc::new(head), Some(extra_headers)); let mut head = RequestHeadType::Rc(Rc::new(head), Some(extra_headers));

View File

@ -178,13 +178,15 @@ impl InnerMultipart {
Some(chunk) => { Some(chunk) => {
if chunk.len() < boundary.len() + 4 if chunk.len() < boundary.len() + 4
|| &chunk[..2] != b"--" || &chunk[..2] != b"--"
|| &chunk[2..boundary.len() + 2] != boundary.as_bytes() { || &chunk[2..boundary.len() + 2] != boundary.as_bytes()
{
Err(MultipartError::Boundary) Err(MultipartError::Boundary)
} else if &chunk[boundary.len() + 2..] == b"\r\n" { } else if &chunk[boundary.len() + 2..] == b"\r\n" {
Ok(Some(false)) Ok(Some(false))
} else if &chunk[boundary.len() + 2..boundary.len() + 4] == b"--" } else if &chunk[boundary.len() + 2..boundary.len() + 4] == b"--"
&& (chunk.len() == boundary.len() + 4 && (chunk.len() == boundary.len() + 4
|| &chunk[boundary.len() + 4..] == b"\r\n") { || &chunk[boundary.len() + 4..] == b"\r\n")
{
Ok(Some(true)) Ok(Some(true))
} else { } else {
Err(MultipartError::Boundary) Err(MultipartError::Boundary)
@ -781,8 +783,10 @@ impl PayloadBuffer {
/// Read bytes until new line delimiter or eof /// Read bytes until new line delimiter or eof
pub fn readline_or_eof(&mut self) -> Result<Option<Bytes>, MultipartError> { pub fn readline_or_eof(&mut self) -> Result<Option<Bytes>, MultipartError> {
match self.readline() { match self.readline() {
Err(MultipartError::Incomplete) if self.eof => Ok(Some(self.buf.take().freeze())), Err(MultipartError::Incomplete) if self.eof => {
line => line Ok(Some(self.buf.take().freeze()))
}
line => line,
} }
} }
@ -859,14 +863,14 @@ mod tests {
fn create_simple_request_with_header() -> (Bytes, HeaderMap) { fn create_simple_request_with_header() -> (Bytes, HeaderMap) {
let bytes = Bytes::from( let bytes = Bytes::from(
"testasdadsad\r\n\ "testasdadsad\r\n\
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\ Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\ Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
test\r\n\ test\r\n\
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\ Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
data\r\n\ data\r\n\
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n" --abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
); );
let mut headers = HeaderMap::new(); let mut headers = HeaderMap::new();
headers.insert( headers.insert(

View File

@ -1,5 +1,5 @@
use std::{fmt, io, net};
use std::rc::Rc; use std::rc::Rc;
use std::{fmt, io, net};
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_http::body::Body; use actix_http::body::Body;
@ -7,8 +7,8 @@ use actix_http::client::{
Connect as ClientConnect, ConnectError, Connection, SendRequestError, Connect as ClientConnect, ConnectError, Connection, SendRequestError,
}; };
use actix_http::h1::ClientCodec; use actix_http::h1::ClientCodec;
use actix_http::{RequestHead, RequestHeadType, ResponseHead};
use actix_http::http::HeaderMap; use actix_http::http::HeaderMap;
use actix_http::{RequestHead, RequestHeadType, ResponseHead};
use actix_service::Service; use actix_service::Service;
use futures::{Future, Poll}; use futures::{Future, Poll};
@ -82,7 +82,9 @@ where
}) })
.from_err() .from_err()
// send request // send request
.and_then(move |connection| connection.send_request(RequestHeadType::from(head), body)) .and_then(move |connection| {
connection.send_request(RequestHeadType::from(head), body)
})
.map(|(head, payload)| ClientResponse::new(head, payload)), .map(|(head, payload)| ClientResponse::new(head, payload)),
) )
} }
@ -103,7 +105,10 @@ where
}) })
.from_err() .from_err()
// send request // send request
.and_then(move |connection| connection.send_request(RequestHeadType::Rc(head, extra_headers), body)) .and_then(move |connection| {
connection
.send_request(RequestHeadType::Rc(head, extra_headers), body)
})
.map(|(head, payload)| ClientResponse::new(head, payload)), .map(|(head, payload)| ClientResponse::new(head, payload)),
) )
} }
@ -127,7 +132,9 @@ where
}) })
.from_err() .from_err()
// send request // send request
.and_then(move |connection| connection.open_tunnel(RequestHeadType::from(head))) .and_then(move |connection| {
connection.open_tunnel(RequestHeadType::from(head))
})
.map(|(head, framed)| { .map(|(head, framed)| {
let framed = framed.map_io(|io| BoxedSocket(Box::new(Socket(io)))); let framed = framed.map_io(|io| BoxedSocket(Box::new(Socket(io))));
(head, framed) (head, framed)
@ -155,7 +162,9 @@ where
}) })
.from_err() .from_err()
// send request // send request
.and_then(move |connection| connection.open_tunnel(RequestHeadType::Rc(head, extra_headers))) .and_then(move |connection| {
connection.open_tunnel(RequestHeadType::Rc(head, extra_headers))
})
.map(|(head, framed)| { .map(|(head, framed)| {
let framed = framed.map_io(|io| BoxedSocket(Box::new(Socket(io)))); let framed = framed.map_io(|io| BoxedSocket(Box::new(Socket(io))));
(head, framed) (head, framed)

View File

@ -1,5 +1,7 @@
//! Http client errors //! Http client errors
pub use actix_http::client::{ConnectError, InvalidUrl, SendRequestError, FreezeRequestError}; pub use actix_http::client::{
ConnectError, FreezeRequestError, InvalidUrl, SendRequestError,
};
pub use actix_http::error::PayloadError; pub use actix_http::error::PayloadError;
pub use actix_http::ws::HandshakeError as WsHandshakeError; pub use actix_http::ws::HandshakeError as WsHandshakeError;
pub use actix_http::ws::ProtocolError as WsProtocolError; pub use actix_http::ws::ProtocolError as WsProtocolError;

View File

@ -90,7 +90,7 @@ impl Future for SendClientRequest {
Ok(Async::Ready(res)) Ok(Async::Ready(res))
} }
SendClientRequest::Err(ref mut e) => match e.take() { SendClientRequest::Err(ref mut e) => match e.take() {
Some(e) => Err(e.into()), Some(e) => Err(e),
None => panic!("Attempting to call completed future"), None => panic!("Attempting to call completed future"),
}, },
} }
@ -153,7 +153,7 @@ impl RequestSender {
SendClientRequest::new( SendClientRequest::new(
fut, fut,
response_decompress, response_decompress,
timeout.or_else(|| config.timeout.clone()), timeout.or_else(|| config.timeout),
) )
} }

View File

@ -234,7 +234,10 @@ impl WebsocketsRequest {
} }
if !self.head.headers.contains_key(header::HOST) { if !self.head.headers.contains_key(header::HOST) {
self.head.headers.insert(header::HOST, HeaderValue::from_str(uri.host().unwrap()).unwrap()); self.head.headers.insert(
header::HOST,
HeaderValue::from_str(uri.host().unwrap()).unwrap(),
);
} }
// set cookies // set cookies

View File

@ -169,7 +169,7 @@ where
match self.data_factories_fut[idx].poll()? { match self.data_factories_fut[idx].poll()? {
Async::Ready(f) => { Async::Ready(f) => {
self.data_factories.push(f); self.data_factories.push(f);
self.data_factories_fut.remove(idx); let _ = self.data_factories_fut.remove(idx);
} }
Async::NotReady => idx += 1, Async::NotReady => idx += 1,
} }

View File

@ -2,13 +2,13 @@
mod compress; mod compress;
pub use self::compress::{BodyEncoding, Compress}; pub use self::compress::{BodyEncoding, Compress};
mod condition;
mod defaultheaders; mod defaultheaders;
pub mod errhandlers; pub mod errhandlers;
mod logger; mod logger;
mod normalize; mod normalize;
mod condition;
pub use self::condition::Condition;
pub use self::defaultheaders::DefaultHeaders; pub use self::defaultheaders::DefaultHeaders;
pub use self::logger::Logger; pub use self::logger::Logger;
pub use self::normalize::NormalizePath; pub use self::normalize::NormalizePath;
pub use self::condition::Condition;