1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-27 17:52:56 +01:00

Merge branch 'master' into master

This commit is contained in:
Yuki Okushi 2019-12-08 16:26:35 +09:00 committed by GitHub
commit 909c7c8b5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
107 changed files with 558 additions and 572 deletions

View File

@ -1,6 +1,10 @@
# Changes # Changes
## [2.0.0-alpha.3] - 2019-12-xx ### Deleted
* Delete HttpServer::run(), it is not useful witht async/await
## [2.0.0-alpha.3] - 2019-12-07
### Changed ### Changed

View File

@ -16,7 +16,7 @@ exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018" edition = "2018"
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["openssl", "brotli", "flate2-zlib", "secure-cookies", "client"] features = ["openssl", "flate2-zlib", "secure-cookies", "client"]
[badges] [badges]
travis-ci = { repository = "actix/actix-web", branch = "master" } travis-ci = { repository = "actix/actix-web", branch = "master" }
@ -43,19 +43,16 @@ members = [
] ]
[features] [features]
default = ["brotli", "flate2-zlib", "client", "fail"] default = ["flate2-zlib", "client", "fail"]
# http client # http client
client = ["awc"] client = ["awc"]
# brotli encoding, requires c compiler
brotli = ["actix-http/brotli"]
# miniz-sys backend for flate2 crate # miniz-sys backend for flate2 crate
flate2-zlib = ["actix-http/flate2-zlib"] flate2-zlib = ["actix-http/flate2-zlib", "awc/flate2-zlib"]
# rust backend for flate2 crate # rust backend for flate2 crate
flate2-rust = ["actix-http/flate2-rust"] flate2-rust = ["actix-http/flate2-rust", "awc/flate2-rust"]
# sessions feature, session require "ring" crate and c compiler # sessions feature, session require "ring" crate and c compiler
secure-cookies = ["actix-http/secure-cookies"] secure-cookies = ["actix-http/secure-cookies"]
@ -80,8 +77,8 @@ actix-threadpool = "0.3.0"
actix-tls = { version = "1.0.0-alpha.3" } actix-tls = { version = "1.0.0-alpha.3" }
actix-web-codegen = "0.2.0-alpha.2" actix-web-codegen = "0.2.0-alpha.2"
actix-http = "0.3.0-alpha.2" actix-http = "1.0.0-alpha.3"
awc = { version = "0.3.0-alpha.2", optional = true } awc = { version = "1.0.0-alpha.3", default-features = false, optional = true }
bytes = "0.5.2" bytes = "0.5.2"
derive_more = "0.99.2" derive_more = "0.99.2"
@ -93,7 +90,7 @@ mime = "0.3"
net2 = "0.2.33" net2 = "0.2.33"
parking_lot = "0.9" parking_lot = "0.9"
pin-project = "0.4.6" pin-project = "0.4.6"
regex = "1.0" regex = "1.3"
serde = { version = "1.0", features=["derive"] } serde = { version = "1.0", features=["derive"] }
serde_json = "1.0" serde_json = "1.0"
serde_urlencoded = "0.6.1" serde_urlencoded = "0.6.1"
@ -106,12 +103,12 @@ rust-tls = { version = "0.16", package="rustls", optional = true }
[dev-dependencies] [dev-dependencies]
# actix = "0.8.3" # actix = "0.8.3"
actix-connect = "1.0.0-alpha.2" actix-connect = "1.0.0-alpha.3"
actix-http-test = "0.3.0-alpha.2" actix-http-test = "1.0.0-alpha.3"
rand = "0.7" rand = "0.7"
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"
brotli2 = "0.3.2" brotli = "3.3.0"
flate2 = "1.0.2" flate2 = "1.0.2"
[profile.release] [profile.release]
@ -130,13 +127,3 @@ actix-session = { path = "actix-session" }
actix-files = { path = "actix-files" } actix-files = { path = "actix-files" }
actix-multipart = { path = "actix-multipart" } actix-multipart = { path = "actix-multipart" }
awc = { path = "awc" } awc = { path = "awc" }
actix-codec = { git = "https://github.com/actix/actix-net.git" }
actix-connect = { git = "https://github.com/actix/actix-net.git" }
actix-rt = { git = "https://github.com/actix/actix-net.git" }
actix-server = { git = "https://github.com/actix/actix-net.git" }
actix-service = { git = "https://github.com/actix/actix-net.git" }
actix-testing = { git = "https://github.com/actix/actix-net.git" }
actix-tls = { git = "https://github.com/actix/actix-net.git" }
actix-utils = { git = "https://github.com/actix/actix-net.git" }
actix-router = { git = "https://github.com/actix/actix-net.git" }

View File

@ -1,6 +1,6 @@
# Changes # Changes
## [0.2.0-alpha.3] - unreleased ## [0.2.0-alpha.3] - 2019-12-07
* Migrate to actix-web 2.0.0 * Migrate to actix-web 2.0.0

View File

@ -17,10 +17,10 @@ name = "actix_cors"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = "2.0.0-alpha.1" actix-web = "2.0.0-alpha.3"
actix-service = "1.0.0-alpha.2" actix-service = "1.0.0-alpha.3"
derive_more = "0.99.2" derive_more = "0.99.2"
futures = "0.3.1" futures = "0.3.1"
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.2" actix-rt = "1.0.0-alpha.3"

View File

@ -1,6 +1,6 @@
# Changes # Changes
## [0.2.0-alpha.2] - 2019-12-03 ## [0.2.0-alpha.7] - 2019-12-07
* Migrate to `std::future` * Migrate to `std::future`

View File

@ -18,8 +18,8 @@ name = "actix_files"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "2.0.0-alpha.2", default-features = false } actix-web = { version = "2.0.0-alpha.3", default-features = false }
actix-http = "0.3.0-alpha.2" actix-http = "1.0.0-alpha.3"
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0-alpha.3"
bitflags = "1" bitflags = "1"
bytes = "0.5.2" bytes = "0.5.2"
@ -32,5 +32,5 @@ percent-encoding = "2.1"
v_htmlescape = "0.4" v_htmlescape = "0.4"
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.2" actix-rt = "1.0.0-alpha.3"
actix-web = { version = "2.0.0-alpha.2", features=["openssl"] } actix-web = { version = "2.0.0-alpha.3", features=["openssl"] }

View File

@ -24,7 +24,7 @@ actix-codec = "0.2.0-alpha.3"
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0-alpha.3"
actix-router = "0.2.0" actix-router = "0.2.0"
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0-alpha.3"
actix-http = "0.3.0-alpha.3" actix-http = "1.0.0-alpha.3"
bytes = "0.5.2" bytes = "0.5.2"
futures = "0.3.1" futures = "0.3.1"
@ -34,5 +34,5 @@ log = "0.4"
[dev-dependencies] [dev-dependencies]
actix-server = { version = "1.0.0-alpha.3" } actix-server = { version = "1.0.0-alpha.3" }
actix-connect = { version = "1.0.0-alpha.3", features=["openssl"] } actix-connect = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.3", features=["openssl"] } actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-utils = "1.0.0-alpha.3" actix-utils = "1.0.0-alpha.3"

View File

@ -1,5 +1,22 @@
# Changes # Changes
### Added
* Add impl ResponseBuilder for Error
### Changed
* Use rust based brotli compression library
## [1.0.0-alpha.3] - 2019-12-07
### Changed
* Migrate to tokio 0.2
* Migrate to `std::future`
## [0.2.11] - 2019-11-06 ## [0.2.11] - 2019-11-06
### Added ### Added

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-http" name = "actix-http"
version = "0.3.0-alpha.3" version = "1.0.0-alpha.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http primitives" description = "Actix http primitives"
readme = "README.md" readme = "README.md"
@ -16,7 +16,7 @@ edition = "2018"
workspace = ".." workspace = ".."
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["openssl", "rustls", "fail", "brotli", "flate2-zlib", "secure-cookies"] features = ["openssl", "rustls", "fail", "flate2-zlib", "secure-cookies"]
[lib] [lib]
name = "actix_http" name = "actix_http"
@ -31,9 +31,6 @@ openssl = ["actix-tls/openssl", "actix-connect/openssl"]
# rustls support # rustls support
rustls = ["actix-tls/rustls", "actix-connect/rustls"] rustls = ["actix-tls/rustls", "actix-connect/rustls"]
# brotli encoding, requires c compiler
brotli = ["brotli2"]
# miniz-sys backend for flate2 crate # miniz-sys backend for flate2 crate
flate2-zlib = ["flate2/miniz-sys"] flate2-zlib = ["flate2/miniz-sys"]
@ -65,7 +62,7 @@ either = "1.5.2"
encoding_rs = "0.8" encoding_rs = "0.8"
futures = "0.3.1" futures = "0.3.1"
fxhash = "0.2.1" fxhash = "0.2.1"
h2 = "0.2.0" h2 = "0.2.1"
http = "0.2.0" http = "0.2.0"
httparse = "1.3" httparse = "1.3"
indexmap = "1.2" indexmap = "1.2"
@ -88,7 +85,7 @@ time = "0.1.42"
ring = { version = "0.16.9", optional = true } ring = { version = "0.16.9", optional = true }
# compression # compression
brotli2 = { version="0.3.2", optional = true } brotli = "3.3.0"
flate2 = { version="1.0.7", optional = true, default-features = false } flate2 = { version="1.0.7", optional = true, default-features = false }
# optional deps # optional deps
@ -97,7 +94,7 @@ failure = { version = "0.1.5", optional = true }
[dev-dependencies] [dev-dependencies]
actix-server = { version = "1.0.0-alpha.3" } actix-server = { version = "1.0.0-alpha.3" }
actix-connect = { version = "1.0.0-alpha.3", features=["openssl"] } actix-connect = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.3", features=["openssl"] } actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-tls = { version = "1.0.0-alpha.3", features=["openssl"] } actix-tls = { version = "1.0.0-alpha.3", features=["openssl"] }
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"

View File

@ -35,7 +35,7 @@ impl BodySize {
pub trait MessageBody { pub trait MessageBody {
fn size(&self) -> BodySize; fn size(&self) -> BodySize;
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>>; fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>>;
} }
impl MessageBody for () { impl MessageBody for () {
@ -43,7 +43,7 @@ impl MessageBody for () {
BodySize::Empty BodySize::Empty
} }
fn poll_next(&mut self, _: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, _: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
Poll::Ready(None) Poll::Ready(None)
} }
} }
@ -53,7 +53,7 @@ impl<T: MessageBody> MessageBody for Box<T> {
self.as_ref().size() self.as_ref().size()
} }
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
self.as_mut().poll_next(cx) self.as_mut().poll_next(cx)
} }
} }
@ -97,7 +97,7 @@ impl<B: MessageBody> MessageBody for ResponseBody<B> {
} }
} }
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
match self { match self {
ResponseBody::Body(ref mut body) => body.poll_next(cx), ResponseBody::Body(ref mut body) => body.poll_next(cx),
ResponseBody::Other(ref mut body) => body.poll_next(cx), ResponseBody::Other(ref mut body) => body.poll_next(cx),
@ -109,7 +109,10 @@ impl<B: MessageBody> Stream for ResponseBody<B> {
type Item = Result<Bytes, Error>; type Item = Result<Bytes, Error>;
#[project] #[project]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
#[project] #[project]
match self.project() { match self.project() {
ResponseBody::Body(ref mut body) => body.poll_next(cx), ResponseBody::Body(ref mut body) => body.poll_next(cx),
@ -152,7 +155,7 @@ impl MessageBody for Body {
} }
} }
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
match self { match self {
Body::None => Poll::Ready(None), Body::None => Poll::Ready(None),
Body::Empty => Poll::Ready(None), Body::Empty => Poll::Ready(None),
@ -190,7 +193,7 @@ impl PartialEq for Body {
} }
impl fmt::Debug for Body { impl fmt::Debug for Body {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
Body::None => write!(f, "Body::None"), Body::None => write!(f, "Body::None"),
Body::Empty => write!(f, "Body::Empty"), Body::Empty => write!(f, "Body::Empty"),
@ -272,7 +275,7 @@ impl MessageBody for Bytes {
BodySize::Sized(self.len()) BodySize::Sized(self.len())
} }
fn poll_next(&mut self, _: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, _: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
if self.is_empty() { if self.is_empty() {
Poll::Ready(None) Poll::Ready(None)
} else { } else {
@ -286,7 +289,7 @@ impl MessageBody for BytesMut {
BodySize::Sized(self.len()) BodySize::Sized(self.len())
} }
fn poll_next(&mut self, _: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, _: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
if self.is_empty() { if self.is_empty() {
Poll::Ready(None) Poll::Ready(None)
} else { } else {
@ -300,7 +303,7 @@ impl MessageBody for &'static str {
BodySize::Sized(self.len()) BodySize::Sized(self.len())
} }
fn poll_next(&mut self, _: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, _: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
if self.is_empty() { if self.is_empty() {
Poll::Ready(None) Poll::Ready(None)
} else { } else {
@ -316,7 +319,7 @@ impl MessageBody for &'static [u8] {
BodySize::Sized(self.len()) BodySize::Sized(self.len())
} }
fn poll_next(&mut self, _: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, _: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
if self.is_empty() { if self.is_empty() {
Poll::Ready(None) Poll::Ready(None)
} else { } else {
@ -330,7 +333,7 @@ impl MessageBody for Vec<u8> {
BodySize::Sized(self.len()) BodySize::Sized(self.len())
} }
fn poll_next(&mut self, _: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, _: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
if self.is_empty() { if self.is_empty() {
Poll::Ready(None) Poll::Ready(None)
} else { } else {
@ -344,7 +347,7 @@ impl MessageBody for String {
BodySize::Sized(self.len()) BodySize::Sized(self.len())
} }
fn poll_next(&mut self, _: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, _: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
if self.is_empty() { if self.is_empty() {
Poll::Ready(None) Poll::Ready(None)
} else { } else {
@ -386,7 +389,7 @@ where
BodySize::Stream BodySize::Stream
} }
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
unsafe { Pin::new_unchecked(self) } unsafe { Pin::new_unchecked(self) }
.project() .project()
.stream .stream
@ -421,7 +424,7 @@ where
BodySize::Sized64(self.size) BodySize::Sized64(self.size)
} }
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
unsafe { Pin::new_unchecked(self) } unsafe { Pin::new_unchecked(self) }
.project() .project()
.stream .stream

View File

@ -63,7 +63,7 @@ impl<T> fmt::Debug for IoConnection<T>
where where
T: fmt::Debug, T: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.io { match self.io {
Some(ConnectionType::H1(ref io)) => write!(f, "H1Connection({:?})", io), Some(ConnectionType::H1(ref io)) => write!(f, "H1Connection({:?})", io),
Some(ConnectionType::H2(_)) => write!(f, "H2Connection"), Some(ConnectionType::H2(_)) => write!(f, "H2Connection"),
@ -247,7 +247,7 @@ where
#[project] #[project]
fn poll_write( fn poll_write(
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context, cx: &mut Context<'_>,
buf: &[u8], buf: &[u8],
) -> Poll<io::Result<usize>> { ) -> Poll<io::Result<usize>> {
#[project] #[project]

View File

@ -62,7 +62,7 @@ trait Io: AsyncRead + AsyncWrite + Unpin {}
impl<T: AsyncRead + AsyncWrite + Unpin> Io for T {} impl<T: AsyncRead + AsyncWrite + Unpin> Io for T {}
impl Connector<(), ()> { impl Connector<(), ()> {
#[allow(clippy::new_ret_no_self)] #[allow(clippy::new_ret_no_self, clippy::let_unit_value)]
pub fn new() -> Connector< pub fn new() -> Connector<
impl Service< impl Service<
Request = TcpConnect<Uri>, Request = TcpConnect<Uri>,
@ -87,9 +87,9 @@ impl Connector<(), ()> {
let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
let mut config = ClientConfig::new(); let mut config = ClientConfig::new();
config.set_protocols(&protos); config.set_protocols(&protos);
config.root_store.add_server_trust_anchors( config
&actix_connect::ssl::rustls::TLS_SERVER_ROOTS, .root_store
); .add_server_trust_anchors(&actix_tls::rustls::TLS_SERVER_ROOTS);
SslConnector::Rustls(Arc::new(config)) SslConnector::Rustls(Arc::new(config))
} }
#[cfg(not(any(feature = "openssl", feature = "rustls")))] #[cfg(not(any(feature = "openssl", feature = "rustls")))]
@ -378,7 +378,7 @@ mod connect_impl {
Ready<Result<IoConnection<Io>, ConnectError>>, Ready<Result<IoConnection<Io>, ConnectError>>,
>; >;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.tcp_pool.poll_ready(cx) self.tcp_pool.poll_ready(cx)
} }
@ -451,7 +451,7 @@ mod connect_impl {
InnerConnectorResponseB<T2, Io1, Io2>, InnerConnectorResponseB<T2, Io1, Io2>,
>; >;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.tcp_pool.poll_ready(cx) self.tcp_pool.poll_ready(cx)
} }
@ -490,10 +490,10 @@ mod connect_impl {
{ {
type Output = Result<EitherConnection<Io1, Io2>, ConnectError>; type Output = Result<EitherConnection<Io1, Io2>, ConnectError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready( Poll::Ready(
ready!(Pin::new(&mut self.get_mut().fut).poll(cx)) ready!(Pin::new(&mut self.get_mut().fut).poll(cx))
.map(|res| EitherConnection::A(res)), .map(EitherConnection::A),
) )
} }
} }
@ -519,10 +519,10 @@ mod connect_impl {
{ {
type Output = Result<EitherConnection<Io1, Io2>, ConnectError>; type Output = Result<EitherConnection<Io1, Io2>, ConnectError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready( Poll::Ready(
ready!(Pin::new(&mut self.get_mut().fut).poll(cx)) ready!(Pin::new(&mut self.get_mut().fut).poll(cx))
.map(|res| EitherConnection::B(res)), .map(EitherConnection::B),
) )
} }
} }

View File

@ -234,7 +234,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin + 'static> AsyncWrite for H1Connection<T>
fn poll_shutdown( fn poll_shutdown(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll<Result<(), io::Error>> { ) -> Poll<Result<(), io::Error>> {
Pin::new(self.io.as_mut().unwrap()).poll_shutdown(cx) Pin::new(self.io.as_mut().unwrap()).poll_shutdown(cx)
} }
@ -255,7 +255,10 @@ impl<Io: ConnectionLifetime> PlStream<Io> {
impl<Io: ConnectionLifetime> Stream for PlStream<Io> { impl<Io: ConnectionLifetime> Stream for PlStream<Io> {
type Item = Result<Bytes, PayloadError>; type Item = Result<Bytes, PayloadError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.get_mut(); let this = self.get_mut();
match this.framed.as_mut().unwrap().next_item(cx)? { match this.framed.as_mut().unwrap().next_item(cx)? {

View File

@ -93,7 +93,7 @@ where
type Error = ConnectError; type Error = ConnectError;
type Future = LocalBoxFuture<'static, Result<IoConnection<Io>, ConnectError>>; type Future = LocalBoxFuture<'static, Result<IoConnection<Io>, ConnectError>>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.poll_ready(cx) self.0.poll_ready(cx)
} }
@ -308,7 +308,7 @@ where
(rx, token) (rx, token)
} }
fn acquire(&mut self, key: &Key, cx: &mut Context) -> Acquire<Io> { fn acquire(&mut self, key: &Key, cx: &mut Context<'_>) -> Acquire<Io> {
// check limits // check limits
if self.limit > 0 && self.acquired >= self.limit { if self.limit > 0 && self.acquired >= self.limit {
return Acquire::NotAvailable; return Acquire::NotAvailable;
@ -409,7 +409,7 @@ where
{ {
type Output = (); type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let this = self.get_mut(); let this = self.get_mut();
match Pin::new(&mut this.timeout).poll(cx) { match Pin::new(&mut this.timeout).poll(cx) {
@ -438,7 +438,7 @@ where
{ {
type Output = (); type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = unsafe { self.get_unchecked_mut() }; let this = unsafe { self.get_unchecked_mut() };
let mut inner = this.inner.as_ref().borrow_mut(); let mut inner = this.inner.as_ref().borrow_mut();
@ -545,7 +545,7 @@ where
{ {
type Output = (); type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = unsafe { self.get_unchecked_mut() }; let this = unsafe { self.get_unchecked_mut() };
if let Some(ref mut h2) = this.h2 { if let Some(ref mut h2) = this.h2 {

View File

@ -32,7 +32,7 @@ where
type Error = T::Error; type Error = T::Error;
type Future = T::Future; type Future = T::Future;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
unsafe { &mut *self.0.as_ref().get() }.poll_ready(cx) unsafe { &mut *self.0.as_ref().get() }.poll_ready(cx)
} }

View File

@ -18,7 +18,6 @@ use super::{Cookie, SameSite};
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let cookie: Cookie = Cookie::build("name", "value") /// let cookie: Cookie = Cookie::build("name", "value")
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
/// .path("/") /// .path("/")
@ -26,7 +25,6 @@ use super::{Cookie, SameSite};
/// .http_only(true) /// .http_only(true)
/// .max_age(84600) /// .max_age(84600)
/// .finish(); /// .finish();
/// # }
/// ``` /// ```
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CookieBuilder { pub struct CookieBuilder {
@ -65,13 +63,11 @@ impl CookieBuilder {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .expires(time::now()) /// .expires(time::now())
/// .finish(); /// .finish();
/// ///
/// assert!(c.expires().is_some()); /// assert!(c.expires().is_some());
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn expires(mut self, when: Tm) -> CookieBuilder { pub fn expires(mut self, when: Tm) -> CookieBuilder {
@ -86,13 +82,11 @@ impl CookieBuilder {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .max_age(1800) /// .max_age(1800)
/// .finish(); /// .finish();
/// ///
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60))); /// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn max_age(self, seconds: i64) -> CookieBuilder { pub fn max_age(self, seconds: i64) -> CookieBuilder {
@ -106,13 +100,11 @@ impl CookieBuilder {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .max_age_time(time::Duration::minutes(30)) /// .max_age_time(time::Duration::minutes(30))
/// .finish(); /// .finish();
/// ///
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60))); /// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn max_age_time(mut self, value: Duration) -> CookieBuilder { pub fn max_age_time(mut self, value: Duration) -> CookieBuilder {
@ -222,14 +214,12 @@ impl CookieBuilder {
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .permanent() /// .permanent()
/// .finish(); /// .finish();
/// ///
/// assert_eq!(c.max_age(), Some(Duration::days(365 * 20))); /// assert_eq!(c.max_age(), Some(Duration::days(365 * 20)));
/// # assert!(c.expires().is_some()); /// # assert!(c.expires().is_some());
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn permanent(mut self) -> CookieBuilder { pub fn permanent(mut self) -> CookieBuilder {

View File

@ -88,7 +88,7 @@ impl SameSite {
} }
impl fmt::Display for SameSite { impl fmt::Display for SameSite {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
SameSite::Strict => write!(f, "Strict"), SameSite::Strict => write!(f, "Strict"),
SameSite::Lax => write!(f, "Lax"), SameSite::Lax => write!(f, "Lax"),

View File

@ -190,7 +190,6 @@ impl CookieJar {
/// use actix_http::cookie::{CookieJar, Cookie}; /// use actix_http::cookie::{CookieJar, Cookie};
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut jar = CookieJar::new(); /// let mut jar = CookieJar::new();
/// ///
/// // Assume this cookie originally had a path of "/" and domain of "a.b". /// // Assume this cookie originally had a path of "/" and domain of "a.b".
@ -204,7 +203,6 @@ impl CookieJar {
/// assert_eq!(delta.len(), 1); /// assert_eq!(delta.len(), 1);
/// assert_eq!(delta[0].name(), "name"); /// assert_eq!(delta[0].name(), "name");
/// assert_eq!(delta[0].max_age(), Some(Duration::seconds(0))); /// assert_eq!(delta[0].max_age(), Some(Duration::seconds(0)));
/// # }
/// ``` /// ```
/// ///
/// Removing a new cookie does not result in a _removal_ cookie: /// Removing a new cookie does not result in a _removal_ cookie:
@ -243,7 +241,6 @@ impl CookieJar {
/// use actix_http::cookie::{CookieJar, Cookie}; /// use actix_http::cookie::{CookieJar, Cookie};
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut jar = CookieJar::new(); /// let mut jar = CookieJar::new();
/// ///
/// // Add an original cookie and a new cookie. /// // Add an original cookie and a new cookie.
@ -261,7 +258,6 @@ impl CookieJar {
/// jar.force_remove(Cookie::new("key", "value")); /// jar.force_remove(Cookie::new("key", "value"));
/// assert_eq!(jar.delta().count(), 0); /// assert_eq!(jar.delta().count(), 0);
/// assert_eq!(jar.iter().count(), 0); /// assert_eq!(jar.iter().count(), 0);
/// # }
/// ``` /// ```
pub fn force_remove<'a>(&mut self, cookie: Cookie<'a>) { pub fn force_remove<'a>(&mut self, cookie: Cookie<'a>) {
self.original_cookies.remove(cookie.name()); self.original_cookies.remove(cookie.name());
@ -307,7 +303,7 @@ impl CookieJar {
/// // Delta contains two new cookies ("new", "yac") and a removal ("name"). /// // Delta contains two new cookies ("new", "yac") and a removal ("name").
/// assert_eq!(jar.delta().count(), 3); /// assert_eq!(jar.delta().count(), 3);
/// ``` /// ```
pub fn delta(&self) -> Delta { pub fn delta(&self) -> Delta<'_> {
Delta { Delta {
iter: self.delta_cookies.iter(), iter: self.delta_cookies.iter(),
} }
@ -343,7 +339,7 @@ impl CookieJar {
/// } /// }
/// } /// }
/// ``` /// ```
pub fn iter(&self) -> Iter { pub fn iter(&self) -> Iter<'_> {
Iter { Iter {
delta_cookies: self delta_cookies: self
.delta_cookies .delta_cookies
@ -386,7 +382,7 @@ impl CookieJar {
/// assert!(jar.get("private").is_some()); /// assert!(jar.get("private").is_some());
/// ``` /// ```
#[cfg(feature = "secure-cookies")] #[cfg(feature = "secure-cookies")]
pub fn private(&mut self, key: &Key) -> PrivateJar { pub fn private(&mut self, key: &Key) -> PrivateJar<'_> {
PrivateJar::new(self, key) PrivateJar::new(self, key)
} }
@ -424,7 +420,7 @@ impl CookieJar {
/// assert!(jar.get("signed").is_some()); /// assert!(jar.get("signed").is_some());
/// ``` /// ```
#[cfg(feature = "secure-cookies")] #[cfg(feature = "secure-cookies")]
pub fn signed(&mut self, key: &Key) -> SignedJar { pub fn signed(&mut self, key: &Key) -> SignedJar<'_> {
SignedJar::new(self, key) SignedJar::new(self, key)
} }
} }

View File

@ -110,7 +110,7 @@ impl CookieStr {
/// # Panics /// # Panics
/// ///
/// Panics if `self` is an indexed string and `string` is None. /// Panics if `self` is an indexed string and `string` is None.
fn to_str<'s>(&'s self, string: Option<&'s Cow<str>>) -> &'s str { fn to_str<'s>(&'s self, string: Option<&'s Cow<'_, str>>) -> &'s str {
match *self { match *self {
CookieStr::Indexed(i, j) => { CookieStr::Indexed(i, j) => {
let s = string.expect( let s = string.expect(
@ -647,13 +647,11 @@ impl<'c> Cookie<'c> {
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut c = Cookie::new("name", "value"); /// let mut c = Cookie::new("name", "value");
/// assert_eq!(c.max_age(), None); /// assert_eq!(c.max_age(), None);
/// ///
/// c.set_max_age(Duration::hours(10)); /// c.set_max_age(Duration::hours(10));
/// assert_eq!(c.max_age(), Some(Duration::hours(10))); /// assert_eq!(c.max_age(), Some(Duration::hours(10)));
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn set_max_age(&mut self, value: Duration) { pub fn set_max_age(&mut self, value: Duration) {
@ -701,7 +699,6 @@ impl<'c> Cookie<'c> {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let mut c = Cookie::new("name", "value"); /// let mut c = Cookie::new("name", "value");
/// assert_eq!(c.expires(), None); /// assert_eq!(c.expires(), None);
/// ///
@ -710,7 +707,6 @@ impl<'c> Cookie<'c> {
/// ///
/// c.set_expires(now); /// c.set_expires(now);
/// assert!(c.expires().is_some()) /// assert!(c.expires().is_some())
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn set_expires(&mut self, time: Tm) { pub fn set_expires(&mut self, time: Tm) {
@ -726,7 +722,6 @@ impl<'c> Cookie<'c> {
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut c = Cookie::new("foo", "bar"); /// let mut c = Cookie::new("foo", "bar");
/// assert!(c.expires().is_none()); /// assert!(c.expires().is_none());
/// assert!(c.max_age().is_none()); /// assert!(c.max_age().is_none());
@ -734,7 +729,6 @@ impl<'c> Cookie<'c> {
/// c.make_permanent(); /// c.make_permanent();
/// assert!(c.expires().is_some()); /// assert!(c.expires().is_some());
/// assert_eq!(c.max_age(), Some(Duration::days(365 * 20))); /// assert_eq!(c.max_age(), Some(Duration::days(365 * 20)));
/// # }
/// ``` /// ```
pub fn make_permanent(&mut self) { pub fn make_permanent(&mut self) {
let twenty_years = Duration::days(365 * 20); let twenty_years = Duration::days(365 * 20);
@ -742,7 +736,7 @@ impl<'c> Cookie<'c> {
self.set_expires(time::now() + twenty_years); self.set_expires(time::now() + twenty_years);
} }
fn fmt_parameters(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt_parameters(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(true) = self.http_only() { if let Some(true) = self.http_only() {
write!(f, "; HttpOnly")?; write!(f, "; HttpOnly")?;
} }
@ -924,10 +918,10 @@ impl<'c> Cookie<'c> {
/// let mut c = Cookie::new("my name", "this; value?"); /// let mut c = Cookie::new("my name", "this; value?");
/// assert_eq!(&c.encoded().to_string(), "my%20name=this%3B%20value%3F"); /// assert_eq!(&c.encoded().to_string(), "my%20name=this%3B%20value%3F");
/// ``` /// ```
pub struct EncodedCookie<'a, 'c: 'a>(&'a Cookie<'c>); pub struct EncodedCookie<'a, 'c>(&'a Cookie<'c>);
impl<'a, 'c: 'a> fmt::Display for EncodedCookie<'a, 'c> { impl<'a, 'c: 'a> fmt::Display for EncodedCookie<'a, 'c> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Percent-encode the name and value. // Percent-encode the name and value.
let name = percent_encode(self.0.name().as_bytes(), USERINFO); let name = percent_encode(self.0.name().as_bytes(), USERINFO);
let value = percent_encode(self.0.value().as_bytes(), USERINFO); let value = percent_encode(self.0.value().as_bytes(), USERINFO);
@ -952,7 +946,7 @@ impl<'c> fmt::Display for Cookie<'c> {
/// ///
/// assert_eq!(&cookie.to_string(), "foo=bar; Path=/"); /// assert_eq!(&cookie.to_string(), "foo=bar; Path=/");
/// ``` /// ```
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}={}", self.name(), self.value())?; write!(f, "{}={}", self.name(), self.value())?;
self.fmt_parameters(f) self.fmt_parameters(f)
} }

View File

@ -40,7 +40,7 @@ impl ParseError {
} }
impl fmt::Display for ParseError { impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str()) write!(f, "{}", self.as_str())
} }
} }

View File

@ -10,7 +10,7 @@ use crate::cookie::{Cookie, CookieJar};
// Keep these in sync, and keep the key len synced with the `private` docs as // Keep these in sync, and keep the key len synced with the `private` docs as
// well as the `KEYS_INFO` const in secure::Key. // well as the `KEYS_INFO` const in secure::Key.
static ALGO: &'static Algorithm = &AES_256_GCM; static ALGO: &Algorithm = &AES_256_GCM;
const NONCE_LEN: usize = 12; const NONCE_LEN: usize = 12;
pub const KEY_LEN: usize = 32; pub const KEY_LEN: usize = 32;
@ -159,7 +159,7 @@ Please change it as soon as possible."
/// Encrypts the cookie's value with /// Encrypts the cookie's value with
/// authenticated encryption assuring confidentiality, integrity, and authenticity. /// authenticated encryption assuring confidentiality, integrity, and authenticity.
fn encrypt_cookie(&self, cookie: &mut Cookie) { fn encrypt_cookie(&self, cookie: &mut Cookie<'_>) {
let name = cookie.name().as_bytes(); let name = cookie.name().as_bytes();
let value = cookie.value().as_bytes(); let value = cookie.value().as_bytes();
let data = encrypt_name_value(name, value, &self.key); let data = encrypt_name_value(name, value, &self.key);

View File

@ -129,7 +129,7 @@ impl<'a> SignedJar<'a> {
} }
/// Signs the cookie's value assuring integrity and authenticity. /// Signs the cookie's value assuring integrity and authenticity.
fn sign_cookie(&self, cookie: &mut Cookie) { fn sign_cookie(&self, cookie: &mut Cookie<'_>) {
let digest = sign(&self.key, cookie.value().as_bytes()); let digest = sign(&self.key, cookie.value().as_bytes());
let mut new_value = base64::encode(digest.as_ref()); let mut new_value = base64::encode(digest.as_ref());
new_value.push_str(cookie.value()); new_value.push_str(cookie.value());

View File

@ -4,8 +4,7 @@ use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_threadpool::{run, CpuFuture}; use actix_threadpool::{run, CpuFuture};
#[cfg(feature = "brotli")] use brotli::DecompressorWriter;
use brotli2::write::BrotliDecoder;
use bytes::Bytes; use bytes::Bytes;
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
use flate2::write::{GzDecoder, ZlibDecoder}; use flate2::write::{GzDecoder, ZlibDecoder};
@ -32,9 +31,8 @@ where
#[inline] #[inline]
pub fn new(stream: S, encoding: ContentEncoding) -> Decoder<S> { pub fn new(stream: S, encoding: ContentEncoding) -> Decoder<S> {
let decoder = match encoding { let decoder = match encoding {
#[cfg(feature = "brotli")]
ContentEncoding::Br => Some(ContentDecoder::Br(Box::new( ContentEncoding::Br => Some(ContentDecoder::Br(Box::new(
BrotliDecoder::new(Writer::new()), DecompressorWriter::new(Writer::new(), 0),
))), ))),
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
ContentEncoding::Deflate => Some(ContentDecoder::Deflate(Box::new( ContentEncoding::Deflate => Some(ContentDecoder::Deflate(Box::new(
@ -80,7 +78,7 @@ where
fn poll_next( fn poll_next(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> { ) -> Poll<Option<Self::Item>> {
loop { loop {
if let Some(ref mut fut) = self.fut { if let Some(ref mut fut) = self.fut {
@ -144,18 +142,16 @@ enum ContentDecoder {
Deflate(Box<ZlibDecoder<Writer>>), Deflate(Box<ZlibDecoder<Writer>>),
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
Gzip(Box<GzDecoder<Writer>>), Gzip(Box<GzDecoder<Writer>>),
#[cfg(feature = "brotli")] Br(Box<DecompressorWriter<Writer>>),
Br(Box<BrotliDecoder<Writer>>),
} }
impl ContentDecoder { impl ContentDecoder {
#[allow(unreachable_patterns)] #[allow(unreachable_patterns)]
fn feed_eof(&mut self) -> io::Result<Option<Bytes>> { fn feed_eof(&mut self) -> io::Result<Option<Bytes>> {
match self { match self {
#[cfg(feature = "brotli")] ContentDecoder::Br(ref mut decoder) => match decoder.flush() {
ContentDecoder::Br(ref mut decoder) => match decoder.finish() { Ok(()) => {
Ok(mut writer) => { let b = decoder.get_mut().take();
let b = writer.take();
if !b.is_empty() { if !b.is_empty() {
Ok(Some(b)) Ok(Some(b))
} else { } else {
@ -195,7 +191,6 @@ impl ContentDecoder {
#[allow(unreachable_patterns)] #[allow(unreachable_patterns)]
fn feed_data(&mut self, data: Bytes) -> io::Result<Option<Bytes>> { fn feed_data(&mut self, data: Bytes) -> io::Result<Option<Bytes>> {
match self { match self {
#[cfg(feature = "brotli")]
ContentDecoder::Br(ref mut decoder) => match decoder.write_all(&data) { ContentDecoder::Br(ref mut decoder) => match decoder.write_all(&data) {
Ok(_) => { Ok(_) => {
decoder.flush()?; decoder.flush()?;

View File

@ -5,8 +5,7 @@ use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_threadpool::{run, CpuFuture}; use actix_threadpool::{run, CpuFuture};
#[cfg(feature = "brotli")] use brotli::CompressorWriter;
use brotli2::write::BrotliEncoder;
use bytes::Bytes; use bytes::Bytes;
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
use flate2::write::{GzEncoder, ZlibEncoder}; use flate2::write::{GzEncoder, ZlibEncoder};
@ -96,7 +95,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
} }
} }
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
loop { loop {
if self.eof { if self.eof {
return Poll::Ready(None); return Poll::Ready(None);
@ -177,8 +176,7 @@ enum ContentEncoder {
Deflate(ZlibEncoder<Writer>), Deflate(ZlibEncoder<Writer>),
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
Gzip(GzEncoder<Writer>), Gzip(GzEncoder<Writer>),
#[cfg(feature = "brotli")] Br(Box<CompressorWriter<Writer>>),
Br(BrotliEncoder<Writer>),
} }
impl ContentEncoder { impl ContentEncoder {
@ -194,10 +192,9 @@ impl ContentEncoder {
Writer::new(), Writer::new(),
flate2::Compression::fast(), flate2::Compression::fast(),
))), ))),
#[cfg(feature = "brotli")] ContentEncoding::Br => Some(ContentEncoder::Br(Box::new(
ContentEncoding::Br => { CompressorWriter::new(Writer::new(), 0, 3, 0),
Some(ContentEncoder::Br(BrotliEncoder::new(Writer::new(), 3))) ))),
}
_ => None, _ => None,
} }
} }
@ -205,8 +202,12 @@ impl ContentEncoder {
#[inline] #[inline]
pub(crate) fn take(&mut self) -> Bytes { pub(crate) fn take(&mut self) -> Bytes {
match *self { match *self {
#[cfg(feature = "brotli")] ContentEncoder::Br(ref mut encoder) => {
ContentEncoder::Br(ref mut encoder) => encoder.get_mut().take(), let mut encoder_new =
Box::new(CompressorWriter::new(Writer::new(), 0, 3, 0));
std::mem::swap(encoder, &mut encoder_new);
encoder_new.into_inner().freeze()
}
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
ContentEncoder::Deflate(ref mut encoder) => encoder.get_mut().take(), ContentEncoder::Deflate(ref mut encoder) => encoder.get_mut().take(),
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
@ -216,11 +217,7 @@ impl ContentEncoder {
fn finish(self) -> Result<Bytes, io::Error> { fn finish(self) -> Result<Bytes, io::Error> {
match self { match self {
#[cfg(feature = "brotli")] ContentEncoder::Br(encoder) => Ok(encoder.into_inner().buf.freeze()),
ContentEncoder::Br(encoder) => match encoder.finish() {
Ok(writer) => Ok(writer.buf.freeze()),
Err(err) => Err(err),
},
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
ContentEncoder::Gzip(encoder) => match encoder.finish() { ContentEncoder::Gzip(encoder) => match encoder.finish() {
Ok(writer) => Ok(writer.buf.freeze()), Ok(writer) => Ok(writer.buf.freeze()),
@ -236,7 +233,6 @@ impl ContentEncoder {
fn write(&mut self, data: &[u8]) -> Result<(), io::Error> { fn write(&mut self, data: &[u8]) -> Result<(), io::Error> {
match *self { match *self {
#[cfg(feature = "brotli")]
ContentEncoder::Br(ref mut encoder) => match encoder.write_all(data) { ContentEncoder::Br(ref mut encoder) => match encoder.write_all(data) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => { Err(err) => {

View File

@ -22,6 +22,9 @@ impl Writer {
fn take(&mut self) -> Bytes { fn take(&mut self) -> Bytes {
self.buf.split().freeze() self.buf.split().freeze()
} }
fn freeze(self) -> Bytes {
self.buf.freeze()
}
} }
impl io::Write for Writer { impl io::Write for Writer {

View File

@ -22,7 +22,7 @@ use serde_urlencoded::ser::Error as FormError;
use crate::body::Body; use crate::body::Body;
pub use crate::cookie::ParseError as CookieParseError; pub use crate::cookie::ParseError as CookieParseError;
use crate::helpers::Writer; use crate::helpers::Writer;
use crate::response::Response; use crate::response::{Response, ResponseBuilder};
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) /// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
/// for actix web operations /// for actix web operations
@ -102,13 +102,13 @@ impl dyn ResponseError + 'static {
} }
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.cause, f) fmt::Display::fmt(&self.cause, f)
} }
} }
impl fmt::Debug for Error { impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{:?}", &self.cause) writeln!(f, "{:?}", &self.cause)
} }
} }
@ -157,6 +157,20 @@ impl<T: ResponseError + 'static> From<T> for Error {
} }
} }
/// Convert Response to a Error
impl From<Response> for Error {
fn from(res: Response) -> Error {
InternalError::from_response("", res).into()
}
}
/// Convert ResponseBuilder to a Error
impl From<ResponseBuilder> for Error {
fn from(mut res: ResponseBuilder) -> Error {
InternalError::from_response("", res.finish()).into()
}
}
/// Return `GATEWAY_TIMEOUT` for `TimeoutError` /// Return `GATEWAY_TIMEOUT` for `TimeoutError`
impl<E: ResponseError> ResponseError for TimeoutError<E> { impl<E: ResponseError> ResponseError for TimeoutError<E> {
fn status_code(&self) -> StatusCode { fn status_code(&self) -> StatusCode {
@ -460,14 +474,12 @@ impl ResponseError for ContentTypeError {
/// default. /// default.
/// ///
/// ```rust /// ```rust
/// # extern crate actix_http;
/// # use std::io; /// # use std::io;
/// # use actix_http::*; /// # use actix_http::*;
/// ///
/// fn index(req: Request) -> Result<&'static str> { /// fn index(req: Request) -> Result<&'static str> {
/// Err(error::ErrorBadRequest(io::Error::new(io::ErrorKind::Other, "error"))) /// Err(error::ErrorBadRequest(io::Error::new(io::ErrorKind::Other, "error")))
/// } /// }
/// # fn main() {}
/// ``` /// ```
pub struct InternalError<T> { pub struct InternalError<T> {
cause: T, cause: T,
@ -501,7 +513,7 @@ impl<T> fmt::Debug for InternalError<T>
where where
T: fmt::Debug + 'static, T: fmt::Debug + 'static,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.cause, f) fmt::Debug::fmt(&self.cause, f)
} }
} }
@ -510,7 +522,7 @@ impl<T> fmt::Display for InternalError<T>
where where
T: fmt::Display + 'static, T: fmt::Display + 'static,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.cause, f) fmt::Display::fmt(&self.cause, f)
} }
} }
@ -555,13 +567,6 @@ where
} }
} }
/// Convert Response to a Error
impl From<Response> for Error {
fn from(res: Response) -> Error {
InternalError::from_response("", res).into()
}
}
/// Helper function that creates wrapper of any error and generate *BAD /// Helper function that creates wrapper of any error and generate *BAD
/// REQUEST* response. /// REQUEST* response.
#[allow(non_snake_case)] #[allow(non_snake_case)]

View File

@ -65,7 +65,7 @@ impl Extensions {
} }
impl fmt::Debug for Extensions { impl fmt::Debug for Extensions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Extensions").finish() f.debug_struct("Extensions").finish()
} }
} }

View File

@ -49,7 +49,7 @@ impl Default for Codec {
} }
impl fmt::Debug for Codec { impl fmt::Debug for Codec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "h1::Codec({:?})", self.flags) write!(f, "h1::Codec({:?})", self.flags)
} }
} }

View File

@ -185,6 +185,7 @@ impl MessageType for Request {
&mut self.head_mut().headers &mut self.head_mut().headers
} }
#[allow(clippy::uninit_assumed_init)]
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> { fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
// Unsafe: we read only this data only after httparse parses headers into. // Unsafe: we read only this data only after httparse parses headers into.
// performance bump for pipeline benchmarks. // performance bump for pipeline benchmarks.
@ -192,7 +193,7 @@ impl MessageType for Request {
unsafe { MaybeUninit::uninit().assume_init() }; unsafe { MaybeUninit::uninit().assume_init() };
let (len, method, uri, ver, h_len) = { let (len, method, uri, ver, h_len) = {
let mut parsed: [httparse::Header; MAX_HEADERS] = let mut parsed: [httparse::Header<'_>; MAX_HEADERS] =
unsafe { MaybeUninit::uninit().assume_init() }; unsafe { MaybeUninit::uninit().assume_init() };
let mut req = httparse::Request::new(&mut parsed); let mut req = httparse::Request::new(&mut parsed);
@ -260,6 +261,7 @@ impl MessageType for ResponseHead {
&mut self.headers &mut self.headers
} }
#[allow(clippy::uninit_assumed_init)]
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> { fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
// Unsafe: we read only this data only after httparse parses headers into. // Unsafe: we read only this data only after httparse parses headers into.
// performance bump for pipeline benchmarks. // performance bump for pipeline benchmarks.
@ -267,7 +269,7 @@ impl MessageType for ResponseHead {
unsafe { MaybeUninit::uninit().assume_init() }; unsafe { MaybeUninit::uninit().assume_init() };
let (len, ver, status, h_len) = { let (len, ver, status, h_len) = {
let mut parsed: [httparse::Header; MAX_HEADERS] = let mut parsed: [httparse::Header<'_>; MAX_HEADERS] =
unsafe { MaybeUninit::uninit().assume_init() }; unsafe { MaybeUninit::uninit().assume_init() };
let mut res = httparse::Response::new(&mut parsed); let mut res = httparse::Response::new(&mut parsed);
@ -326,7 +328,7 @@ pub(crate) struct HeaderIndex {
impl HeaderIndex { impl HeaderIndex {
pub(crate) fn record( pub(crate) fn record(
bytes: &[u8], bytes: &[u8],
headers: &[httparse::Header], headers: &[httparse::Header<'_>],
indices: &mut [HeaderIndex], indices: &mut [HeaderIndex],
) { ) {
let bytes_ptr = bytes.as_ptr() as usize; let bytes_ptr = bytes.as_ptr() as usize;

View File

@ -264,7 +264,7 @@ where
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>, U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display, U::Error: fmt::Display,
{ {
fn can_read(&self, cx: &mut Context) -> bool { fn can_read(&self, cx: &mut Context<'_>) -> bool {
if self if self
.flags .flags
.intersects(Flags::READ_DISCONNECT | Flags::UPGRADE) .intersects(Flags::READ_DISCONNECT | Flags::UPGRADE)
@ -290,7 +290,7 @@ where
/// ///
/// true - got whouldblock /// true - got whouldblock
/// false - didnt get whouldblock /// false - didnt get whouldblock
fn poll_flush(&mut self, cx: &mut Context) -> Result<bool, DispatchError> { fn poll_flush(&mut self, cx: &mut Context<'_>) -> Result<bool, DispatchError> {
if self.write_buf.is_empty() { if self.write_buf.is_empty() {
return Ok(false); return Ok(false);
} }
@ -355,7 +355,7 @@ where
fn poll_response( fn poll_response(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Result<PollResponse, DispatchError> { ) -> Result<PollResponse, DispatchError> {
loop { loop {
let state = match self.state { let state = match self.state {
@ -459,7 +459,7 @@ where
fn handle_request( fn handle_request(
&mut self, &mut self,
req: Request, req: Request,
cx: &mut Context, cx: &mut Context<'_>,
) -> Result<State<S, B, X>, DispatchError> { ) -> Result<State<S, B, X>, DispatchError> {
// Handle `EXPECT: 100-Continue` header // Handle `EXPECT: 100-Continue` header
let req = if req.head().expect() { let req = if req.head().expect() {
@ -500,7 +500,7 @@ where
/// Process one incoming requests /// Process one incoming requests
pub(self) fn poll_request( pub(self) fn poll_request(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Result<bool, DispatchError> { ) -> Result<bool, DispatchError> {
// limit a mount of non processed requests // limit a mount of non processed requests
if self.messages.len() >= MAX_PIPELINED_MESSAGES || !self.can_read(cx) { if self.messages.len() >= MAX_PIPELINED_MESSAGES || !self.can_read(cx) {
@ -604,7 +604,7 @@ where
} }
/// keep-alive timer /// keep-alive timer
fn poll_keepalive(&mut self, cx: &mut Context) -> Result<(), DispatchError> { fn poll_keepalive(&mut self, cx: &mut Context<'_>) -> Result<(), DispatchError> {
if self.ka_timer.is_none() { if self.ka_timer.is_none() {
// shutdown timeout // shutdown timeout
if self.flags.contains(Flags::SHUTDOWN) { if self.flags.contains(Flags::SHUTDOWN) {
@ -710,7 +710,7 @@ where
type Output = Result<(), DispatchError>; type Output = Result<(), DispatchError>;
#[inline] #[inline]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.as_mut().inner { match self.as_mut().inner {
DispatcherState::Normal(ref mut inner) => { DispatcherState::Normal(ref mut inner) => {
inner.poll_keepalive(cx)?; inner.poll_keepalive(cx)?;
@ -832,7 +832,7 @@ where
} }
fn read_available<T>( fn read_available<T>(
cx: &mut Context, cx: &mut Context<'_>,
io: &mut T, io: &mut T,
buf: &mut BytesMut, buf: &mut BytesMut,
) -> Result<Option<bool>, io::Error> ) -> Result<Option<bool>, io::Error>
@ -874,7 +874,7 @@ where
} }
fn read<T>( fn read<T>(
cx: &mut Context, cx: &mut Context<'_>,
io: &mut T, io: &mut T,
buf: &mut BytesMut, buf: &mut BytesMut,
) -> Poll<Result<usize, io::Error>> ) -> Poll<Result<usize, io::Error>>

View File

@ -28,7 +28,7 @@ impl Service for ExpectHandler {
type Error = Error; type Error = Error;
type Future = Ready<Result<Self::Response, Self::Error>>; type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }

View File

@ -82,7 +82,7 @@ impl Payload {
#[inline] #[inline]
pub fn readany( pub fn readany(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, PayloadError>>> { ) -> Poll<Option<Result<Bytes, PayloadError>>> {
self.inner.borrow_mut().readany(cx) self.inner.borrow_mut().readany(cx)
} }
@ -93,7 +93,7 @@ impl Stream for Payload {
fn poll_next( fn poll_next(
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, PayloadError>>> { ) -> Poll<Option<Result<Bytes, PayloadError>>> {
self.inner.borrow_mut().readany(cx) self.inner.borrow_mut().readany(cx)
} }
@ -127,7 +127,7 @@ impl PayloadSender {
} }
#[inline] #[inline]
pub fn need_read(&self, cx: &mut Context) -> PayloadStatus { pub fn need_read(&self, cx: &mut Context<'_>) -> PayloadStatus {
// we check need_read only if Payload (other side) is alive, // we check need_read only if Payload (other side) is alive,
// otherwise always return true (consume payload) // otherwise always return true (consume payload)
if let Some(shared) = self.inner.upgrade() { if let Some(shared) = self.inner.upgrade() {
@ -194,7 +194,7 @@ impl Inner {
fn readany( fn readany(
&mut self, &mut self,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, PayloadError>>> { ) -> Poll<Option<Result<Bytes, PayloadError>>> {
if let Some(data) = self.items.pop_front() { if let Some(data) = self.items.pop_front() {
self.len -= data.len(); self.len -= data.len();

View File

@ -324,7 +324,7 @@ where
{ {
type Output = Result<H1ServiceHandler<T, S::Service, B, X::Service, U::Service>, ()>; type Output = Result<H1ServiceHandler<T, S::Service, B, X::Service, U::Service>, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.as_mut().project(); let mut this = self.as_mut().project();
if let Some(fut) = this.fut_ex.as_pin_mut() { if let Some(fut) = this.fut_ex.as_pin_mut() {
@ -419,7 +419,7 @@ where
type Error = DispatchError; type Error = DispatchError;
type Future = Dispatcher<T, S, B, X, U>; type Future = Dispatcher<T, S, B, X, U>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let ready = self let ready = self
.expect .expect
.poll_ready(cx) .poll_ready(cx)
@ -523,7 +523,7 @@ where
type Error = ParseError; type Error = ParseError;
type Future = OneRequestServiceResponse<T>; type Future = OneRequestServiceResponse<T>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
@ -548,7 +548,7 @@ where
{ {
type Output = Result<(Request, Framed<T, Codec>), ParseError>; type Output = Result<(Request, Framed<T, Codec>), ParseError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.framed.as_mut().unwrap().next_item(cx) { match self.framed.as_mut().unwrap().next_item(cx) {
Poll::Ready(Some(Ok(req))) => match req { Poll::Ready(Some(Ok(req))) => match req {
Message::Item(req) => { Message::Item(req) => {

View File

@ -31,7 +31,7 @@ impl<T> Service for UpgradeHandler<T> {
type Error = Error; type Error = Error;
type Future = Ready<Result<Self::Response, Self::Error>>; type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }

View File

@ -39,7 +39,7 @@ where
{ {
type Output = Result<Framed<T, Codec>, Error>; type Output = Result<Framed<T, Codec>, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
loop { loop {

View File

@ -106,7 +106,7 @@ where
type Output = Result<(), DispatchError>; type Output = Result<(), DispatchError>;
#[inline] #[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
loop { loop {
@ -252,7 +252,7 @@ where
{ {
type Output = (); type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.as_mut().project(); let mut this = self.as_mut().project();
match this.state { match this.state {

View File

@ -29,7 +29,10 @@ impl Payload {
impl Stream for Payload { impl Stream for Payload {
type Item = Result<Bytes, PayloadError>; type Item = Result<Bytes, PayloadError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.get_mut(); let this = self.get_mut();
match Pin::new(&mut this.pl).poll_data(cx) { match Pin::new(&mut this.pl).poll_data(cx) {

View File

@ -235,7 +235,7 @@ where
{ {
type Output = Result<H2ServiceHandler<T, S::Service, B>, S::InitError>; type Output = Result<H2ServiceHandler<T, S::Service, B>, S::InitError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.as_mut().project(); let this = self.as_mut().project();
Poll::Ready(ready!(this.fut.poll(cx)).map(|service| { Poll::Ready(ready!(this.fut.poll(cx)).map(|service| {
@ -293,7 +293,7 @@ where
type Error = DispatchError; type Error = DispatchError;
type Future = H2ServiceHandlerResponse<T, S, B>; type Future = H2ServiceHandlerResponse<T, S, B>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.srv.poll_ready(cx).map_err(|e| { self.srv.poll_ready(cx).map_err(|e| {
let e = e.into(); let e = e.into();
error!("Service readiness error: {:?}", e); error!("Service readiness error: {:?}", e);
@ -358,7 +358,7 @@ where
{ {
type Output = Result<(), DispatchError>; type Output = Result<(), DispatchError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.state { match self.state {
State::Incoming(ref mut disp) => Pin::new(disp).poll(cx), State::Incoming(ref mut disp) => Pin::new(disp).poll(cx),
State::Handshake( State::Handshake(

View File

@ -74,7 +74,7 @@ impl Header for CacheControl {
} }
impl fmt::Display for CacheControl { impl fmt::Display for CacheControl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_comma_delimited(f, &self[..]) fmt_comma_delimited(f, &self[..])
} }
} }
@ -126,7 +126,7 @@ pub enum CacheDirective {
} }
impl fmt::Display for CacheDirective { impl fmt::Display for CacheDirective {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::CacheDirective::*; use self::CacheDirective::*;
fmt::Display::fmt( fmt::Display::fmt(
match *self { match *self {

View File

@ -486,7 +486,7 @@ impl Header for ContentDisposition {
} }
impl fmt::Display for DispositionType { impl fmt::Display for DispositionType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
DispositionType::Inline => write!(f, "inline"), DispositionType::Inline => write!(f, "inline"),
DispositionType::Attachment => write!(f, "attachment"), DispositionType::Attachment => write!(f, "attachment"),
@ -497,7 +497,7 @@ impl fmt::Display for DispositionType {
} }
impl fmt::Display for DispositionParam { impl fmt::Display for DispositionParam {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// All ASCII control characters (0-30, 127) including horizontal tab, double quote, and // All ASCII control characters (0-30, 127) including horizontal tab, double quote, and
// backslash should be escaped in quoted-string (i.e. "foobar"). // backslash should be escaped in quoted-string (i.e. "foobar").
// Ref: RFC6266 S4.1 -> RFC2616 S3.6 // Ref: RFC6266 S4.1 -> RFC2616 S3.6
@ -555,7 +555,7 @@ impl fmt::Display for DispositionParam {
} }
impl fmt::Display for ContentDisposition { impl fmt::Display for ContentDisposition {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.disposition)?; write!(f, "{}", self.disposition)?;
self.parameters self.parameters
.iter() .iter()

View File

@ -166,7 +166,7 @@ impl FromStr for ContentRangeSpec {
} }
impl Display for ContentRangeSpec { impl Display for ContentRangeSpec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
ContentRangeSpec::Bytes { ContentRangeSpec::Bytes {
range, range,

View File

@ -87,7 +87,7 @@ impl Header for IfRange {
} }
impl Display for IfRange { impl Display for IfRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
IfRange::EntityTag(ref x) => Display::fmt(x, f), IfRange::EntityTag(ref x) => Display::fmt(x, f),
IfRange::Date(ref x) => Display::fmt(x, f), IfRange::Date(ref x) => Display::fmt(x, f),

View File

@ -159,7 +159,7 @@ macro_rules! header {
} }
impl std::fmt::Display for $id { impl std::fmt::Display for $id {
#[inline] #[inline]
fn fmt(&self, f: &mut std::fmt::Formatter) -> ::std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> ::std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..]) $crate::http::header::fmt_comma_delimited(f, &self.0[..])
} }
} }
@ -195,7 +195,7 @@ macro_rules! header {
} }
impl std::fmt::Display for $id { impl std::fmt::Display for $id {
#[inline] #[inline]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..]) $crate::http::header::fmt_comma_delimited(f, &self.0[..])
} }
} }
@ -231,7 +231,7 @@ macro_rules! header {
} }
impl std::fmt::Display for $id { impl std::fmt::Display for $id {
#[inline] #[inline]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f) std::fmt::Display::fmt(&self.0, f)
} }
} }
@ -276,7 +276,7 @@ macro_rules! header {
} }
impl std::fmt::Display for $id { impl std::fmt::Display for $id {
#[inline] #[inline]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self { match *self {
$id::Any => f.write_str("*"), $id::Any => f.write_str("*"),
$id::Items(ref fields) => $crate::http::header::fmt_comma_delimited( $id::Items(ref fields) => $crate::http::header::fmt_comma_delimited(

View File

@ -143,7 +143,7 @@ impl HeaderMap {
/// Returns `None` if there are no values associated with the key. /// Returns `None` if there are no values associated with the key.
/// ///
/// [`GetAll`]: struct.GetAll.html /// [`GetAll`]: struct.GetAll.html
pub fn get_all<N: AsName>(&self, name: N) -> GetAll { pub fn get_all<N: AsName>(&self, name: N) -> GetAll<'_> {
GetAll { GetAll {
idx: 0, idx: 0,
item: self.get2(name), item: self.get2(name),
@ -187,7 +187,7 @@ impl HeaderMap {
/// The iteration order is arbitrary, but consistent across platforms for /// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version. Each key will be yielded once per associated /// the same crate version. Each key will be yielded once per associated
/// value. So, if a key has 3 associated values, it will be yielded 3 times. /// value. So, if a key has 3 associated values, it will be yielded 3 times.
pub fn iter(&self) -> Iter { pub fn iter(&self) -> Iter<'_> {
Iter::new(self.inner.iter()) Iter::new(self.inner.iter())
} }
@ -196,7 +196,7 @@ impl HeaderMap {
/// The iteration order is arbitrary, but consistent across platforms for /// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version. Each key will be yielded only once even if it /// the same crate version. Each key will be yielded only once even if it
/// has multiple associated values. /// has multiple associated values.
pub fn keys(&self) -> Keys { pub fn keys(&self) -> Keys<'_> {
Keys(self.inner.keys()) Keys(self.inner.keys())
} }

View File

@ -217,7 +217,7 @@ impl fmt::Write for Writer {
} }
#[inline] #[inline]
fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
fmt::write(self, args) fmt::write(self, args)
} }
} }
@ -259,7 +259,7 @@ pub fn from_one_raw_str<T: FromStr>(val: Option<&HeaderValue>) -> Result<T, Pars
#[inline] #[inline]
#[doc(hidden)] #[doc(hidden)]
/// Format an array into a comma-delimited string. /// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result pub fn fmt_comma_delimited<T>(f: &mut fmt::Formatter<'_>, parts: &[T]) -> fmt::Result
where where
T: fmt::Display, T: fmt::Display,
{ {
@ -361,7 +361,7 @@ pub fn parse_extended_value(
} }
impl fmt::Display for ExtendedValue { impl fmt::Display for ExtendedValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let encoded_value = let encoded_value =
percent_encoding::percent_encode(&self.value[..], HTTP_VALUE); percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
if let Some(ref lang) = self.language_tag { if let Some(ref lang) = self.language_tag {
@ -376,7 +376,7 @@ impl fmt::Display for ExtendedValue {
/// [https://tools.ietf.org/html/rfc5987#section-3.2][url] /// [https://tools.ietf.org/html/rfc5987#section-3.2][url]
/// ///
/// [url]: https://tools.ietf.org/html/rfc5987#section-3.2 /// [url]: https://tools.ietf.org/html/rfc5987#section-3.2
pub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result { pub fn http_percent_encode(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE); let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE);
fmt::Display::fmt(&encoded, f) fmt::Display::fmt(&encoded, f)
} }

View File

@ -98,7 +98,7 @@ impl Charset {
} }
impl Display for Charset { impl Display for Charset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.label()) f.write_str(self.label())
} }
} }

View File

@ -27,7 +27,7 @@ pub enum Encoding {
} }
impl fmt::Display for Encoding { impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match *self { f.write_str(match *self {
Chunked => "chunked", Chunked => "chunked",
Brotli => "br", Brotli => "br",

View File

@ -113,7 +113,7 @@ impl EntityTag {
} }
impl Display for EntityTag { impl Display for EntityTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.weak { if self.weak {
write!(f, "W/\"{}\"", self.tag) write!(f, "W/\"{}\"", self.tag)
} else { } else {

View File

@ -28,7 +28,7 @@ impl FromStr for HttpDate {
} }
impl Display for HttpDate { impl Display for HttpDate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0.to_utc().rfc822(), f) fmt::Display::fmt(&self.0.to_utc().rfc822(), f)
} }
} }

View File

@ -53,7 +53,7 @@ impl<T: PartialEq> cmp::PartialOrd for QualityItem<T> {
} }
impl<T: fmt::Display> fmt::Display for QualityItem<T> { impl<T: fmt::Display> fmt::Display for QualityItem<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.item, f)?; fmt::Display::fmt(&self.item, f)?;
match self.quality.0 { match self.quality.0 {
1000 => Ok(()), 1000 => Ok(()),

View File

@ -25,10 +25,10 @@ pub trait HttpMessage: Sized {
fn take_payload(&mut self) -> Payload<Self::Stream>; fn take_payload(&mut self) -> Payload<Self::Stream>;
/// Request's extensions container /// Request's extensions container
fn extensions(&self) -> Ref<Extensions>; fn extensions(&self) -> Ref<'_, Extensions>;
/// Mutable reference to a the request's extensions container /// Mutable reference to a the request's extensions container
fn extensions_mut(&self) -> RefMut<Extensions>; fn extensions_mut(&self) -> RefMut<'_, Extensions>;
#[doc(hidden)] #[doc(hidden)]
/// Get a header /// Get a header
@ -105,7 +105,7 @@ pub trait HttpMessage: Sized {
/// Load request cookies. /// Load request cookies.
#[inline] #[inline]
fn cookies(&self) -> Result<Ref<Vec<Cookie<'static>>>, CookieParseError> { fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
if self.extensions().get::<Cookies>().is_none() { if self.extensions().get::<Cookies>().is_none() {
let mut cookies = Vec::new(); let mut cookies = Vec::new();
for hdr in self.headers().get_all(header::COOKIE) { for hdr in self.headers().get_all(header::COOKIE) {
@ -153,12 +153,12 @@ where
} }
/// Request's extensions container /// Request's extensions container
fn extensions(&self) -> Ref<Extensions> { fn extensions(&self) -> Ref<'_, Extensions> {
(**self).extensions() (**self).extensions()
} }
/// Mutable reference to a the request's extensions container /// Mutable reference to a the request's extensions container
fn extensions_mut(&self) -> RefMut<Extensions> { fn extensions_mut(&self) -> RefMut<'_, Extensions> {
(**self).extensions_mut() (**self).extensions_mut()
} }
} }

View File

@ -1,4 +1,5 @@
//! Basic http primitives for actix-net framework. //! Basic http primitives for actix-net framework.
#![deny(rust_2018_idioms, warnings)]
#![allow( #![allow(
clippy::type_complexity, clippy::type_complexity,
clippy::too_many_arguments, clippy::too_many_arguments,

View File

@ -78,13 +78,13 @@ impl Head for RequestHead {
impl RequestHead { impl RequestHead {
/// Message extensions /// Message extensions
#[inline] #[inline]
pub fn extensions(&self) -> Ref<Extensions> { pub fn extensions(&self) -> Ref<'_, Extensions> {
self.extensions.borrow() self.extensions.borrow()
} }
/// Mutable reference to a the message's extensions /// Mutable reference to a the message's extensions
#[inline] #[inline]
pub fn extensions_mut(&self) -> RefMut<Extensions> { pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.extensions.borrow_mut() self.extensions.borrow_mut()
} }
@ -237,13 +237,13 @@ impl ResponseHead {
/// Message extensions /// Message extensions
#[inline] #[inline]
pub fn extensions(&self) -> Ref<Extensions> { pub fn extensions(&self) -> Ref<'_, Extensions> {
self.extensions.borrow() self.extensions.borrow()
} }
/// Mutable reference to a the message's extensions /// Mutable reference to a the message's extensions
#[inline] #[inline]
pub fn extensions_mut(&self) -> RefMut<Extensions> { pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.extensions.borrow_mut() self.extensions.borrow_mut()
} }

View File

@ -56,7 +56,10 @@ where
type Item = Result<Bytes, PayloadError>; type Item = Result<Bytes, PayloadError>;
#[inline] #[inline]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
match self.get_mut() { match self.get_mut() {
Payload::None => Poll::Ready(None), Payload::None => Poll::Ready(None),
Payload::H1(ref mut pl) => pl.readany(cx), Payload::H1(ref mut pl) => pl.readany(cx),

View File

@ -25,13 +25,13 @@ impl<P> HttpMessage for Request<P> {
/// Request extensions /// Request extensions
#[inline] #[inline]
fn extensions(&self) -> Ref<Extensions> { fn extensions(&self) -> Ref<'_, Extensions> {
self.head.extensions() self.head.extensions()
} }
/// Mutable reference to a the request's extensions /// Mutable reference to a the request's extensions
#[inline] #[inline]
fn extensions_mut(&self) -> RefMut<Extensions> { fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.head.extensions_mut() self.head.extensions_mut()
} }
@ -165,7 +165,7 @@ impl<P> Request<P> {
} }
impl<P> fmt::Debug for Request<P> { impl<P> fmt::Debug for Request<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!( writeln!(
f, f,
"\nRequest {:?} {}:{}", "\nRequest {:?} {}:{}",

View File

@ -130,7 +130,7 @@ impl<B> Response<B> {
/// Get an iterator for the cookies set by this response /// Get an iterator for the cookies set by this response
#[inline] #[inline]
pub fn cookies(&self) -> CookieIter { pub fn cookies(&self) -> CookieIter<'_> {
CookieIter { CookieIter {
iter: self.head.headers.get_all(header::SET_COOKIE), iter: self.head.headers.get_all(header::SET_COOKIE),
} }
@ -138,7 +138,7 @@ impl<B> Response<B> {
/// Add a cookie to this response /// Add a cookie to this response
#[inline] #[inline]
pub fn add_cookie(&mut self, cookie: &Cookie) -> Result<(), HttpError> { pub fn add_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
let h = &mut self.head.headers; let h = &mut self.head.headers;
HeaderValue::from_str(&cookie.to_string()) HeaderValue::from_str(&cookie.to_string())
.map(|c| { .map(|c| {
@ -186,13 +186,13 @@ impl<B> Response<B> {
/// Responses extensions /// Responses extensions
#[inline] #[inline]
pub fn extensions(&self) -> Ref<Extensions> { pub fn extensions(&self) -> Ref<'_, Extensions> {
self.head.extensions.borrow() self.head.extensions.borrow()
} }
/// Mutable reference to a the response's extensions /// Mutable reference to a the response's extensions
#[inline] #[inline]
pub fn extensions_mut(&mut self) -> RefMut<Extensions> { pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
self.head.extensions.borrow_mut() self.head.extensions.borrow_mut()
} }
@ -265,7 +265,7 @@ impl<B> Response<B> {
} }
impl<B: MessageBody> fmt::Debug for Response<B> { impl<B: MessageBody> fmt::Debug for Response<B> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = writeln!( let res = writeln!(
f, f,
"\nResponse {:?} {}{}", "\nResponse {:?} {}{}",
@ -285,7 +285,7 @@ impl<B: MessageBody> fmt::Debug for Response<B> {
impl Future for Response { impl Future for Response {
type Output = Result<Response, Error>; type Output = Result<Response, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(Ok(Response { Poll::Ready(Ok(Response {
head: self.head.take(), head: self.head.take(),
body: self.body.take_body(), body: self.body.take_body(),
@ -354,7 +354,6 @@ impl ResponseBuilder {
/// )) /// ))
/// .finish()) /// .finish())
/// } /// }
/// fn main() {}
/// ``` /// ```
#[doc(hidden)] #[doc(hidden)]
pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self { pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self {
@ -380,7 +379,6 @@ impl ResponseBuilder {
/// .header(http::header::CONTENT_TYPE, "application/json") /// .header(http::header::CONTENT_TYPE, "application/json")
/// .finish() /// .finish()
/// } /// }
/// fn main() {}
/// ``` /// ```
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
where where
@ -413,7 +411,6 @@ impl ResponseBuilder {
/// .set_header(http::header::CONTENT_TYPE, "application/json") /// .set_header(http::header::CONTENT_TYPE, "application/json")
/// .finish() /// .finish()
/// } /// }
/// fn main() {}
/// ``` /// ```
pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where where
@ -588,14 +585,14 @@ impl ResponseBuilder {
/// Responses extensions /// Responses extensions
#[inline] #[inline]
pub fn extensions(&self) -> Ref<Extensions> { pub fn extensions(&self) -> Ref<'_, Extensions> {
let head = self.head.as_ref().expect("cannot reuse response builder"); let head = self.head.as_ref().expect("cannot reuse response builder");
head.extensions.borrow() head.extensions.borrow()
} }
/// Mutable reference to a the response's extensions /// Mutable reference to a the response's extensions
#[inline] #[inline]
pub fn extensions_mut(&mut self) -> RefMut<Extensions> { pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
let head = self.head.as_ref().expect("cannot reuse response builder"); let head = self.head.as_ref().expect("cannot reuse response builder");
head.extensions.borrow_mut() head.extensions.borrow_mut()
} }
@ -765,13 +762,13 @@ impl<'a> From<&'a ResponseHead> for ResponseBuilder {
impl Future for ResponseBuilder { impl Future for ResponseBuilder {
type Output = Result<Response, Error>; type Output = Result<Response, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(Ok(self.finish())) Poll::Ready(Ok(self.finish()))
} }
} }
impl fmt::Debug for ResponseBuilder { impl fmt::Debug for ResponseBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let head = self.head.as_ref().unwrap(); let head = self.head.as_ref().unwrap();
let res = writeln!( let res = writeln!(

View File

@ -403,7 +403,7 @@ where
type Output = type Output =
Result<HttpServiceHandler<T, S::Service, B, X::Service, U::Service>, ()>; Result<HttpServiceHandler<T, S::Service, B, X::Service, U::Service>, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.as_mut().project(); let mut this = self.as_mut().project();
if let Some(fut) = this.fut_ex.as_pin_mut() { if let Some(fut) = this.fut_ex.as_pin_mut() {
@ -499,7 +499,7 @@ where
type Error = DispatchError; type Error = DispatchError;
type Future = HttpServiceHandlerResponse<T, S, B, X, U>; type Future = HttpServiceHandlerResponse<T, S, B, X, U>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let ready = self let ready = self
.expect .expect
.poll_ready(cx) .poll_ready(cx)
@ -619,7 +619,7 @@ where
{ {
type Output = Result<(), DispatchError>; type Output = Result<(), DispatchError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.project().state.poll(cx) self.project().state.poll(cx)
} }
} }
@ -639,7 +639,7 @@ where
#[project] #[project]
fn poll( fn poll(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
cx: &mut Context, cx: &mut Context<'_>,
) -> Poll<Result<(), DispatchError>> { ) -> Poll<Result<(), DispatchError>> {
#[project] #[project]
match self.as_mut().project() { match self.as_mut().project() {

View File

@ -21,8 +21,6 @@ use crate::Request;
/// Test `Request` builder /// Test `Request` builder
/// ///
/// ```rust,ignore /// ```rust,ignore
/// # extern crate http;
/// # extern crate actix_web;
/// # use http::{header, StatusCode}; /// # use http::{header, StatusCode};
/// # use actix_web::*; /// # use actix_web::*;
/// use actix_web::test::TestRequest; /// use actix_web::test::TestRequest;
@ -35,15 +33,13 @@ use crate::Request;
/// } /// }
/// } /// }
/// ///
/// fn main() { /// let resp = TestRequest::with_header("content-type", "text/plain")
/// let resp = TestRequest::with_header("content-type", "text/plain") /// .run(&index)
/// .run(&index) /// .unwrap();
/// .unwrap(); /// assert_eq!(resp.status(), StatusCode::OK);
/// assert_eq!(resp.status(), StatusCode::OK);
/// ///
/// let resp = TestRequest::default().run(&index).unwrap(); /// let resp = TestRequest::default().run(&index).unwrap();
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST); /// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// }
/// ``` /// ```
pub struct TestRequest(Option<Inner>); pub struct TestRequest(Option<Inner>);

View File

@ -51,7 +51,7 @@ pub(crate) fn apply_mask(buf: &mut [u8], mask_u32: u32) {
// inefficient, it could be done better. The compiler does not understand that // inefficient, it could be done better. The compiler does not understand that
// a `ShortSlice` must be smaller than a u64. // a `ShortSlice` must be smaller than a u64.
#[allow(clippy::needless_pass_by_value)] #[allow(clippy::needless_pass_by_value)]
fn xor_short(buf: ShortSlice, mask: u64) { fn xor_short(buf: ShortSlice<'_>, mask: u64) {
// Unsafe: we know that a `ShortSlice` fits in a u64 // Unsafe: we know that a `ShortSlice` fits in a u64
unsafe { unsafe {
let (ptr, len) = (buf.0.as_mut_ptr(), buf.0.len()); let (ptr, len) = (buf.0.as_mut_ptr(), buf.0.len());
@ -77,7 +77,7 @@ unsafe fn cast_slice(buf: &mut [u8]) -> &mut [u64] {
#[inline] #[inline]
// Splits a slice into three parts: an unaligned short head and tail, plus an aligned // Splits a slice into three parts: an unaligned short head and tail, plus an aligned
// u64 mid section. // u64 mid section.
fn align_buf(buf: &mut [u8]) -> (ShortSlice, &mut [u64], ShortSlice) { fn align_buf(buf: &mut [u8]) -> (ShortSlice<'_>, &mut [u64], ShortSlice<'_>) {
let start_ptr = buf.as_ptr() as usize; let start_ptr = buf.as_ptr() as usize;
let end_ptr = start_ptr + buf.len(); let end_ptr = start_ptr + buf.len();

View File

@ -24,7 +24,7 @@ pub enum OpCode {
} }
impl fmt::Display for OpCode { impl fmt::Display for OpCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
Continue => write!(f, "CONTINUE"), Continue => write!(f, "CONTINUE"),
Text => write!(f, "TEXT"), Text => write!(f, "TEXT"),

View File

@ -45,7 +45,7 @@ where
{ {
type Output = Result<(), FramedTransportError<S::Error, Codec>>; type Output = Result<(), FramedTransportError<S::Error, Codec>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.inner).poll(cx) Pin::new(&mut self.inner).poll(cx)
} }
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-identity" name = "actix-identity"
version = "0.2.0-alpha.1" version = "0.2.0-alpha.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Identity service for actix web framework." description = "Identity service for actix web framework."
readme = "README.md" readme = "README.md"
@ -17,14 +17,14 @@ name = "actix_identity"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "2.0.0-alpha.2", default-features = false, features = ["secure-cookies"] } actix-web = { version = "2.0.0-alpha.3", default-features = false, features = ["secure-cookies"] }
actix-service = "1.0.0-alpha.2" actix-service = "1.0.0-alpha.3"
futures = "0.3.1" futures = "0.3.1"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
time = "0.1.42" time = "0.1.42"
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.2" actix-rt = "1.0.0-alpha.3"
actix-http = "0.3.0-alpha.2" actix-http = "1.0.0-alpha.3"
bytes = "0.5.2" bytes = "0.5.2"

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-multipart" name = "actix-multipart"
version = "0.2.0-alpha.2" version = "0.2.0-alpha.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Multipart support for actix web framework." description = "Multipart support for actix web framework."
readme = "README.md" readme = "README.md"
@ -18,9 +18,9 @@ name = "actix_multipart"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "2.0.0-alpha.2", default-features = false } actix-web = { version = "2.0.0-alpha.3", default-features = false }
actix-service = "1.0.0-alpha.2" actix-service = "1.0.0-alpha.3"
actix-utils = "1.0.0-alpha.2" actix-utils = "1.0.0-alpha.3"
bytes = "0.5.2" bytes = "0.5.2"
derive_more = "0.99.2" derive_more = "0.99.2"
httparse = "1.3" httparse = "1.3"
@ -31,5 +31,5 @@ time = "0.1"
twoway = "0.2" twoway = "0.2"
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.2" actix-rt = "1.0.0-alpha.3"
actix-http = "0.3.0-alpha.2" actix-http = "1.0.0-alpha.3"

View File

@ -12,7 +12,7 @@
//! [*Session*](struct.Session.html) extractor must be used. Session //! [*Session*](struct.Session.html) extractor must be used. Session
//! extractor allows us to get or set session data. //! extractor allows us to get or set session data.
//! //!
//! ```rust //! ```rust,no_run
//! use actix_web::{web, App, HttpServer, HttpResponse, Error}; //! use actix_web::{web, App, HttpServer, HttpResponse, Error};
//! use actix_session::{Session, CookieSession}; //! use actix_session::{Session, CookieSession};
//! //!
@ -28,8 +28,8 @@
//! Ok("Welcome!") //! Ok("Welcome!")
//! } //! }
//! //!
//! fn main() -> std::io::Result<()> { //! #[actix_rt::main]
//! # std::thread::spawn(|| //! async fn main() -> std::io::Result<()> {
//! HttpServer::new( //! HttpServer::new(
//! || App::new().wrap( //! || App::new().wrap(
//! CookieSession::signed(&[0; 32]) // <- create cookie based session middleware //! CookieSession::signed(&[0; 32]) // <- create cookie based session middleware
@ -37,9 +37,8 @@
//! ) //! )
//! .service(web::resource("/").to(|| HttpResponse::Ok()))) //! .service(web::resource("/").to(|| HttpResponse::Ok())))
//! .bind("127.0.0.1:59880")? //! .bind("127.0.0.1:59880")?
//! .run() //! .start()
//! # ); //! .await
//! # Ok(())
//! } //! }
//! ``` //! ```
use std::cell::RefCell; use std::cell::RefCell;

View File

@ -1,5 +1,9 @@
# Changes # Changes
## [1.0.4] - 2019-12-07
* Allow comma-separated websocket subprotocols without spaces (#1172)
## [1.0.3] - 2019-11-14 ## [1.0.3] - 2019-11-14
* Update actix-web and actix-http dependencies * Update actix-web and actix-http dependencies

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-web-actors" name = "actix-web-actors"
version = "1.0.3" version = "1.0.4"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix actors support for actix web framework." description = "Actix actors support for actix web framework."
readme = "README.md" readme = "README.md"

View File

@ -152,7 +152,8 @@ pub fn handshake_with_protocols(
.and_then(|req_protocols| { .and_then(|req_protocols| {
let req_protocols = req_protocols.to_str().ok()?; let req_protocols = req_protocols.to_str().ok()?;
req_protocols req_protocols
.split(", ") .split(',')
.map(|req_p| req_p.trim())
.find(|req_p| protocols.iter().any(|p| p == req_p)) .find(|req_p| protocols.iter().any(|p| p == req_p))
}); });
@ -736,5 +737,46 @@ mod tests {
.headers() .headers()
.get(&header::SEC_WEBSOCKET_PROTOCOL) .get(&header::SEC_WEBSOCKET_PROTOCOL)
); );
let req = TestRequest::default()
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
)
.header(
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
)
.header(
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"),
)
.header(
header::SEC_WEBSOCKET_KEY,
header::HeaderValue::from_static("13"),
)
.header(
header::SEC_WEBSOCKET_PROTOCOL,
header::HeaderValue::from_static("p1,p2,p3"),
)
.to_http_request();
let protocols = vec!["p3", "p2"];
assert_eq!(
StatusCode::SWITCHING_PROTOCOLS,
handshake_with_protocols(&req, &protocols)
.unwrap()
.finish()
.status()
);
assert_eq!(
Some(&header::HeaderValue::from_static("p2")),
handshake_with_protocols(&req, &protocols)
.unwrap()
.finish()
.headers()
.get(&header::SEC_WEBSOCKET_PROTOCOL)
);
} }
} }

View File

@ -19,6 +19,6 @@ proc-macro2 = "^1"
[dev-dependencies] [dev-dependencies]
actix-rt = { version = "1.0.0-alpha.2" } actix-rt = { version = "1.0.0-alpha.2" }
actix-web = { version = "2.0.0-alpha.2" } actix-web = { version = "2.0.0-alpha.2" }
actix-http = { version = "0.3.0-alpha.2", features=["openssl"] } actix-http = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.2", features=["openssl"] } actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
futures = { version = "0.3.1" } futures = { version = "0.3.1" }

View File

@ -1,5 +1,10 @@
# Changes # Changes
## [1.0.0-alpha.3]
* Migrate to `std::future`
## [0.2.8] - 2019-11-06 ## [0.2.8] - 2019-11-06
* Add support for setting query from Serialize type for client request. * Add support for setting query from Serialize type for client request.

View File

@ -1,6 +1,6 @@
[package] [package]
name = "awc" name = "awc"
version = "0.3.0-alpha.3" version = "1.0.0-alpha.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http client." description = "Actix http client."
readme = "README.md" readme = "README.md"
@ -21,10 +21,10 @@ name = "awc"
path = "src/lib.rs" path = "src/lib.rs"
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["openssl", "rustls", "brotli", "flate2-zlib"] features = ["openssl", "rustls", "flate2-zlib"]
[features] [features]
default = ["brotli", "flate2-zlib"] default = ["flate2-zlib"]
# openssl # openssl
openssl = ["open-ssl", "actix-http/openssl"] openssl = ["open-ssl", "actix-http/openssl"]
@ -32,9 +32,6 @@ openssl = ["open-ssl", "actix-http/openssl"]
# rustls # rustls
rustls = ["rust-tls", "actix-http/rustls"] rustls = ["rust-tls", "actix-http/rustls"]
# brotli encoding, requires c compiler
brotli = ["actix-http/brotli"]
# miniz-sys backend for flate2 crate # miniz-sys backend for flate2 crate
flate2-zlib = ["actix-http/flate2-zlib"] flate2-zlib = ["actix-http/flate2-zlib"]
@ -44,7 +41,7 @@ flate2-rust = ["actix-http/flate2-rust"]
[dependencies] [dependencies]
actix-codec = "0.2.0-alpha.3" actix-codec = "0.2.0-alpha.3"
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0-alpha.3"
actix-http = "0.3.0-alpha.3" actix-http = "1.0.0-alpha.3"
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0-alpha.3"
base64 = "0.11" base64 = "0.11"
@ -64,12 +61,12 @@ rust-tls = { version = "0.16.0", package="rustls", optional = true, features = [
[dev-dependencies] [dev-dependencies]
actix-connect = { version = "1.0.0-alpha.3", features=["openssl"] } actix-connect = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-web = { version = "2.0.0-alpha.3", features=["openssl"] } actix-web = { version = "2.0.0-alpha.3", features=["openssl"] }
actix-http = { version = "0.3.0-alpha.3", features=["openssl"] } actix-http = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.3", features=["openssl"] } actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-utils = "1.0.0-alpha.3" actix-utils = "1.0.0-alpha.3"
actix-server = { version = "1.0.0-alpha.3" } actix-server = { version = "1.0.0-alpha.3" }
actix-tls = { version = "1.0.0-alpha.3", features=["openssl", "rustls"] } actix-tls = { version = "1.0.0-alpha.3", features=["openssl", "rustls"] }
brotli2 = { version="0.3.2" } brotli = "3.3.0"
flate2 = { version="1.0.2" } flate2 = { version="1.0.2" }
env_logger = "0.6" env_logger = "0.6"
webpki = { version = "0.21" } webpki = { version = "0.21" }

View File

@ -195,7 +195,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin> AsyncSocket for Socket<T> {
pub struct BoxedSocket(Box<dyn AsyncSocket>); pub struct BoxedSocket(Box<dyn AsyncSocket>);
impl fmt::Debug for BoxedSocket { impl fmt::Debug for BoxedSocket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BoxedSocket") write!(f, "BoxedSocket")
} }
} }

View File

@ -1,4 +1,9 @@
#![allow(clippy::borrow_interior_mutable_const)] #![deny(rust_2018_idioms, warnings)]
#![allow(
clippy::type_complexity,
clippy::borrow_interior_mutable_const,
clippy::needless_doctest_main
)]
//! An HTTP Client //! An HTTP Client
//! //!
//! ```rust //! ```rust
@ -11,9 +16,9 @@
//! let mut client = Client::default(); //! let mut client = Client::default();
//! //!
//! let response = client.get("http://www.rust-lang.org") // <- Create request builder //! let response = client.get("http://www.rust-lang.org") // <- Create request builder
//! .header("User-Agent", "Actix-web") //! .header("User-Agent", "Actix-web")
//! .send() // <- Send http request //! .send() // <- Send http request
//! .await; //! .await;
//! //!
//! println!("Response: {:?}", response); //! println!("Response: {:?}", response);
//! } //! }
@ -50,22 +55,18 @@ use self::connect::{Connect, ConnectorWrapper};
/// An HTTP Client /// An HTTP Client
/// ///
/// ```rust /// ```rust
/// use actix_rt::System;
/// use awc::Client; /// use awc::Client;
/// ///
/// fn main() { /// #[actix_rt::main]
/// System::new("test").block_on(async { /// async fn main() {
/// let mut client = Client::default(); /// let mut client = Client::default();
/// ///
/// client.get("http://www.rust-lang.org") // <- Create request builder /// let res = client.get("http://www.rust-lang.org") // <- Create request builder
/// .header("User-Agent", "Actix-web") /// .header("User-Agent", "Actix-web")
/// .send() // <- Send http request /// .send() // <- Send http request
/// .await /// .await; // <- send request and wait for response
/// .and_then(|response| { // <- server http response ///
/// println!("Response: {:?}", response); /// println!("Response: {:?}", res);
/// Ok(())
/// })
/// });
/// } /// }
/// ``` /// ```
#[derive(Clone)] #[derive(Clone)]

View File

@ -23,13 +23,10 @@ use crate::frozen::FrozenClientRequest;
use crate::sender::{PrepForSendingError, RequestSender, SendClientRequest}; use crate::sender::{PrepForSendingError, RequestSender, SendClientRequest};
use crate::ClientConfig; use crate::ClientConfig;
#[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
const HTTPS_ENCODING: &str = "br, gzip, deflate"; const HTTPS_ENCODING: &str = "br, gzip, deflate";
#[cfg(all( #[cfg(not(any(feature = "flate2-zlib", feature = "flate2-rust")))]
any(feature = "flate2-zlib", feature = "flate2-rust"), const HTTPS_ENCODING: &str = "br";
not(feature = "brotli")
))]
const HTTPS_ENCODING: &str = "gzip, deflate";
/// An HTTP Client request builder /// An HTTP Client request builder
/// ///
@ -544,31 +541,23 @@ impl ClientRequest {
let mut slf = self; let mut slf = self;
// enable br only for https if slf.response_decompress {
#[cfg(any( let https = slf
feature = "brotli", .head
feature = "flate2-zlib", .uri
feature = "flate2-rust" .scheme()
))] .map(|s| s == &uri::Scheme::HTTPS)
{ .unwrap_or(true);
if slf.response_decompress {
let https = slf
.head
.uri
.scheme()
.map(|s| s == &uri::Scheme::HTTPS)
.unwrap_or(true);
if https { if https {
slf = slf.set_header_if_none(header::ACCEPT_ENCODING, HTTPS_ENCODING) slf = slf.set_header_if_none(header::ACCEPT_ENCODING, HTTPS_ENCODING)
} else { } else {
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
{ {
slf = slf slf =
.set_header_if_none(header::ACCEPT_ENCODING, "gzip, deflate") slf.set_header_if_none(header::ACCEPT_ENCODING, "gzip, deflate")
} }
}; };
}
} }
Ok(slf) Ok(slf)
@ -576,7 +565,7 @@ impl ClientRequest {
} }
impl fmt::Debug for ClientRequest { impl fmt::Debug for ClientRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!( writeln!(
f, f,
"\nClientRequest {:?} {}:{}", "\nClientRequest {:?} {}:{}",

View File

@ -29,11 +29,11 @@ impl<S> HttpMessage for ClientResponse<S> {
&self.head.headers &self.head.headers
} }
fn extensions(&self) -> Ref<Extensions> { fn extensions(&self) -> Ref<'_, Extensions> {
self.head.extensions() self.head.extensions()
} }
fn extensions_mut(&self) -> RefMut<Extensions> { fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.head.extensions_mut() self.head.extensions_mut()
} }
@ -43,7 +43,7 @@ impl<S> HttpMessage for ClientResponse<S> {
/// Load request cookies. /// Load request cookies.
#[inline] #[inline]
fn cookies(&self) -> Result<Ref<Vec<Cookie<'static>>>, CookieParseError> { fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
struct Cookies(Vec<Cookie<'static>>); struct Cookies(Vec<Cookie<'static>>);
if self.extensions().get::<Cookies>().is_none() { if self.extensions().get::<Cookies>().is_none() {
@ -131,13 +131,16 @@ where
{ {
type Item = Result<Bytes, PayloadError>; type Item = Result<Bytes, PayloadError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().payload).poll_next(cx) Pin::new(&mut self.get_mut().payload).poll_next(cx)
} }
} }
impl<S> fmt::Debug for ClientResponse<S> { impl<S> fmt::Debug for ClientResponse<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?; writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?;
writeln!(f, " headers:")?; writeln!(f, " headers:")?;
for (key, val) in self.headers().iter() { for (key, val) in self.headers().iter() {
@ -203,7 +206,7 @@ where
{ {
type Output = Result<Bytes, PayloadError>; type Output = Result<Bytes, PayloadError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
if let Some(err) = this.err.take() { if let Some(err) = this.err.take() {
@ -295,7 +298,7 @@ where
{ {
type Output = Result<U, JsonPayloadError>; type Output = Result<U, JsonPayloadError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.err.take() { if let Some(err) = self.err.take() {
return Poll::Ready(Err(err)); return Poll::Ready(Err(err));
} }
@ -335,7 +338,7 @@ where
{ {
type Output = Result<Bytes, PayloadError>; type Output = Result<Bytes, PayloadError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
loop { loop {

View File

@ -62,7 +62,7 @@ impl SendClientRequest {
response_decompress: bool, response_decompress: bool,
timeout: Option<Duration>, timeout: Option<Duration>,
) -> SendClientRequest { ) -> SendClientRequest {
let delay = timeout.map(|t| delay_for(t)); let delay = timeout.map(delay_for);
SendClientRequest::Fut(send, delay, response_decompress) SendClientRequest::Fut(send, delay, response_decompress)
} }
} }
@ -71,7 +71,7 @@ impl Future for SendClientRequest {
type Output = type Output =
Result<ClientResponse<Decoder<Payload<PayloadStream>>>, SendRequestError>; Result<ClientResponse<Decoder<Payload<PayloadStream>>>, SendRequestError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
match this { match this {

View File

@ -304,7 +304,7 @@ impl WebsocketsRequest {
let (head, framed) = if let Some(to) = self.config.timeout { let (head, framed) = if let Some(to) = self.config.timeout {
timeout(to, fut) timeout(to, fut)
.await .await
.map_err(|_| SendRequestError::Timeout.into()) .map_err(|_| SendRequestError::Timeout)
.and_then(|res| res)? .and_then(|res| res)?
} else { } else {
fut.await? fut.await?
@ -379,7 +379,7 @@ impl WebsocketsRequest {
} }
impl fmt::Debug for WebsocketsRequest { impl fmt::Debug for WebsocketsRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!( writeln!(
f, f,
"\nWebsocketsRequest {}:{}", "\nWebsocketsRequest {}:{}",

View File

@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use brotli2::write::BrotliEncoder; use brotli::CompressorWriter;
use bytes::Bytes; use bytes::Bytes;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
use flate2::write::GzEncoder; use flate2::write::GzEncoder;
@ -514,9 +514,9 @@ async fn test_client_brotli_encoding() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(
|data: Bytes| { |data: Bytes| {
let mut e = BrotliEncoder::new(Vec::new(), 5); let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
e.write_all(&data).unwrap(); e.write_all(&data).unwrap();
let data = e.finish().unwrap(); let data = e.into_inner();
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "br") .header("content-encoding", "br")
.body(data) .body(data)
@ -534,41 +534,37 @@ async fn test_client_brotli_encoding() {
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
} }
// #[actix_rt::test] #[actix_rt::test]
// async fn test_client_brotli_encoding_large_random() { async fn test_client_brotli_encoding_large_random() {
// let data = rand::thread_rng() let data = rand::thread_rng()
// .sample_iter(&rand::distributions::Alphanumeric) .sample_iter(&rand::distributions::Alphanumeric)
// .take(70_000) .take(70_000)
// .collect::<String>(); .collect::<String>();
// let srv = test::TestServer::start(|app| { let srv = TestServer::start(|| {
// app.handler(|req: &HttpRequest| { HttpService::new(App::new().service(web::resource("/").route(web::to(
// req.body() |data: Bytes| {
// .and_then(move |bytes: Bytes| { let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
// Ok(HttpResponse::Ok() e.write_all(&data).unwrap();
// .content_encoding(http::ContentEncoding::Gzip) let data = e.into_inner();
// .body(bytes)) HttpResponse::Ok()
// }) .header("content-encoding", "br")
// .responder() .body(data)
// }) },
// }); ))))
.tcp()
});
// // client request // client request
// let request = srv let mut response = srv.post("/").send_body(data.clone()).await.unwrap();
// .client(http::Method::POST, "/") assert!(response.status().is_success());
// .content_encoding(http::ContentEncoding::Br)
// .body(data.clone())
// .unwrap();
// let response = request.send().await.unwrap();
// assert!(response.status().is_success());
// // read response // read response
// let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
// assert_eq!(bytes.len(), data.len()); assert_eq!(bytes.len(), data.len());
// assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
// } }
// #[cfg(feature = "brotli")]
// #[actix_rt::test] // #[actix_rt::test]
// async fn test_client_deflate_encoding() { // async fn test_client_deflate_encoding() {
// let srv = test::TestServer::start(|app| { // let srv = test::TestServer::start(|app| {

View File

@ -38,7 +38,7 @@ pub struct App<T, B> {
data_factories: Vec<FnDataFactory>, data_factories: Vec<FnDataFactory>,
config: AppConfigInner, config: AppConfigInner,
external: Vec<ResourceDef>, external: Vec<ResourceDef>,
_t: PhantomData<(B)>, _t: PhantomData<B>,
} }
impl App<AppEntry, Body> { impl App<AppEntry, Body> {
@ -93,13 +93,11 @@ where
/// HttpResponse::Ok() /// HttpResponse::Ok()
/// } /// }
/// ///
/// fn main() { /// let app = App::new()
/// let app = App::new() /// .data(MyData{ counter: Cell::new(0) })
/// .data(MyData{ counter: Cell::new(0) }) /// .service(
/// .service( /// web::resource("/index.html").route(
/// web::resource("/index.html").route( /// web::get().to(index)));
/// web::get().to(index)));
/// }
/// ``` /// ```
pub fn data<U: 'static>(mut self, data: U) -> Self { pub fn data<U: 'static>(mut self, data: U) -> Self {
self.data.push(Box::new(Data::new(data))); self.data.push(Box::new(Data::new(data)));

View File

@ -154,7 +154,7 @@ where
{ {
type Output = Result<AppInitService<T::Service, B>, ()>; type Output = Result<AppInitService<T::Service, B>, ()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
// async data factories // async data factories
@ -220,7 +220,7 @@ where
type Error = T::Error; type Error = T::Error;
type Future = T::Future; type Future = T::Future;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx) self.service.poll_ready(cx)
} }
@ -310,7 +310,7 @@ enum CreateAppRoutingItem {
impl Future for AppRoutingFactoryResponse { impl Future for AppRoutingFactoryResponse {
type Output = Result<AppRouting, ()>; type Output = Result<AppRouting, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut done = true; let mut done = true;
if let Some(ref mut fut) = self.default_fut { if let Some(ref mut fut) = self.default_fut {
@ -381,7 +381,7 @@ impl Service for AppRouting {
type Error = Error; type Error = Error;
type Future = BoxResponse; type Future = BoxResponse;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.ready.is_none() { if self.ready.is_none() {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} else { } else {

View File

@ -195,6 +195,7 @@ macro_rules! tuple_from_req ({$fut_type:ident, $(($n:tt, $T:ident)),+} => {
/// FromRequest implementation for tuple /// FromRequest implementation for tuple
#[doc(hidden)] #[doc(hidden)]
#[allow(unused_parens)]
impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+) impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+)
{ {
type Error = Error; type Error = Error;
@ -220,7 +221,7 @@ macro_rules! tuple_from_req ({$fut_type:ident, $(($n:tt, $T:ident)),+} => {
{ {
type Output = Result<($($T,)+), Error>; type Output = Result<($($T,)+), Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
let mut ready = true; let mut ready = true;

View File

@ -259,16 +259,15 @@ impl Guard for HeaderGuard {
/// Return predicate that matches if request contains specified Host name. /// Return predicate that matches if request contains specified Host name.
/// ///
/// ```rust,ignore /// ```rust
/// # extern crate actix_web; /// use actix_web::{web, guard::Host, App, HttpResponse};
/// use actix_web::{guard::Host, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// App::new().resource("/index.html", |r| { /// App::new().service(
/// r.route() /// web::resource("/index.html")
/// .guard(Host("www.rust-lang.org")) /// .guard(Host("www.rust-lang.org"))
/// .f(|_| HttpResponse::MethodNotAllowed()) /// .to(|| HttpResponse::MethodNotAllowed())
/// }); /// );
/// } /// }
/// ``` /// ```
pub fn Host<H: AsRef<str>>(host: H) -> HostGuard { pub fn Host<H: AsRef<str>>(host: H) -> HostGuard {

View File

@ -85,7 +85,7 @@ where
type Error = Infallible; type Error = Infallible;
type Future = HandlerServiceResponse<R, O>; type Future = HandlerServiceResponse<R, O>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
@ -119,7 +119,7 @@ where
{ {
type Output = Result<ServiceResponse, Infallible>; type Output = Result<ServiceResponse, Infallible>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.as_mut().project(); let this = self.as_mut().project();
if let Some(fut) = this.fut2.as_pin_mut() { if let Some(fut) = this.fut2.as_pin_mut() {
@ -203,7 +203,7 @@ where
type Error = (Error, ServiceRequest); type Error = (Error, ServiceRequest);
type Future = ExtractResponse<T, S>; type Future = ExtractResponse<T, S>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
@ -240,7 +240,7 @@ where
{ {
type Output = Result<ServiceResponse, (Error, ServiceRequest)>; type Output = Result<ServiceResponse, (Error, ServiceRequest)>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.as_mut().project(); let this = self.as_mut().project();
if let Some(fut) = this.fut_s.as_pin_mut() { if let Some(fut) = this.fut_s.as_pin_mut() {

View File

@ -1,24 +1,27 @@
#![allow(clippy::borrow_interior_mutable_const)] #![deny(rust_2018_idioms, warnings)]
#![allow(
clippy::needless_doctest_main,
clippy::type_complexity,
clippy::borrow_interior_mutable_const
)]
//! Actix web is a small, pragmatic, and extremely fast web framework //! Actix web is a small, pragmatic, and extremely fast web framework
//! for Rust. //! for Rust.
//! //!
//! ```rust //! ```rust,no_run
//! use actix_web::{web, App, Responder, HttpServer}; //! use actix_web::{web, App, Responder, HttpServer};
//! # use std::thread;
//! //!
//! async fn index(info: web::Path<(String, u32)>) -> impl Responder { //! async fn index(info: web::Path<(String, u32)>) -> impl Responder {
//! format!("Hello {}! id:{}", info.0, info.1) //! format!("Hello {}! id:{}", info.0, info.1)
//! } //! }
//! //!
//! fn main() -> std::io::Result<()> { //! #[actix_rt::main]
//! # thread::spawn(|| { //! async fn main() -> std::io::Result<()> {
//! HttpServer::new(|| App::new().service( //! HttpServer::new(|| App::new().service(
//! web::resource("/{name}/{id}/index.html").to(index)) //! web::resource("/{name}/{id}/index.html").to(index))
//! ) //! )
//! .bind("127.0.0.1:8080")? //! .bind("127.0.0.1:8080")?
//! .run() //! .start()
//! # }); //! .await
//! # Ok(())
//! } //! }
//! ``` //! ```
//! //!
@ -72,8 +75,6 @@
//! * `rustls` - enables ssl support via `rustls` crate, supports `http/2` //! * `rustls` - enables ssl support via `rustls` crate, supports `http/2`
//! * `secure-cookies` - enables secure cookies support, includes `ring` crate as //! * `secure-cookies` - enables secure cookies support, includes `ring` crate as
//! dependency //! dependency
//! * `brotli` - enables `brotli` compression support, requires `c`
//! compiler (default enabled)
//! * `flate2-zlib` - enables `gzip`, `deflate` compression support, requires //! * `flate2-zlib` - enables `gzip`, `deflate` compression support, requires
//! `c` compiler (default enabled) //! `c` compiler (default enabled)
//! * `flate2-rust` - experimental rust based implementation for //! * `flate2-rust` - experimental rust based implementation for
@ -171,7 +172,6 @@ pub mod client {
//! An HTTP Client //! An HTTP Client
//! //!
//! ```rust //! ```rust
//! use actix_rt::System;
//! use actix_web::client::Client; //! use actix_web::client::Client;
//! //!
//! #[actix_rt::main] //! #[actix_rt::main]

View File

@ -106,7 +106,7 @@ where
type Error = Error; type Error = Error;
type Future = CompressResponse<S, B>; type Future = CompressResponse<S, B>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx) self.service.poll_ready(cx)
} }
@ -140,7 +140,7 @@ where
#[pin] #[pin]
fut: S::Future, fut: S::Future,
encoding: ContentEncoding, encoding: ContentEncoding,
_t: PhantomData<(B)>, _t: PhantomData<B>,
} }
impl<S, B> Future for CompressResponse<S, B> impl<S, B> Future for CompressResponse<S, B>
@ -150,7 +150,7 @@ where
{ {
type Output = Result<ServiceResponse<Encoder<B>>, Error>; type Output = Result<ServiceResponse<Encoder<B>>, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
match futures::ready!(this.fut.poll(cx)) { match futures::ready!(this.fut.poll(cx)) {
@ -178,6 +178,7 @@ struct AcceptEncoding {
impl Eq for AcceptEncoding {} impl Eq for AcceptEncoding {}
impl Ord for AcceptEncoding { impl Ord for AcceptEncoding {
#[allow(clippy::comparison_chain)]
fn cmp(&self, other: &AcceptEncoding) -> cmp::Ordering { fn cmp(&self, other: &AcceptEncoding) -> cmp::Ordering {
if self.quality > other.quality { if self.quality > other.quality {
cmp::Ordering::Less cmp::Ordering::Less

View File

@ -76,7 +76,7 @@ where
type Error = E::Error; type Error = E::Error;
type Future = Either<E::Future, D::Future>; type Future = Either<E::Future, D::Future>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
use ConditionMiddleware::*; use ConditionMiddleware::*;
match self { match self {
Enable(service) => service.poll_ready(cx), Enable(service) => service.poll_ready(cx),

View File

@ -124,7 +124,7 @@ where
type Error = Error; type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx) self.service.poll_ready(cx)
} }

View File

@ -119,7 +119,7 @@ where
type Error = Error; type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx) self.service.poll_ready(cx)
} }

View File

@ -154,7 +154,7 @@ where
type Error = Error; type Error = Error;
type Future = LoggerResponse<S, B>; type Future = LoggerResponse<S, B>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx) self.service.poll_ready(cx)
} }
@ -204,7 +204,7 @@ where
{ {
type Output = Result<ServiceResponse<StreamLog<B>>, Error>; type Output = Result<ServiceResponse<StreamLog<B>>, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
let res = match futures::ready!(this.fut.poll(cx)) { let res = match futures::ready!(this.fut.poll(cx)) {
@ -248,7 +248,7 @@ pub struct StreamLog<B> {
impl<B> Drop for StreamLog<B> { impl<B> Drop for StreamLog<B> {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(ref format) = self.format { if let Some(ref format) = self.format {
let render = |fmt: &mut Formatter| { let render = |fmt: &mut Formatter<'_>| {
for unit in &format.0 { for unit in &format.0 {
unit.render(fmt, self.size, self.time)?; unit.render(fmt, self.size, self.time)?;
} }
@ -264,7 +264,7 @@ impl<B: MessageBody> MessageBody for StreamLog<B> {
self.body.size() self.body.size()
} }
fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<Result<Bytes, Error>>> { fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, Error>>> {
match self.body.poll_next(cx) { match self.body.poll_next(cx) {
Poll::Ready(Some(Ok(chunk))) => { Poll::Ready(Some(Ok(chunk))) => {
self.size += chunk.len(); self.size += chunk.len();
@ -364,7 +364,7 @@ pub enum FormatText {
impl FormatText { impl FormatText {
fn render( fn render(
&self, &self,
fmt: &mut Formatter, fmt: &mut Formatter<'_>,
size: usize, size: usize,
entry_time: time::Tm, entry_time: time::Tm,
) -> Result<(), fmt::Error> { ) -> Result<(), fmt::Error> {
@ -464,11 +464,11 @@ impl FormatText {
} }
pub(crate) struct FormatDisplay<'a>( pub(crate) struct FormatDisplay<'a>(
&'a dyn Fn(&mut Formatter) -> Result<(), fmt::Error>, &'a dyn Fn(&mut Formatter<'_>) -> Result<(), fmt::Error>,
); );
impl<'a> fmt::Display for FormatDisplay<'a> { impl<'a> fmt::Display for FormatDisplay<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> {
(self.0)(fmt) (self.0)(fmt)
} }
} }
@ -523,7 +523,7 @@ mod tests {
unit.render_response(&resp); unit.render_response(&resp);
} }
let render = |fmt: &mut Formatter| { let render = |fmt: &mut Formatter<'_>| {
for unit in &format.0 { for unit in &format.0 {
unit.render(fmt, 1024, now)?; unit.render(fmt, 1024, now)?;
} }
@ -555,7 +555,7 @@ mod tests {
} }
let entry_time = time::now(); let entry_time = time::now();
let render = |fmt: &mut Formatter| { let render = |fmt: &mut Formatter<'_>| {
for unit in &format.0 { for unit in &format.0 {
unit.render(fmt, 1024, entry_time)?; unit.render(fmt, 1024, entry_time)?;
} }
@ -582,7 +582,7 @@ mod tests {
unit.render_response(&resp); unit.render_response(&resp);
} }
let render = |fmt: &mut Formatter| { let render = |fmt: &mut Formatter<'_>| {
for unit in &format.0 { for unit in &format.0 {
unit.render(fmt, 1024, now)?; unit.render(fmt, 1024, now)?;
} }

View File

@ -68,7 +68,7 @@ where
type Error = Error; type Error = Error;
type Future = S::Future; type Future = S::Future;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx) self.service.poll_ready(cx)
} }
@ -88,7 +88,6 @@ where
Bytes::copy_from_slice(path.as_bytes()) Bytes::copy_from_slice(path.as_bytes())
}; };
parts.path_and_query = Some(PathAndQuery::from_maybe_shared(path).unwrap()); parts.path_and_query = Some(PathAndQuery::from_maybe_shared(path).unwrap());
drop(head);
let uri = Uri::from_parts(parts).unwrap(); let uri = Uri::from_parts(parts).unwrap();
req.match_info_mut().get_mut().update(&uri); req.match_info_mut().get_mut().update(&uri);

View File

@ -125,13 +125,13 @@ impl HttpRequest {
/// Request extensions /// Request extensions
#[inline] #[inline]
pub fn extensions(&self) -> Ref<Extensions> { pub fn extensions(&self) -> Ref<'_, Extensions> {
self.head().extensions() self.head().extensions()
} }
/// Mutable reference to a the request's extensions /// Mutable reference to a the request's extensions
#[inline] #[inline]
pub fn extensions_mut(&self) -> RefMut<Extensions> { pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.head().extensions_mut() self.head().extensions_mut()
} }
@ -197,7 +197,7 @@ impl HttpRequest {
/// This method panics if request's extensions container is already /// This method panics if request's extensions container is already
/// borrowed. /// borrowed.
#[inline] #[inline]
pub fn connection_info(&self) -> Ref<ConnectionInfo> { pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
ConnectionInfo::get(self.head(), &*self.app_config()) ConnectionInfo::get(self.head(), &*self.app_config())
} }
@ -239,13 +239,13 @@ impl HttpMessage for HttpRequest {
/// Request extensions /// Request extensions
#[inline] #[inline]
fn extensions(&self) -> Ref<Extensions> { fn extensions(&self) -> Ref<'_, Extensions> {
self.0.head.extensions() self.0.head.extensions()
} }
/// Mutable reference to a the request's extensions /// Mutable reference to a the request's extensions
#[inline] #[inline]
fn extensions_mut(&self) -> RefMut<Extensions> { fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.0.head.extensions_mut() self.0.head.extensions_mut()
} }
@ -299,7 +299,7 @@ impl FromRequest for HttpRequest {
} }
impl fmt::Debug for HttpRequest { impl fmt::Debug for HttpRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!( writeln!(
f, f,
"\nHttpRequest {:?} {}:{}", "\nHttpRequest {:?} {}:{}",

View File

@ -470,7 +470,7 @@ pub struct CreateResourceService {
impl Future for CreateResourceService { impl Future for CreateResourceService {
type Output = Result<ResourceService, ()>; type Output = Result<ResourceService, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut done = true; let mut done = true;
if let Some(ref mut fut) = self.default_fut { if let Some(ref mut fut) = self.default_fut {
@ -530,7 +530,7 @@ impl Service for ResourceService {
LocalBoxFuture<'static, Result<ServiceResponse, Error>>, LocalBoxFuture<'static, Result<ServiceResponse, Error>>,
>; >;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }

View File

@ -313,7 +313,7 @@ pub struct CustomResponderFut<T: Responder> {
impl<T: Responder> Future for CustomResponderFut<T> { impl<T: Responder> Future for CustomResponderFut<T> {
type Output = Result<Response, T::Error>; type Output = Result<Response, T::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
let mut res = match ready!(this.fut.poll(cx)) { let mut res = match ready!(this.fut.poll(cx)) {
@ -397,7 +397,7 @@ where
type Output = Result<Response, Error>; type Output = Result<Response, Error>;
#[project] #[project]
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[project] #[project]
match self.project() { match self.project() {
EitherResponder::A(fut) => { EitherResponder::A(fut) => {
@ -446,7 +446,7 @@ where
{ {
type Output = Result<Response, Error>; type Output = Result<Response, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(ready!(self.project().fut.poll(cx)).map_err(|e| e.into())) Poll::Ready(ready!(self.project().fut.poll(cx)).map_err(|e| e.into()))
} }
} }

View File

@ -92,7 +92,7 @@ pub struct CreateRouteService {
impl Future for CreateRouteService { impl Future for CreateRouteService {
type Output = Result<RouteService, ()>; type Output = Result<RouteService, ()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project(); let this = self.project();
match this.fut.poll(cx)? { match this.fut.poll(cx)? {
@ -127,7 +127,7 @@ impl Service for RouteService {
type Error = Error; type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx) self.service.poll_ready(cx)
} }
@ -313,7 +313,7 @@ where
type Error = Error; type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx).map_err(|(e, _)| e) self.service.poll_ready(cx).map_err(|(e, _)| e)
} }

View File

@ -534,7 +534,7 @@ enum CreateScopeServiceItem {
impl Future for ScopeFactoryResponse { impl Future for ScopeFactoryResponse {
type Output = Result<ScopeService, ()>; type Output = Result<ScopeService, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut done = true; let mut done = true;
if let Some(ref mut fut) = self.default_fut { if let Some(ref mut fut) = self.default_fut {
@ -606,7 +606,7 @@ impl Service for ScopeService {
type Error = Error; type Error = Error;
type Future = Either<BoxedResponse, Ready<Result<Self::Response, Self::Error>>>; type Future = Either<BoxedResponse, Ready<Result<Self::Response, Self::Error>>>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }

View File

@ -5,7 +5,6 @@ use std::{fmt, io, net};
use actix_http::{ use actix_http::{
body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response, body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response,
}; };
use actix_rt::System;
use actix_server::{Server, ServerBuilder}; use actix_server::{Server, ServerBuilder};
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory}; use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
use futures::future::ok; use futures::future::ok;
@ -516,13 +515,12 @@ where
/// This methods panics if no socket address can be bound or an `Actix` system is not yet /// This methods panics if no socket address can be bound or an `Actix` system is not yet
/// configured. /// configured.
/// ///
/// ```rust /// ```rust,no_run
/// use std::io; /// use std::io;
/// use actix_web::{web, App, HttpResponse, HttpServer}; /// use actix_web::{web, App, HttpResponse, HttpServer};
/// ///
/// #[actix_rt::main] /// #[actix_rt::main]
/// async fn main() -> io::Result<()> { /// async fn main() -> io::Result<()> {
/// # actix_rt::System::current().stop();
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok()))) /// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0")? /// .bind("127.0.0.1:0")?
/// .start() /// .start()
@ -532,32 +530,6 @@ where
pub fn start(self) -> Server { pub fn start(self) -> Server {
self.builder.start() self.builder.start()
} }
/// Spawn new thread and start listening for incoming connections.
///
/// This method spawns new thread and starts new actix system. Other than
/// that it is similar to `start()` method. This method blocks.
///
/// This methods panics if no socket addresses get bound.
///
/// ```rust
/// use std::io;
/// use actix_web::{web, App, HttpResponse, HttpServer};
///
/// fn main() -> io::Result<()> {
/// # std::thread::spawn(|| {
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0")?
/// .run()
/// # });
/// # Ok(())
/// }
/// ```
pub fn run(self) -> io::Result<()> {
let sys = System::new("http-server");
self.start();
sys.run()
}
} }
fn create_tcp_listener( fn create_tcp_listener(

View File

@ -181,7 +181,7 @@ impl ServiceRequest {
/// Get *ConnectionInfo* for the current request. /// Get *ConnectionInfo* for the current request.
#[inline] #[inline]
pub fn connection_info(&self) -> Ref<ConnectionInfo> { pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
ConnectionInfo::get(self.head(), &*self.app_config()) ConnectionInfo::get(self.head(), &*self.app_config())
} }
@ -253,13 +253,13 @@ impl HttpMessage for ServiceRequest {
/// Request extensions /// Request extensions
#[inline] #[inline]
fn extensions(&self) -> Ref<Extensions> { fn extensions(&self) -> Ref<'_, Extensions> {
self.0.extensions() self.0.extensions()
} }
/// Mutable reference to a the request's extensions /// Mutable reference to a the request's extensions
#[inline] #[inline]
fn extensions_mut(&self) -> RefMut<Extensions> { fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.0.extensions_mut() self.0.extensions_mut()
} }
@ -270,7 +270,7 @@ impl HttpMessage for ServiceRequest {
} }
impl fmt::Debug for ServiceRequest { impl fmt::Debug for ServiceRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!( writeln!(
f, f,
"\nServiceRequest {:?} {}:{}", "\nServiceRequest {:?} {}:{}",
@ -404,7 +404,7 @@ impl<B> Into<Response<B>> for ServiceResponse<B> {
} }
impl<B: MessageBody> fmt::Debug for ServiceResponse<B> { impl<B: MessageBody> fmt::Debug for ServiceResponse<B> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = writeln!( let res = writeln!(
f, f,
"\nServiceResponse {:?} {}{}", "\nServiceResponse {:?} {}{}",

View File

@ -388,7 +388,7 @@ impl TestRequest {
} }
/// Set cookie for this request /// Set cookie for this request
pub fn cookie(mut self, cookie: Cookie) -> Self { pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
self.req.cookie(cookie); self.req.cookie(cookie);
self self
} }

View File

@ -141,13 +141,13 @@ where
} }
impl<T: fmt::Debug> fmt::Debug for Form<T> { impl<T: fmt::Debug> fmt::Debug for Form<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f) self.0.fmt(f)
} }
} }
impl<T: fmt::Display> fmt::Display for Form<T> { impl<T: fmt::Display> fmt::Display for Form<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f) self.0.fmt(f)
} }
} }
@ -308,7 +308,7 @@ where
{ {
type Output = Result<U, UrlencodedError>; type Output = Result<U, UrlencodedError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(ref mut fut) = self.fut { if let Some(ref mut fut) = self.fut {
return Pin::new(fut).poll(cx); return Pin::new(fut).poll(cx);
} }

View File

@ -106,7 +106,7 @@ impl<T> fmt::Debug for Json<T>
where where
T: fmt::Debug, T: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Json: {:?}", self.0) write!(f, "Json: {:?}", self.0)
} }
} }
@ -115,7 +115,7 @@ impl<T> fmt::Display for Json<T>
where where
T: fmt::Display, T: fmt::Display,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f) fmt::Display::fmt(&self.0, f)
} }
} }
@ -356,7 +356,7 @@ where
{ {
type Output = Result<U, JsonPayloadError>; type Output = Result<U, JsonPayloadError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(ref mut fut) = self.fut { if let Some(ref mut fut) = self.fut {
return Pin::new(fut).poll(cx); return Pin::new(fut).poll(cx);
} }

View File

@ -97,13 +97,13 @@ impl<T> From<T> for Path<T> {
} }
impl<T: fmt::Debug> fmt::Debug for Path<T> { impl<T: fmt::Debug> fmt::Debug for Path<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f) self.inner.fmt(f)
} }
} }
impl<T: fmt::Display> fmt::Display for Path<T> { impl<T: fmt::Display> fmt::Display for Path<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f) self.inner.fmt(f)
} }
} }

Some files were not shown because too many files have changed in this diff Show More