From e9121025b7abde064124584118c7689a3e5b519e Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Thu, 6 Dec 2018 14:32:52 -0800 Subject: [PATCH] convert to 2018 edition --- Cargo.toml | 1 + examples/echo.rs | 6 ++- examples/echo2.rs | 3 +- examples/framed_hello.rs | 3 +- examples/hello-world.rs | 6 ++- src/body.rs | 2 +- src/client/connector.rs | 21 ++++------ src/client/error.rs | 13 ++----- src/client/pipeline.rs | 26 +++++++------ src/client/request.rs | 24 ++++++------ src/client/response.rs | 8 ++-- src/config.rs | 9 +++-- src/error.rs | 7 ++-- src/h1/client.rs | 21 +++++----- src/h1/codec.rs | 19 ++++----- src/h1/decoder.rs | 21 +++++----- src/h1/dispatcher.rs | 22 +++++------ src/h1/encoder.rs | 20 +++++----- src/h1/mod.rs | 2 +- src/h1/service.rs | 21 +++++----- src/header.rs | 9 ++--- src/httpcodes.rs | 3 +- src/httpmessage.rs | 39 ++++++++++++------- src/json.rs | 22 +++++++---- src/lib.rs | 83 +++++++++------------------------------- src/message.rs | 4 +- src/payload.rs | 26 ++++++++----- src/request.rs | 9 ++--- src/response.rs | 11 +++--- src/service.rs | 22 ++++++----- src/test.rs | 14 +++---- src/ws/client/connect.rs | 5 +-- src/ws/client/error.rs | 9 ++--- src/ws/client/service.rs | 11 +++--- src/ws/frame.rs | 7 ++-- src/ws/mod.rs | 47 +++++++++++++++-------- src/ws/service.rs | 4 +- tests/test_client.rs | 3 +- tests/test_server.rs | 18 ++++++--- tests/test_ws.rs | 3 +- 40 files changed, 310 insertions(+), 294 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b1dd69ac..57ed3f9b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ categories = ["network-programming", "asynchronous", "web-programming::websocket"] license = "MIT/Apache-2.0" exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] +edition = "2018" [package.metadata.docs.rs] features = ["session"] diff --git a/examples/echo.rs b/examples/echo.rs index c98863e5..0453ad6a 100644 --- a/examples/echo.rs +++ b/examples/echo.rs @@ -34,7 +34,9 @@ fn main() { res.header("x-head", HeaderValue::from_static("dummy value!")); Ok(res.body(bytes)) }) - }).map(|_| ()) - }).unwrap() + }) + .map(|_| ()) + }) + .unwrap() .run(); } diff --git a/examples/echo2.rs b/examples/echo2.rs index 4c144b43..3206ff50 100644 --- a/examples/echo2.rs +++ b/examples/echo2.rs @@ -37,6 +37,7 @@ fn main() { .server_hostname("localhost") .finish(|_req: Request| handle_request(_req)) .map(|_| ()) - }).unwrap() + }) + .unwrap() .run(); } diff --git a/examples/framed_hello.rs b/examples/framed_hello.rs index 0c9175a9..6c53d27f 100644 --- a/examples/framed_hello.rs +++ b/examples/framed_hello.rs @@ -29,6 +29,7 @@ fn main() { .map_err(|_| ()) .map(|_| ()) }) - }).unwrap() + }) + .unwrap() .run(); } diff --git a/examples/hello-world.rs b/examples/hello-world.rs index 74ff509b..b477f191 100644 --- a/examples/hello-world.rs +++ b/examples/hello-world.rs @@ -29,7 +29,9 @@ fn main() { let mut res = Response::Ok(); res.header("x-head", HeaderValue::from_static("dummy value!")); future::ok::<_, ()>(res.body("Hello world!")) - }).map(|_| ()) - }).unwrap() + }) + .map(|_| ()) + }) + .unwrap() .run(); } diff --git a/src/body.rs b/src/body.rs index cc4e77af..4b71e9bb 100644 --- a/src/body.rs +++ b/src/body.rs @@ -4,7 +4,7 @@ use std::{fmt, mem}; use bytes::{Bytes, BytesMut}; use futures::{Async, Poll, Stream}; -use error::{Error, PayloadError}; +use crate::error::{Error, PayloadError}; /// Type represent streaming payload pub type PayloadStream = Box>; diff --git a/src/client/connector.rs b/src/client/connector.rs index 9d084154..74ee6a7e 100644 --- a/src/client/connector.rs +++ b/src/client/connector.rs @@ -143,7 +143,8 @@ impl Connector { self.resolver .map_err(ConnectorError::from) .and_then(TcpConnector::default().from_err()), - ).map_err(|e| match e { + ) + .map_err(|e| match e { TimeoutError::Service(e) => e, TimeoutError::Timeout => ConnectorError::Timeout, }); @@ -170,7 +171,8 @@ impl Connector { OpensslConnector::service(self.connector) .map_err(ConnectorError::SslError), ), - ).map_err(|e| match e { + ) + .map_err(|e| match e { TimeoutError::Service(e) => e, TimeoutError::Timeout => ConnectorError::Timeout, }); @@ -180,7 +182,8 @@ impl Connector { self.resolver .map_err(ConnectorError::from) .and_then(TcpConnector::default().from_err()), - ).map_err(|e| match e { + ) + .map_err(|e| match e { TimeoutError::Service(e) => e, TimeoutError::Timeout => ConnectorError::Timeout, }); @@ -271,16 +274,8 @@ mod connect_impl { where Io1: AsyncRead + AsyncWrite + 'static, Io2: AsyncRead + AsyncWrite + 'static, - T1: Service< - Connect, - Response = (Connect, Io1), - Error = ConnectorError, - >, - T2: Service< - Connect, - Response = (Connect, Io2), - Error = ConnectorError, - >, + T1: Service, + T2: Service, { pub(crate) tcp_pool: ConnectionPool, pub(crate) ssl_pool: ConnectionPool, diff --git a/src/client/error.rs b/src/client/error.rs index 2c475364..d2a0f38e 100644 --- a/src/client/error.rs +++ b/src/client/error.rs @@ -1,23 +1,18 @@ use std::io; +use failure::Fail; use trust_dns_resolver::error::ResolveError; #[cfg(feature = "ssl")] use openssl::ssl::Error as SslError; -#[cfg(all( - feature = "tls", - not(any(feature = "ssl", feature = "rust-tls")) -))] +#[cfg(all(feature = "tls", not(any(feature = "ssl", feature = "rust-tls"))))] use native_tls::Error as SslError; -#[cfg(all( - feature = "rust-tls", - not(any(feature = "tls", feature = "ssl")) -))] +#[cfg(all(feature = "rust-tls", not(any(feature = "tls", feature = "ssl"))))] use std::io::Error as SslError; -use error::{Error, ParseError}; +use crate::error::{Error, ParseError}; /// A set of errors that can occur while connecting to an HTTP host #[derive(Fail, Debug)] diff --git a/src/client/pipeline.rs b/src/client/pipeline.rs index e7526550..fc1e53e8 100644 --- a/src/client/pipeline.rs +++ b/src/client/pipeline.rs @@ -10,10 +10,10 @@ use tokio_io::{AsyncRead, AsyncWrite}; use super::error::{ConnectorError, SendRequestError}; use super::response::ClientResponse; use super::{Connect, Connection}; -use body::{BodyLength, MessageBody, PayloadStream}; -use error::PayloadError; -use h1; -use message::RequestHead; +use crate::body::{BodyLength, MessageBody, PayloadStream}; +use crate::error::PayloadError; +use crate::h1; +use crate::message::RequestHead; pub(crate) fn send_request( head: RequestHead, @@ -174,14 +174,16 @@ impl Stream for Payload { fn poll(&mut self) -> Poll, Self::Error> { match self.framed.as_mut().unwrap().poll()? { Async::NotReady => Ok(Async::NotReady), - Async::Ready(Some(chunk)) => if let Some(chunk) = chunk { - Ok(Async::Ready(Some(chunk))) - } else { - let framed = self.framed.take().unwrap(); - let force_close = framed.get_codec().keepalive(); - release_connection(framed, force_close); - Ok(Async::Ready(None)) - }, + Async::Ready(Some(chunk)) => { + if let Some(chunk) = chunk { + Ok(Async::Ready(Some(chunk))) + } else { + let framed = self.framed.take().unwrap(); + let force_close = framed.get_codec().keepalive(); + release_connection(framed, force_close); + Ok(Async::Ready(None)) + } + } Async::Ready(None) => Ok(Async::Ready(None)), } } diff --git a/src/client/request.rs b/src/client/request.rs index e71c3ffd..5f294bbd 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -8,14 +8,14 @@ use cookie::{Cookie, CookieJar}; use futures::{Future, Stream}; use percent_encoding::{percent_encode, USERINFO_ENCODE_SET}; -use body::{BodyStream, MessageBody}; -use error::Error; -use header::{self, Header, IntoHeaderValue}; -use http::{ +use crate::body::{BodyStream, MessageBody}; +use crate::error::Error; +use crate::header::{self, Header, IntoHeaderValue}; +use crate::http::{ uri, Error as HttpError, HeaderMap, HeaderName, HeaderValue, HttpTryFrom, Method, Uri, Version, }; -use message::{ConnectionType, Head, RequestHead}; +use crate::message::{ConnectionType, Head, RequestHead}; use super::response::ClientResponse; use super::{pipeline, Connect, Connection, ConnectorError, SendRequestError}; @@ -355,14 +355,16 @@ impl ClientRequestBuilder { { if let Some(parts) = parts(&mut self.head, &self.err) { match HeaderName::try_from(key) { - Ok(key) => if !parts.headers.contains_key(&key) { - match value.try_into() { - Ok(value) => { - parts.headers.insert(key, value); + Ok(key) => { + if !parts.headers.contains_key(&key) { + match value.try_into() { + Ok(value) => { + parts.headers.insert(key, value); + } + Err(e) => self.err = Some(e.into()), } - Err(e) => self.err = Some(e.into()), } - }, + } Err(e) => self.err = Some(e.into()), }; } diff --git a/src/client/response.rs b/src/client/response.rs index dc7b13c1..6bfdfc32 100644 --- a/src/client/response.rs +++ b/src/client/response.rs @@ -5,10 +5,10 @@ use bytes::Bytes; use futures::{Async, Poll, Stream}; use http::{HeaderMap, StatusCode, Version}; -use body::PayloadStream; -use error::PayloadError; -use httpmessage::HttpMessage; -use message::{Head, ResponseHead}; +use crate::body::PayloadStream; +use crate::error::PayloadError; +use crate::httpmessage::HttpMessage; +use crate::message::{Head, ResponseHead}; use super::pipeline::Payload; diff --git a/src/config.rs b/src/config.rs index 833bca7f..661c0901 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,6 +6,7 @@ use std::{fmt, net}; use bytes::BytesMut; use futures::{future, Future}; +use log::error; use time; use tokio_current_thread::spawn; use tokio_timer::{sleep, Delay}; @@ -268,9 +269,11 @@ impl ServiceConfigBuilder { pub fn server_address(mut self, addr: S) -> Self { match addr.to_socket_addrs() { Err(err) => error!("Can not convert to SocketAddr: {}", err), - Ok(mut addrs) => if let Some(addr) = addrs.next() { - self.addr = addr; - }, + Ok(mut addrs) => { + if let Some(addr) = addrs.next() { + self.addr = addr; + } + } } self } diff --git a/src/error.rs b/src/error.rs index 2e0c2382..280f9a32 100644 --- a/src/error.rs +++ b/src/error.rs @@ -20,8 +20,8 @@ use tokio_timer::Error as TimerError; // re-exports pub use cookie::ParseError as CookieParseError; -use body::Body; -use response::{Response, ResponseParts}; +use crate::body::Body; +use crate::response::{Response, ResponseParts}; /// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) /// for actix web operations @@ -186,7 +186,8 @@ impl From for Error { /// Compatibility for `failure::Error` impl ResponseError for failure::Compat where T: fmt::Display + fmt::Debug + Sync + Send + 'static -{} +{ +} impl From for Error { fn from(err: failure::Error) -> Error { diff --git a/src/h1/client.rs b/src/h1/client.rs index 7704ba97..f547983f 100644 --- a/src/h1/client.rs +++ b/src/h1/client.rs @@ -1,22 +1,23 @@ #![allow(unused_imports, unused_variables, dead_code)] use std::io::{self, Write}; +use bitflags::bitflags; use bytes::{BufMut, Bytes, BytesMut}; +use http::header::{ + HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, UPGRADE, +}; +use http::{Method, Version}; use tokio_codec::{Decoder, Encoder}; use super::decoder::{PayloadDecoder, PayloadItem, PayloadType}; use super::{decoder, encoder}; use super::{Message, MessageType}; -use body::BodyLength; -use client::ClientResponse; -use config::ServiceConfig; -use error::{ParseError, PayloadError}; -use helpers; -use http::header::{ - HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, UPGRADE, -}; -use http::{Method, Version}; -use message::{ConnectionType, Head, MessagePool, RequestHead}; +use crate::body::BodyLength; +use crate::client::ClientResponse; +use crate::config::ServiceConfig; +use crate::error::{ParseError, PayloadError}; +use crate::helpers; +use crate::message::{ConnectionType, Head, MessagePool, RequestHead}; bitflags! { struct Flags: u8 { diff --git a/src/h1/codec.rs b/src/h1/codec.rs index 3174e78e..54c1ce2e 100644 --- a/src/h1/codec.rs +++ b/src/h1/codec.rs @@ -2,21 +2,22 @@ use std::fmt; use std::io::{self, Write}; +use bitflags::bitflags; use bytes::{BufMut, Bytes, BytesMut}; +use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING}; +use http::{Method, StatusCode, Version}; use tokio_codec::{Decoder, Encoder}; use super::decoder::{PayloadDecoder, PayloadItem, PayloadType}; use super::{decoder, encoder}; use super::{Message, MessageType}; -use body::BodyLength; -use config::ServiceConfig; -use error::ParseError; -use helpers; -use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING}; -use http::{Method, StatusCode, Version}; -use message::{ConnectionType, Head, ResponseHead}; -use request::Request; -use response::Response; +use crate::body::BodyLength; +use crate::config::ServiceConfig; +use crate::error::ParseError; +use crate::helpers; +use crate::message::{ConnectionType, Head, ResponseHead}; +use crate::request::Request; +use crate::response::Response; bitflags! { struct Flags: u8 { diff --git a/src/h1/decoder.rs b/src/h1/decoder.rs index a081a5cf..26b28440 100644 --- a/src/h1/decoder.rs +++ b/src/h1/decoder.rs @@ -3,15 +3,16 @@ use std::{io, mem}; use bytes::{Bytes, BytesMut}; use futures::{Async, Poll}; -use httparse; -use tokio_codec::Decoder; - -use client::ClientResponse; -use error::ParseError; use http::header::{HeaderName, HeaderValue}; use http::{header, HeaderMap, HttpTryFrom, Method, StatusCode, Uri, Version}; -use message::ConnectionType; -use request::Request; +use httparse; +use log::{debug, error, trace}; +use tokio_codec::Decoder; + +use crate::client::ClientResponse; +use crate::error::ParseError; +use crate::message::ConnectionType; +use crate::request::Request; const MAX_BUFFER_SIZE: usize = 131_072; const MAX_HEADERS: usize = 96; @@ -825,13 +826,13 @@ mod tests { let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n"); let mut reader = MessageDecoder::::default(); - assert!{ reader.decode(&mut buf).unwrap().is_none() } + assert! { reader.decode(&mut buf).unwrap().is_none() } buf.extend(b"t"); - assert!{ reader.decode(&mut buf).unwrap().is_none() } + assert! { reader.decode(&mut buf).unwrap().is_none() } buf.extend(b"es"); - assert!{ reader.decode(&mut buf).unwrap().is_none() } + assert! { reader.decode(&mut buf).unwrap().is_none() } buf.extend(b"t: value\r\n\r\n"); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); diff --git a/src/h1/dispatcher.rs b/src/h1/dispatcher.rs index 5e2742aa..59b419c3 100644 --- a/src/h1/dispatcher.rs +++ b/src/h1/dispatcher.rs @@ -5,19 +5,19 @@ use std::time::Instant; use actix_net::codec::Framed; use actix_net::service::Service; - -use futures::{Async, Future, Poll, Sink, Stream}; +use bitflags::bitflags; +use futures::{try_ready, Async, Future, Poll, Sink, Stream}; +use log::{debug, error, trace}; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_timer::Delay; -use error::{ParseError, PayloadError}; -use payload::{Payload, PayloadSender, PayloadStatus, PayloadWriter}; - -use body::{Body, BodyLength, MessageBody, ResponseBody}; -use config::ServiceConfig; -use error::DispatchError; -use request::Request; -use response::Response; +use crate::body::{Body, BodyLength, MessageBody, ResponseBody}; +use crate::config::ServiceConfig; +use crate::error::DispatchError; +use crate::error::{ParseError, PayloadError}; +use crate::payload::{Payload, PayloadSender, PayloadStatus, PayloadWriter}; +use crate::request::Request; +use crate::response::Response; use super::codec::Codec; use super::{H1ServiceResult, Message, MessageType}; @@ -224,7 +224,7 @@ where }, State::ServiceCall(mut fut) => { match fut.poll().map_err(DispatchError::Service)? { - Async::Ready(mut res) => { + Async::Ready(res) => { let (res, body) = res.replace_body(()); Some(self.send_response(res, body)?) } diff --git a/src/h1/encoder.rs b/src/h1/encoder.rs index f9b4aab3..92456520 100644 --- a/src/h1/encoder.rs +++ b/src/h1/encoder.rs @@ -9,16 +9,15 @@ use bytes::{BufMut, Bytes, BytesMut}; use http::header::{ HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, }; -use http::{HeaderMap, StatusCode, Version}; +use http::{HeaderMap, Method, StatusCode, Version}; -use body::BodyLength; -use config::ServiceConfig; -use header::ContentEncoding; -use helpers; -use http::Method; -use message::{ConnectionType, RequestHead, ResponseHead}; -use request::Request; -use response::Response; +use crate::body::BodyLength; +use crate::config::ServiceConfig; +use crate::header::ContentEncoding; +use crate::helpers; +use crate::message::{ConnectionType, RequestHead, ResponseHead}; +use crate::request::Request; +use crate::response::Response; const AVERAGE_HEADER_SIZE: usize = 30; @@ -205,7 +204,8 @@ impl MessageType for RequestHead { Version::HTTP_11 => "HTTP/1.1", Version::HTTP_2 => "HTTP/2.0", } - ).map_err(|e| io::Error::new(io::ErrorKind::Other, e)) + ) + .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) } } diff --git a/src/h1/mod.rs b/src/h1/mod.rs index da80e55e..461ecb95 100644 --- a/src/h1/mod.rs +++ b/src/h1/mod.rs @@ -16,7 +16,7 @@ pub use self::codec::Codec; pub use self::dispatcher::Dispatcher; pub use self::service::{H1Service, H1ServiceHandler, OneRequest}; -use request::Request; +use crate::request::Request; /// H1 service response type pub enum H1ServiceResult { diff --git a/src/h1/service.rs b/src/h1/service.rs index e21d0fb6..1a5a587c 100644 --- a/src/h1/service.rs +++ b/src/h1/service.rs @@ -5,14 +5,15 @@ use std::net; use actix_net::codec::Framed; use actix_net::service::{IntoNewService, NewService, Service}; use futures::future::{ok, FutureResult}; -use futures::{Async, Future, Poll, Stream}; +use futures::{try_ready, Async, Future, Poll, Stream}; +use log::error; use tokio_io::{AsyncRead, AsyncWrite}; -use body::MessageBody; -use config::{KeepAlive, ServiceConfig}; -use error::{DispatchError, ParseError}; -use request::Request; -use response::Response; +use crate::body::MessageBody; +use crate::config::{KeepAlive, ServiceConfig}; +use crate::error::{DispatchError, ParseError}; +use crate::request::Request; +use crate::response::Response; use super::codec::Codec; use super::dispatcher::Dispatcher; @@ -174,9 +175,11 @@ where pub fn server_address(mut self, addr: U) -> Self { match addr.to_socket_addrs() { Err(err) => error!("Can not convert to SocketAddr: {}", err), - Ok(mut addrs) => if let Some(addr) = addrs.next() { - self.addr = addr; - }, + Ok(mut addrs) => { + if let Some(addr) = addrs.next() { + self.addr = addr; + } + } } self } diff --git a/src/header.rs b/src/header.rs index b1ba6524..6276dd4f 100644 --- a/src/header.rs +++ b/src/header.rs @@ -1,13 +1,12 @@ //! Various http headers use bytes::Bytes; +pub use http::header::*; +use http::Error as HttpError; use mime::Mime; -use modhttp::Error as HttpError; -pub use modhttp::header::*; - -use error::ParseError; -use httpmessage::HttpMessage; +use crate::error::ParseError; +use crate::httpmessage::HttpMessage; #[doc(hidden)] /// A trait for any object that will represent a header field and value. diff --git a/src/httpcodes.rs b/src/httpcodes.rs index 7d42a1cc..80722734 100644 --- a/src/httpcodes.rs +++ b/src/httpcodes.rs @@ -1,7 +1,8 @@ //! Basic http responses #![allow(non_upper_case_globals)] use http::StatusCode; -use response::{Response, ResponseBuilder}; + +use crate::response::{Response, ResponseBuilder}; macro_rules! STATIC_RESP { ($name:ident, $status:expr) => { diff --git a/src/httpmessage.rs b/src/httpmessage.rs index f68f3650..e239a733 100644 --- a/src/httpmessage.rs +++ b/src/httpmessage.rs @@ -10,11 +10,11 @@ use serde::de::DeserializeOwned; use serde_urlencoded; use std::str; -use error::{ +use crate::error::{ ContentTypeError, ParseError, PayloadError, ReadlinesError, UrlencodedError, }; -use header::Header; -use json::JsonBody; +use crate::header::Header; +use crate::json::JsonBody; /// Trait that implements general purpose operations on http messages pub trait HttpMessage: Sized { @@ -438,7 +438,8 @@ where body.extend_from_slice(&chunk); Ok(body) } - }).map(|body| body.freeze()), + }) + .map(|body| body.freeze()), )); self.poll() } @@ -546,7 +547,8 @@ where body.extend_from_slice(&chunk); Ok(body) } - }).and_then(move |body| { + }) + .and_then(move |body| { if (encoding as *const Encoding) == UTF_8 { serde_urlencoded::from_bytes::(&body) .map_err(|_| UrlencodedError::Parse) @@ -604,7 +606,8 @@ mod tests { let req = TestRequest::with_header( "content-type", "applicationadfadsfasdflknadsfklnadsfjson", - ).finish(); + ) + .finish(); assert_eq!(Err(ContentTypeError::ParseError), req.mime_type()); } @@ -619,7 +622,8 @@ mod tests { let req = TestRequest::with_header( "content-type", "application/json; charset=ISO-8859-2", - ).finish(); + ) + .finish(); assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name()); } @@ -631,7 +635,8 @@ mod tests { let req = TestRequest::with_header( "content-type", "application/json; charset=kkkttktk", - ).finish(); + ) + .finish(); assert_eq!( Some(ContentTypeError::UnknownEncoding), req.encoding().err() @@ -651,7 +656,8 @@ mod tests { .header( header::TRANSFER_ENCODING, Bytes::from_static(b"some va\xadscc\xacas0xsdasdlue"), - ).finish(); + ) + .finish(); assert!(req.chunked().is_err()); } @@ -689,7 +695,8 @@ mod tests { let req = TestRequest::with_header( header::CONTENT_TYPE, "application/x-www-form-urlencoded", - ).header(header::CONTENT_LENGTH, "xxxx") + ) + .header(header::CONTENT_LENGTH, "xxxx") .finish(); assert_eq!( req.urlencoded::().poll().err().unwrap(), @@ -699,7 +706,8 @@ mod tests { let req = TestRequest::with_header( header::CONTENT_TYPE, "application/x-www-form-urlencoded", - ).header(header::CONTENT_LENGTH, "1000000") + ) + .header(header::CONTENT_LENGTH, "1000000") .finish(); assert_eq!( req.urlencoded::().poll().err().unwrap(), @@ -720,7 +728,8 @@ mod tests { let req = TestRequest::with_header( header::CONTENT_TYPE, "application/x-www-form-urlencoded", - ).header(header::CONTENT_LENGTH, "11") + ) + .header(header::CONTENT_LENGTH, "11") .set_payload(Bytes::from_static(b"hello=world")) .finish(); @@ -735,7 +744,8 @@ mod tests { let req = TestRequest::with_header( header::CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8", - ).header(header::CONTENT_LENGTH, "11") + ) + .header(header::CONTENT_LENGTH, "11") .set_payload(Bytes::from_static(b"hello=world")) .finish(); @@ -786,7 +796,8 @@ mod tests { b"Lorem Ipsum is simply dummy text of the printing and typesetting\n\ industry. Lorem Ipsum has been the industry's standard dummy\n\ Contrary to popular belief, Lorem Ipsum is not simply random text.", - )).finish(); + )) + .finish(); let mut r = Readlines::new(&req); match r.poll().ok().unwrap() { Async::Ready(Some(s)) => assert_eq!( diff --git a/src/json.rs b/src/json.rs index e2c99ba3..0b6ac377 100644 --- a/src/json.rs +++ b/src/json.rs @@ -6,8 +6,8 @@ use mime; use serde::de::DeserializeOwned; use serde_json; -use error::JsonPayloadError; -use httpmessage::HttpMessage; +use crate::error::JsonPayloadError; +use crate::httpmessage::HttpMessage; /// Request payload json parser that resolves to a deserialized `T` value. /// @@ -124,7 +124,8 @@ impl Future for JsonBod body.extend_from_slice(&chunk); Ok(body) } - }).and_then(|body| Ok(serde_json::from_slice::(&body)?)); + }) + .and_then(|body| Ok(serde_json::from_slice::(&body)?)); self.fut = Some(Box::new(fut)); self.poll() } @@ -170,7 +171,8 @@ mod tests { .header( header::CONTENT_TYPE, header::HeaderValue::from_static("application/text"), - ).finish(); + ) + .finish(); let mut json = req.json::(); assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType); @@ -178,10 +180,12 @@ mod tests { .header( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), - ).header( + ) + .header( header::CONTENT_LENGTH, header::HeaderValue::from_static("10000"), - ).finish(); + ) + .finish(); let mut json = req.json::().limit(100); assert_eq!(json.poll().err().unwrap(), JsonPayloadError::Overflow); @@ -189,10 +193,12 @@ mod tests { .header( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), - ).header( + ) + .header( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), - ).set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) + ) + .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .finish(); let mut json = req.json::(); diff --git a/src/lib.rs b/src/lib.rs index 4870eb64..76c3a967 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -62,56 +62,12 @@ // #![warn(missing_docs)] #![allow(dead_code)] -extern crate actix; -extern crate actix_net; -#[macro_use] -extern crate log; -extern crate base64; -extern crate byteorder; -extern crate bytes; -extern crate sha1; -extern crate time; -#[macro_use] -extern crate bitflags; -#[macro_use] -extern crate failure; -#[macro_use] -extern crate futures; -extern crate cookie; -extern crate encoding; -extern crate http as modhttp; -extern crate httparse; -extern crate indexmap; -extern crate mime; -extern crate net2; -extern crate percent_encoding; -extern crate rand; -extern crate serde; -extern crate serde_json; -extern crate serde_urlencoded; -extern crate slab; -extern crate tokio; -extern crate tokio_codec; -extern crate tokio_current_thread; -extern crate tokio_io; -extern crate tokio_tcp; -extern crate tokio_timer; -extern crate trust_dns_proto; -extern crate trust_dns_resolver; -extern crate url as urlcrate; - -#[cfg(test)] -#[macro_use] -extern crate serde_derive; - -#[cfg(feature = "ssl")] -extern crate openssl; - pub mod body; pub mod client; mod config; mod extensions; mod header; +mod helpers; mod httpcodes; mod httpmessage; mod json; @@ -123,18 +79,17 @@ mod service; pub mod error; pub mod h1; -pub(crate) mod helpers; pub mod test; pub mod ws; -pub use body::{Body, MessageBody}; -pub use error::{Error, ResponseError, Result}; -pub use extensions::Extensions; -pub use httpmessage::HttpMessage; -pub use request::Request; -pub use response::Response; -pub use service::{SendError, SendResponse}; +pub use self::body::{Body, MessageBody}; pub use self::config::{KeepAlive, ServiceConfig, ServiceConfigBuilder}; +pub use self::error::{Error, ResponseError, Result}; +pub use self::extensions::Extensions; +pub use self::httpmessage::HttpMessage; +pub use self::request::Request; +pub use self::response::Response; +pub use self::service::{SendError, SendResponse}; pub mod dev { //! The `actix-web` prelude for library developers @@ -147,31 +102,31 @@ pub mod dev { //! use actix_http::dev::*; //! ``` - pub use httpmessage::{MessageBody, Readlines, UrlEncoded}; - pub use json::JsonBody; - pub use payload::{Payload, PayloadBuffer}; - pub use response::ResponseBuilder; + pub use crate::httpmessage::{MessageBody, Readlines, UrlEncoded}; + pub use crate::json::JsonBody; + pub use crate::payload::{Payload, PayloadBuffer}; + pub use crate::response::ResponseBuilder; } pub mod http { //! Various HTTP related types // re-exports - pub use modhttp::header::{HeaderName, HeaderValue}; - pub use modhttp::{Method, StatusCode, Version}; + pub use http::header::{HeaderName, HeaderValue}; + pub use http::{Method, StatusCode, Version}; #[doc(hidden)] - pub use modhttp::{uri, Error, HeaderMap, HttpTryFrom, Uri}; + pub use http::{uri, Error, HeaderMap, HttpTryFrom, Uri}; #[doc(hidden)] - pub use modhttp::uri::PathAndQuery; + pub use http::uri::PathAndQuery; pub use cookie::{Cookie, CookieBuilder}; /// Various http headers pub mod header { - pub use header::*; + pub use crate::header::*; } - pub use header::ContentEncoding; - pub use message::ConnectionType; + pub use crate::header::ContentEncoding; + pub use crate::message::ConnectionType; } diff --git a/src/message.rs b/src/message.rs index d3d52e2f..31d61f63 100644 --- a/src/message.rs +++ b/src/message.rs @@ -4,8 +4,8 @@ use std::rc::Rc; use http::{HeaderMap, Method, StatusCode, Uri, Version}; -use extensions::Extensions; -use payload::Payload; +use crate::extensions::Extensions; +use crate::payload::Payload; /// Represents various types of connection #[derive(Copy, Clone, PartialEq, Debug)] diff --git a/src/payload.rs b/src/payload.rs index b0592496..37f06d43 100644 --- a/src/payload.rs +++ b/src/payload.rs @@ -9,7 +9,7 @@ use std::cmp; use std::collections::VecDeque; use std::rc::{Rc, Weak}; -use error::PayloadError; +use crate::error::PayloadError; /// max buffer size 32k pub(crate) const MAX_BUFFER_SIZE: usize = 32_768; @@ -515,7 +515,8 @@ where .fold(BytesMut::new(), |mut b, c| { b.extend_from_slice(c); b - }).freeze() + }) + .freeze() } } @@ -547,7 +548,8 @@ mod tests { let res: Result<(), ()> = Ok(()); result(res) - })).unwrap(); + })) + .unwrap(); } #[test] @@ -571,7 +573,8 @@ mod tests { let res: Result<(), ()> = Ok(()); result(res) - })).unwrap(); + })) + .unwrap(); } #[test] @@ -588,7 +591,8 @@ mod tests { payload.readany().err().unwrap(); let res: Result<(), ()> = Ok(()); result(res) - })).unwrap(); + })) + .unwrap(); } #[test] @@ -616,7 +620,8 @@ mod tests { let res: Result<(), ()> = Ok(()); result(res) - })).unwrap(); + })) + .unwrap(); } #[test] @@ -649,7 +654,8 @@ mod tests { let res: Result<(), ()> = Ok(()); result(res) - })).unwrap(); + })) + .unwrap(); } #[test] @@ -682,7 +688,8 @@ mod tests { let res: Result<(), ()> = Ok(()); result(res) - })).unwrap(); + })) + .unwrap(); } #[test] @@ -703,6 +710,7 @@ mod tests { let res: Result<(), ()> = Ok(()); result(res) - })).unwrap(); + })) + .unwrap(); } } diff --git a/src/request.rs b/src/request.rs index 248555e6..60ddee19 100644 --- a/src/request.rs +++ b/src/request.rs @@ -4,11 +4,10 @@ use std::rc::Rc; use http::{header, HeaderMap, Method, Uri, Version}; -use extensions::Extensions; -use httpmessage::HttpMessage; -use payload::Payload; - -use message::{Message, MessagePool, RequestHead}; +use crate::extensions::Extensions; +use crate::httpmessage::HttpMessage; +use crate::message::{Message, MessagePool, RequestHead}; +use crate::payload::Payload; /// Request pub struct Request { diff --git a/src/response.rs b/src/response.rs index ae68189d..e506cd16 100644 --- a/src/response.rs +++ b/src/response.rs @@ -12,10 +12,10 @@ use http::{Error as HttpError, HeaderMap, HttpTryFrom, StatusCode, Version}; use serde::Serialize; use serde_json; -use body::{Body, BodyStream, MessageBody, ResponseBody}; -use error::Error; -use header::{Header, IntoHeaderValue}; -use message::{ConnectionType, Head, ResponseHead}; +use crate::body::{Body, BodyStream, MessageBody, ResponseBody}; +use crate::error::Error; +use crate::header::{Header, IntoHeaderValue}; +use crate::message::{ConnectionType, Head, ResponseHead}; /// max write buffer size 64k pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536; @@ -161,7 +161,8 @@ impl Response { HeaderValue::from_str(&cookie.to_string()) .map(|c| { h.append(header::SET_COOKIE, c); - }).map_err(|e| e.into()) + }) + .map_err(|e| e.into()) } /// Remove all cookies with the given name from this response. Returns diff --git a/src/service.rs b/src/service.rs index aa507acb..a6a82097 100644 --- a/src/service.rs +++ b/src/service.rs @@ -6,10 +6,10 @@ use futures::future::{ok, Either, FutureResult}; use futures::{Async, Future, Poll, Sink}; use tokio_io::{AsyncRead, AsyncWrite}; -use body::{BodyLength, MessageBody, ResponseBody}; -use error::{Error, ResponseError}; -use h1::{Codec, Message}; -use response::Response; +use crate::body::{BodyLength, MessageBody, ResponseBody}; +use crate::error::{Error, ResponseError}; +use crate::h1::{Codec, Message}; +use crate::response::Response; pub struct SendError(PhantomData<(T, R, E)>); @@ -56,7 +56,7 @@ where match req { Ok(r) => Either::A(ok(r)), Err((e, framed)) => { - let mut res = e.error_response().set_body(format!("{}", e)); + let res = e.error_response().set_body(format!("{}", e)); let (res, _body) = res.replace_body(()); Either::B(SendErrorFut { framed: Some(framed), @@ -206,11 +206,13 @@ where // flush write buffer if !framed.is_write_buf_empty() { match framed.poll_complete()? { - Async::Ready(_) => if body_ready { - continue; - } else { - return Ok(Async::NotReady); - }, + Async::Ready(_) => { + if body_ready { + continue; + } else { + return Ok(Async::NotReady); + } + } Async::NotReady => return Ok(Async::NotReady), } } diff --git a/src/test.rs b/src/test.rs index 3d12e344..308d2b4d 100644 --- a/src/test.rs +++ b/src/test.rs @@ -17,15 +17,15 @@ use net2::TcpBuilder; use tokio::runtime::current_thread::Runtime; use tokio_io::{AsyncRead, AsyncWrite}; -use body::MessageBody; -use client::{ +use crate::body::MessageBody; +use crate::client::{ ClientRequest, ClientRequestBuilder, ClientResponse, Connect, Connection, Connector, ConnectorError, SendRequestError, }; -use header::{Header, IntoHeaderValue}; -use payload::Payload; -use request::Request; -use ws; +use crate::header::{Header, IntoHeaderValue}; +use crate::payload::Payload; +use crate::request::Request; +use crate::ws; /// Test `Request` builder /// @@ -338,7 +338,7 @@ impl TestServer { } fn new_connector( -) -> impl Service + Clone + ) -> impl Service + Clone { #[cfg(feature = "ssl")] { diff --git a/src/ws/client/connect.rs b/src/ws/client/connect.rs index 575b4e4d..09d02563 100644 --- a/src/ws/client/connect.rs +++ b/src/ws/client/connect.rs @@ -5,10 +5,9 @@ use cookie::Cookie; use http::header::{HeaderName, HeaderValue}; use http::{Error as HttpError, HttpTryFrom}; -use client::{ClientRequest, ClientRequestBuilder}; -use header::IntoHeaderValue; - use super::ClientError; +use crate::client::{ClientRequest, ClientRequestBuilder}; +use crate::header::IntoHeaderValue; /// `WebSocket` connection pub struct Connect { diff --git a/src/ws/client/error.rs b/src/ws/client/error.rs index 589648ee..62a3f47a 100644 --- a/src/ws/client/error.rs +++ b/src/ws/client/error.rs @@ -2,12 +2,11 @@ use std::io; use actix_net::connector::ConnectorError; -use http::header::HeaderValue; -use http::StatusCode; +use failure::Fail; +use http::{header::HeaderValue, Error as HttpError, StatusCode}; -use error::ParseError; -use http::Error as HttpError; -use ws::ProtocolError; +use crate::error::ParseError; +use crate::ws::ProtocolError; /// Websocket client error #[derive(Fail, Debug)] diff --git a/src/ws/client/service.rs b/src/ws/client/service.rs index 68f8032e..8dd407b0 100644 --- a/src/ws/client/service.rs +++ b/src/ws/client/service.rs @@ -6,17 +6,18 @@ use actix_net::connector::{Connect as TcpConnect, ConnectorError, DefaultConnect use actix_net::service::Service; use base64; use futures::future::{err, Either, FutureResult}; -use futures::{Async, Future, Poll, Sink, Stream}; +use futures::{try_ready, Async, Future, Poll, Sink, Stream}; use http::header::{self, HeaderValue}; use http::{HttpTryFrom, StatusCode}; +use log::trace; use rand; use sha1::Sha1; use tokio_io::{AsyncRead, AsyncWrite}; -use body::BodyLength; -use client::ClientResponse; -use h1; -use ws::Codec; +use crate::body::BodyLength; +use crate::client::ClientResponse; +use crate::h1; +use crate::ws::Codec; use super::{ClientError, Connect, Protocol}; diff --git a/src/ws/frame.rs b/src/ws/frame.rs index 56d28296..32ad4ef4 100644 --- a/src/ws/frame.rs +++ b/src/ws/frame.rs @@ -1,10 +1,11 @@ use byteorder::{ByteOrder, LittleEndian, NetworkEndian}; use bytes::{BufMut, Bytes, BytesMut}; +use log::debug; use rand; -use ws::mask::apply_mask; -use ws::proto::{CloseCode, CloseReason, OpCode}; -use ws::ProtocolError; +use crate::ws::mask::apply_mask; +use crate::ws::proto::{CloseCode, CloseReason, OpCode}; +use crate::ws::ProtocolError; /// A struct representing a `WebSocket` frame. #[derive(Debug)] diff --git a/src/ws/mod.rs b/src/ws/mod.rs index f1c91714..ccd9ef4a 100644 --- a/src/ws/mod.rs +++ b/src/ws/mod.rs @@ -5,10 +5,12 @@ //! communicate with the peer. use std::io; -use error::ResponseError; +use failure::Fail; use http::{header, Method, StatusCode}; -use request::Request; -use response::{Response, ResponseBuilder}; + +use crate::error::ResponseError; +use crate::request::Request; +use crate::response::{Response, ResponseBuilder}; mod client; mod codec; @@ -221,7 +223,8 @@ mod tests { .header( header::UPGRADE, header::HeaderValue::from_static("websocket"), - ).finish(); + ) + .finish(); assert_eq!( HandshakeError::NoConnectionUpgrade, verify_handshake(&req).err().unwrap() @@ -231,10 +234,12 @@ mod tests { .header( header::UPGRADE, header::HeaderValue::from_static("websocket"), - ).header( + ) + .header( header::CONNECTION, header::HeaderValue::from_static("upgrade"), - ).finish(); + ) + .finish(); assert_eq!( HandshakeError::NoVersionHeader, verify_handshake(&req).err().unwrap() @@ -244,13 +249,16 @@ mod tests { .header( header::UPGRADE, header::HeaderValue::from_static("websocket"), - ).header( + ) + .header( header::CONNECTION, header::HeaderValue::from_static("upgrade"), - ).header( + ) + .header( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("5"), - ).finish(); + ) + .finish(); assert_eq!( HandshakeError::UnsupportedVersion, verify_handshake(&req).err().unwrap() @@ -260,13 +268,16 @@ mod tests { .header( header::UPGRADE, header::HeaderValue::from_static("websocket"), - ).header( + ) + .header( header::CONNECTION, header::HeaderValue::from_static("upgrade"), - ).header( + ) + .header( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), - ).finish(); + ) + .finish(); assert_eq!( HandshakeError::BadWebsocketKey, verify_handshake(&req).err().unwrap() @@ -276,16 +287,20 @@ mod tests { .header( header::UPGRADE, header::HeaderValue::from_static("websocket"), - ).header( + ) + .header( header::CONNECTION, header::HeaderValue::from_static("upgrade"), - ).header( + ) + .header( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), - ).header( + ) + .header( header::SEC_WEBSOCKET_KEY, header::HeaderValue::from_static("13"), - ).finish(); + ) + .finish(); assert_eq!( StatusCode::SWITCHING_PROTOCOLS, handshake_response(&req).finish().status() diff --git a/src/ws/service.rs b/src/ws/service.rs index 118a2244..84627814 100644 --- a/src/ws/service.rs +++ b/src/ws/service.rs @@ -5,8 +5,8 @@ use actix_net::service::{NewService, Service}; use futures::future::{ok, FutureResult}; use futures::{Async, IntoFuture, Poll}; -use h1::Codec; -use request::Request; +use crate::h1::Codec; +use crate::request::Request; use super::{verify_handshake, HandshakeError}; diff --git a/tests/test_client.rs b/tests/test_client.rs index 4a4ccb7d..3e14cd7b 100644 --- a/tests/test_client.rs +++ b/tests/test_client.rs @@ -91,7 +91,8 @@ fn test_with_query_parameter() { } else { ok::<_, ()>(Response::BadRequest().finish()) } - }).map(|_| ()) + }) + .map(|_| ()) }); let mut connector = srv.new_connector(); diff --git a/tests/test_server.rs b/tests/test_server.rs index 300b38a8..d169e5a9 100644 --- a/tests/test_server.rs +++ b/tests/test_server.rs @@ -209,7 +209,8 @@ fn test_content_length() { StatusCode::NOT_FOUND, ]; future::ok::<_, ()>(Response::new(statuses[indx])) - }).map(|_| ()) + }) + .map(|_| ()) }); let header = HeaderName::from_static("content-length"); @@ -348,7 +349,8 @@ fn test_head_binary() { let mut srv = test::TestServer::with_factory(|| { h1::H1Service::new(|_| { ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR)) - }).map(|_| ()) + }) + .map(|_| ()) }); let req = client::ClientRequest::head(srv.url("/")).finish().unwrap(); @@ -396,7 +398,8 @@ fn test_body_length() { Response::Ok() .body(Body::from_message(body::SizedStream::new(STR.len(), body))), ) - }).map(|_| ()) + }) + .map(|_| ()) }); let req = srv.get().finish().unwrap(); @@ -414,7 +417,8 @@ fn test_body_chunked_explicit() { h1::H1Service::new(|_| { let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref()))); ok::<_, ()>(Response::Ok().streaming(body)) - }).map(|_| ()) + }) + .map(|_| ()) }); let req = srv.get().finish().unwrap(); @@ -434,7 +438,8 @@ fn test_body_chunked_implicit() { h1::H1Service::new(|_| { let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref()))); ok::<_, ()>(Response::Ok().streaming(body)) - }).map(|_| ()) + }) + .map(|_| ()) }); let req = srv.get().finish().unwrap(); @@ -456,7 +461,8 @@ fn test_response_http_error_handling() { .header(http::header::CONTENT_TYPE, broken_header) .body(STR), ) - }).map(|_| ()) + }) + .map(|_| ()) }); let req = srv.get().finish().unwrap(); diff --git a/tests/test_ws.rs b/tests/test_ws.rs index 22ce3ca2..f890c586 100644 --- a/tests/test_ws.rs +++ b/tests/test_ws.rs @@ -62,7 +62,8 @@ fn test_simple() { SendResponse::send( framed, ws::handshake_response(&req).finish(), - ).map_err(|_| ()) + ) + .map_err(|_| ()) .and_then(|framed| { // start websocket service let framed = framed.into_framed(ws::Codec::new());