diff --git a/CHANGES.md b/CHANGES.md index 641e09bdd..cb5f51126 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,11 +1,19 @@ # Changes -## [1.0.4] - TBD +## [1.0.4] - 2019-07-17 + +### Added + +* Add `Responder` impl for `(T, StatusCode) where T: Responder` + +* Allow to access app's resource map via + `ServiceRequest::resource_map()` and `HttpRequest::resource_map()` methods. ### Changed * Upgrade `rand` dependency version to 0.7 + ## [1.0.3] - 2019-06-28 ### Added diff --git a/Cargo.toml b/Cargo.toml index 57676accc..866a7628f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "actix-web" -version = "1.0.3" +version = "1.0.4" authors = ["Nikolay Kim "] description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust." readme = "README.md" @@ -71,11 +71,11 @@ rust-tls = ["rustls", "actix-server/rust-tls"] [dependencies] actix-codec = "0.1.2" actix-service = "0.4.1" -actix-utils = "0.4.2" +actix-utils = "0.4.4" actix-router = "0.1.5" -actix-rt = "0.2.3" +actix-rt = "0.2.4" actix-web-codegen = "0.1.2" -actix-http = "0.2.5" +actix-http = "0.2.6" actix-server = "0.5.1" actix-server-config = "0.1.1" actix-threadpool = "0.1.1" @@ -89,7 +89,7 @@ hashbrown = "0.5.0" log = "0.4" mime = "0.3" net2 = "0.2.33" -parking_lot = "0.8" +parking_lot = "0.9" regex = "1.0" serde = { version = "1.0", features=["derive"] } serde_json = "1.0" diff --git a/README.md b/README.md index cae737b68..e533c848c 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ You may consider checking out ## Benchmarks -* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext) +* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r18) ## License diff --git a/actix-cors/src/lib.rs b/actix-cors/src/lib.rs index 5d0d013e3..c76bae925 100644 --- a/actix-cors/src/lib.rs +++ b/actix-cors/src/lib.rs @@ -1,3 +1,4 @@ +#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)] //! Cross-origin resource sharing (CORS) for Actix applications //! //! CORS middleware could be used with application and with resource. @@ -162,6 +163,7 @@ impl AllOrSome { /// .max_age(3600); /// # } /// ``` +#[derive(Default)] pub struct Cors { cors: Option, methods: bool, @@ -585,10 +587,10 @@ impl Inner { } Err(CorsError::BadOrigin) } else { - return match self.origins { + match self.origins { AllOrSome::All => Ok(()), _ => Err(CorsError::MissingOrigin), - }; + } } } @@ -663,7 +665,7 @@ impl Inner { } Err(CorsError::BadRequestHeaders) } else { - return Ok(()); + Ok(()) } } } @@ -681,7 +683,7 @@ where type Error = Error; type Future = Either< FutureResult, - Either>>, + Either>>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { diff --git a/actix-files/src/lib.rs b/actix-files/src/lib.rs index 8e87f7d89..cf07153fa 100644 --- a/actix-files/src/lib.rs +++ b/actix-files/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)] + //! Static files support use std::cell::RefCell; use std::fmt::Write; @@ -50,14 +52,14 @@ pub struct ChunkedReadFile { size: u64, offset: u64, file: Option, - fut: Option>>>, + fut: Option>>>, counter: u64, } fn handle_error(err: BlockingError) -> Error { match err { BlockingError::Error(err) => err.into(), - BlockingError::Canceled => ErrorInternalServerError("Unexpected error").into(), + BlockingError::Canceled => ErrorInternalServerError("Unexpected error"), } } @@ -105,7 +107,7 @@ impl Stream for ChunkedReadFile { } type DirectoryRenderer = - Fn(&Directory, &HttpRequest) -> Result; + dyn Fn(&Directory, &HttpRequest) -> Result; /// A directory; responds with the generated directory listing. #[derive(Debug)] @@ -209,7 +211,7 @@ fn directory_listing( )) } -type MimeOverride = Fn(&mime::Name) -> DispositionType; +type MimeOverride = dyn Fn(&mime::Name) -> DispositionType; /// Static files handling /// @@ -370,7 +372,7 @@ impl NewService for Files { type Error = Error; type Service = FilesService; type InitError = (); - type Future = Box>; + type Future = Box>; fn new_service(&self, _: &()) -> Self::Future { let mut srv = FilesService { @@ -416,7 +418,7 @@ impl FilesService { req: ServiceRequest, ) -> Either< FutureResult, - Box>, + Box>, > { log::debug!("Files: Failed to handle {}: {}", req.path(), e); if let Some(ref mut default) = self.default { @@ -433,7 +435,7 @@ impl Service for FilesService { type Error = Error; type Future = Either< FutureResult, - Box>, + Box>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { @@ -473,7 +475,7 @@ impl Service for FilesService { Err(e) => ServiceResponse::from_err(e, req), })) } - Err(e) => return self.handle_err(e, req), + Err(e) => self.handle_err(e, req), } } else if self.show_index { let dir = Directory::new(self.directory.clone(), path); @@ -481,7 +483,7 @@ impl Service for FilesService { let x = (self.renderer)(&dir, &req); match x { Ok(resp) => Either::A(ok(resp)), - Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req))), + Err(e) => Either::A(ok(ServiceResponse::from_err(e, req))), } } else { Either::A(ok(ServiceResponse::from_err( @@ -855,7 +857,7 @@ mod tests { #[test] fn test_named_file_content_length_headers() { - use actix_web::body::{MessageBody, ResponseBody}; + // use actix_web::body::{MessageBody, ResponseBody}; let mut srv = test::init_service( App::new().service(Files::new("test", ".").index_file("tests/test.binary")), @@ -866,7 +868,7 @@ mod tests { .uri("/t%65st/tests/test.binary") .header(header::RANGE, "bytes=10-20") .to_request(); - let response = test::call_service(&mut srv, request); + let _response = test::call_service(&mut srv, request); // let contentlength = response // .headers() @@ -889,7 +891,7 @@ mod tests { .uri("/t%65st/tests/test.binary") // .no_default_headers() .to_request(); - let response = test::call_service(&mut srv, request); + let _response = test::call_service(&mut srv, request); // let contentlength = response // .headers() @@ -937,7 +939,7 @@ mod tests { .method(Method::HEAD) .uri("/t%65st/tests/test.binary") .to_request(); - let response = test::call_service(&mut srv, request); + let _response = test::call_service(&mut srv, request); // TODO: fix check // let contentlength = response diff --git a/actix-files/src/named.rs b/actix-files/src/named.rs index 6b948da8e..3273a4d67 100644 --- a/actix-files/src/named.rs +++ b/actix-files/src/named.rs @@ -24,8 +24,8 @@ use crate::ChunkedReadFile; bitflags! { pub(crate) struct Flags: u32 { - const ETAG = 0b00000001; - const LAST_MD = 0b00000010; + const ETAG = 0b0000_0001; + const LAST_MD = 0b0000_0010; } } @@ -311,8 +311,8 @@ impl Responder for NamedFile { return Ok(resp.streaming(reader)); } - match req.method() { - &Method::HEAD | &Method::GET => (), + match *req.method() { + Method::HEAD | Method::GET => (), _ => { return Ok(HttpResponse::MethodNotAllowed() .header(header::CONTENT_TYPE, "text/plain") diff --git a/actix-files/src/range.rs b/actix-files/src/range.rs index d97a35e7e..47673b0b0 100644 --- a/actix-files/src/range.rs +++ b/actix-files/src/range.rs @@ -5,7 +5,7 @@ pub struct HttpRange { pub length: u64, } -static PREFIX: &'static str = "bytes="; +static PREFIX: &str = "bytes="; const PREFIX_LEN: usize = 6; impl HttpRange { diff --git a/actix-framed/src/app.rs b/actix-framed/src/app.rs index 297796bd1..a9d73a25c 100644 --- a/actix-framed/src/app.rs +++ b/actix-framed/src/app.rs @@ -13,7 +13,7 @@ use crate::helpers::{BoxedHttpNewService, BoxedHttpService, HttpNewService}; use crate::request::FramedRequest; use crate::state::State; -type BoxedResponse = Box>; +type BoxedResponse = Box>; pub trait HttpServiceFactory { type Factory: NewService; @@ -61,7 +61,7 @@ impl FramedApp { Request = FramedRequest, Response = (), Error = Error, - Future = Box>, + Future = Box>, >, { let path = factory.path().to_string(); @@ -129,7 +129,7 @@ pub struct CreateService { enum CreateServiceItem { Future( Option, - Box>, Error = ()>>, + Box>, Error = ()>>, ), Service(String, BoxedHttpService>), } diff --git a/actix-framed/src/helpers.rs b/actix-framed/src/helpers.rs index 944b729d4..b343301f3 100644 --- a/actix-framed/src/helpers.rs +++ b/actix-framed/src/helpers.rs @@ -3,23 +3,23 @@ use actix_service::{NewService, Service}; use futures::{Future, Poll}; pub(crate) type BoxedHttpService = Box< - Service< + dyn Service< Request = Req, Response = (), Error = Error, - Future = Box>, + Future = Box>, >, >; pub(crate) type BoxedHttpNewService = Box< - NewService< + dyn NewService< Config = (), Request = Req, Response = (), Error = Error, InitError = (), Service = BoxedHttpService, - Future = Box, Error = ()>>, + Future = Box, Error = ()>>, >, >; @@ -30,7 +30,7 @@ where T: NewService, T::Response: 'static, T::Future: 'static, - T::Service: Service>> + 'static, + T::Service: Service>> + 'static, ::Future: 'static, { pub fn new(service: T) -> Self { @@ -43,7 +43,7 @@ where T: NewService, T::Request: 'static, T::Future: 'static, - T::Service: Service>> + 'static, + T::Service: Service>> + 'static, ::Future: 'static, { type Config = (); @@ -52,7 +52,7 @@ where type Error = Error; type InitError = (); type Service = BoxedHttpService; - type Future = Box>; + type Future = Box>; fn new_service(&self, _: &()) -> Self::Future { Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| { @@ -70,7 +70,7 @@ impl Service for HttpServiceWrapper where T: Service< Response = (), - Future = Box>, + Future = Box>, Error = Error, >, T::Request: 'static, @@ -78,7 +78,7 @@ where type Request = T::Request; type Response = (); type Error = Error; - type Future = Box>; + type Future = Box>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() diff --git a/actix-framed/src/lib.rs b/actix-framed/src/lib.rs index c6405e20b..5e72ba5ba 100644 --- a/actix-framed/src/lib.rs +++ b/actix-framed/src/lib.rs @@ -1,3 +1,9 @@ +#![allow( + clippy::type_complexity, + clippy::new_without_default, + dead_code, + deprecated +)] mod app; mod helpers; mod request; diff --git a/actix-framed/src/route.rs b/actix-framed/src/route.rs index c50401d6d..5beb24165 100644 --- a/actix-framed/src/route.rs +++ b/actix-framed/src/route.rs @@ -140,7 +140,7 @@ where type Request = FramedRequest; type Response = (); type Error = Error; - type Future = Box>; + type Future = Box>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(Async::Ready(())) diff --git a/actix-http/CHANGES.md b/actix-http/CHANGES.md index 516793264..84033531d 100644 --- a/actix-http/CHANGES.md +++ b/actix-http/CHANGES.md @@ -1,11 +1,14 @@ # Changes -## [0.2.6] - TBD +## [0.2.6] - 2019-07-17 ### Changed +* Replace `ClonableService` with local copy + * Upgrade `rand` dependency version to 0.7 + ## [0.2.5] - 2019-06-28 ### Added diff --git a/actix-http/Cargo.toml b/actix-http/Cargo.toml index 5db7a6ca3..ae12cbc41 100644 --- a/actix-http/Cargo.toml +++ b/actix-http/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "actix-http" -version = "0.2.5" +version = "0.2.6" authors = ["Nikolay Kim "] description = "Actix http primitives" readme = "README.md" @@ -46,10 +46,10 @@ secure-cookies = ["ring"] [dependencies] actix-service = "0.4.1" actix-codec = "0.1.2" -actix-connect = "0.2.0" -actix-utils = "0.4.2" +actix-connect = "0.2.1" +actix-utils = "0.4.4" actix-server-config = "0.1.1" -actix-threadpool = "0.1.0" +actix-threadpool = "0.1.1" base64 = "0.10" bitflags = "1.0" diff --git a/actix-http/src/builder.rs b/actix-http/src/builder.rs index b6967d94d..bab0f5e1e 100644 --- a/actix-http/src/builder.rs +++ b/actix-http/src/builder.rs @@ -26,7 +26,7 @@ pub struct HttpServiceBuilder> { client_disconnect: u64, expect: X, upgrade: Option, - on_connect: Option Box>>, + on_connect: Option Box>>, _t: PhantomData<(T, S)>, } diff --git a/actix-http/src/client/connection.rs b/actix-http/src/client/connection.rs index 9354fca4a..36913c5f0 100644 --- a/actix-http/src/client/connection.rs +++ b/actix-http/src/client/connection.rs @@ -94,7 +94,8 @@ where T: AsyncRead + AsyncWrite + 'static, { type Io = T; - type Future = Box>; + type Future = + Box>; fn protocol(&self) -> Protocol { match self.io { @@ -129,7 +130,7 @@ where type TunnelFuture = Either< Box< - Future< + dyn Future< Item = (ResponseHead, Framed), Error = SendRequestError, >, @@ -169,7 +170,8 @@ where B: AsyncRead + AsyncWrite + 'static, { type Io = EitherIo; - type Future = Box>; + type Future = + Box>; fn protocol(&self) -> Protocol { match self { @@ -190,7 +192,7 @@ where } type TunnelFuture = Box< - Future< + dyn Future< Item = (ResponseHead, Framed), Error = SendRequestError, >, diff --git a/actix-http/src/client/connector.rs b/actix-http/src/client/connector.rs index 0241e8472..cd3ae3d9e 100644 --- a/actix-http/src/client/connector.rs +++ b/actix-http/src/client/connector.rs @@ -47,6 +47,7 @@ pub struct Connector { } impl Connector<(), ()> { + #[allow(clippy::new_ret_no_self)] pub fn new() -> Connector< impl Service< Request = TcpConnect, diff --git a/actix-http/src/client/pool.rs b/actix-http/src/client/pool.rs index 8dedf72f5..4739141d0 100644 --- a/actix-http/src/client/pool.rs +++ b/actix-http/src/client/pool.rs @@ -427,7 +427,9 @@ where fn check_availibility(&self) { if !self.waiters_queue.is_empty() && self.acquired < self.limit { - self.task.as_ref().map(|t| t.notify()); + if let Some(t) = self.task.as_ref() { + t.notify() + } } } } diff --git a/actix-http/src/cloneable.rs b/actix-http/src/cloneable.rs new file mode 100644 index 000000000..ffc1d0611 --- /dev/null +++ b/actix-http/src/cloneable.rs @@ -0,0 +1,42 @@ +use std::cell::UnsafeCell; +use std::rc::Rc; + +use actix_service::Service; +use futures::Poll; + +#[doc(hidden)] +/// Service that allows to turn non-clone service to a service with `Clone` impl +pub(crate) struct CloneableService(Rc>); + +impl CloneableService { + pub(crate) fn new(service: T) -> Self + where + T: Service, + { + Self(Rc::new(UnsafeCell::new(service))) + } +} + +impl Clone for CloneableService { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +impl Service for CloneableService +where + T: Service, +{ + type Request = T::Request; + type Response = T::Response; + type Error = T::Error; + type Future = T::Future; + + fn poll_ready(&mut self) -> Poll<(), Self::Error> { + unsafe { &mut *self.0.as_ref().get() }.poll_ready() + } + + fn call(&mut self, req: T::Request) -> Self::Future { + unsafe { &mut *self.0.as_ref().get() }.call(req) + } +} diff --git a/actix-http/src/cookie/mod.rs b/actix-http/src/cookie/mod.rs index ddcb12bbf..f576a4521 100644 --- a/actix-http/src/cookie/mod.rs +++ b/actix-http/src/cookie/mod.rs @@ -104,6 +104,7 @@ impl CookieStr { } } + #[allow(clippy::ptr_arg)] fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> { match *self { CookieStr::Indexed(i, j) => match *string { diff --git a/actix-http/src/cookie/secure/key.rs b/actix-http/src/cookie/secure/key.rs index 4e74f6e78..39575c93f 100644 --- a/actix-http/src/cookie/secure/key.rs +++ b/actix-http/src/cookie/secure/key.rs @@ -6,8 +6,8 @@ use ring::rand::{SecureRandom, SystemRandom}; use super::private::KEY_LEN as PRIVATE_KEY_LEN; use super::signed::KEY_LEN as SIGNED_KEY_LEN; -static HKDF_DIGEST: &'static Algorithm = &SHA256; -const KEYS_INFO: &'static str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM"; +static HKDF_DIGEST: &Algorithm = &SHA256; +const KEYS_INFO: &str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM"; /// A cryptographic master key for use with `Signed` and/or `Private` jars. /// diff --git a/actix-http/src/cookie/secure/private.rs b/actix-http/src/cookie/secure/private.rs index e59743767..eb8e9beb1 100644 --- a/actix-http/src/cookie/secure/private.rs +++ b/actix-http/src/cookie/secure/private.rs @@ -10,7 +10,7 @@ use crate::cookie::{Cookie, CookieJar}; // Keep these in sync, and keep the key len synced with the `private` docs as // 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; pub const KEY_LEN: usize = 32; diff --git a/actix-http/src/cookie/secure/signed.rs b/actix-http/src/cookie/secure/signed.rs index 1b1799cf4..36a277cd5 100644 --- a/actix-http/src/cookie/secure/signed.rs +++ b/actix-http/src/cookie/secure/signed.rs @@ -6,7 +6,7 @@ use crate::cookie::{Cookie, CookieJar}; // Keep these in sync, and keep the key len synced with the `signed` docs as // well as the `KEYS_INFO` const in secure::Key. -static HMAC_DIGEST: &'static Algorithm = &SHA256; +static HMAC_DIGEST: &Algorithm = &SHA256; const BASE64_DIGEST_LEN: usize = 44; pub const KEY_LEN: usize = 32; diff --git a/actix-http/src/error.rs b/actix-http/src/error.rs index 4913c3d9d..368ee6dde 100644 --- a/actix-http/src/error.rs +++ b/actix-http/src/error.rs @@ -43,12 +43,12 @@ pub type Result = result::Result; /// if you have access to an actix `Error` you can always get a /// `ResponseError` reference from it. pub struct Error { - cause: Box, + cause: Box, } impl Error { /// Returns the reference to the underlying `ResponseError`. - pub fn as_response_error(&self) -> &ResponseError { + pub fn as_response_error(&self) -> &dyn ResponseError { self.cause.as_ref() } } diff --git a/actix-http/src/extensions.rs b/actix-http/src/extensions.rs index 148e4c18e..c6266f56e 100644 --- a/actix-http/src/extensions.rs +++ b/actix-http/src/extensions.rs @@ -6,7 +6,7 @@ use hashbrown::HashMap; #[derive(Default)] /// A type map of request extensions. pub struct Extensions { - map: HashMap>, + map: HashMap>, } impl Extensions { @@ -35,14 +35,14 @@ impl Extensions { pub fn get(&self) -> Option<&T> { self.map .get(&TypeId::of::()) - .and_then(|boxed| (&**boxed as &(Any + 'static)).downcast_ref()) + .and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref()) } /// Get a mutable reference to a type previously inserted on this `Extensions`. pub fn get_mut(&mut self) -> Option<&mut T> { self.map .get_mut(&TypeId::of::()) - .and_then(|boxed| (&mut **boxed as &mut (Any + 'static)).downcast_mut()) + .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut()) } /// Remove a type from this `Extensions`. @@ -50,7 +50,7 @@ impl Extensions { /// If a extension of this type existed, it will be returned. pub fn remove(&mut self) -> Option { self.map.remove(&TypeId::of::()).and_then(|boxed| { - (boxed as Box) + (boxed as Box) .downcast() .ok() .map(|boxed| *boxed) diff --git a/actix-http/src/h1/decoder.rs b/actix-http/src/h1/decoder.rs index 12419d665..c7ef065a5 100644 --- a/actix-http/src/h1/decoder.rs +++ b/actix-http/src/h1/decoder.rs @@ -502,15 +502,15 @@ impl ChunkedState { fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll { let radix = 16; match byte!(rdr) { - b @ b'0'...b'9' => { + b @ b'0'..=b'9' => { *size *= radix; *size += u64::from(b - b'0'); } - b @ b'a'...b'f' => { + b @ b'a'..=b'f' => { *size *= radix; *size += u64::from(b + 10 - b'a'); } - b @ b'A'...b'F' => { + b @ b'A'..=b'F' => { *size *= radix; *size += u64::from(b + 10 - b'A'); } diff --git a/actix-http/src/h1/dispatcher.rs b/actix-http/src/h1/dispatcher.rs index 91990d05c..5e9c0b53d 100644 --- a/actix-http/src/h1/dispatcher.rs +++ b/actix-http/src/h1/dispatcher.rs @@ -5,7 +5,6 @@ use std::{fmt, io, net}; use actix_codec::{Decoder, Encoder, Framed, FramedParts}; use actix_server_config::IoStream; use actix_service::Service; -use actix_utils::cloneable::CloneableService; use bitflags::bitflags; use bytes::{BufMut, BytesMut}; use futures::{Async, Future, Poll}; @@ -13,6 +12,7 @@ use log::{error, trace}; use tokio_timer::Delay; use crate::body::{Body, BodySize, MessageBody, ResponseBody}; +use crate::cloneable::CloneableService; use crate::config::ServiceConfig; use crate::error::{DispatchError, Error}; use crate::error::{ParseError, PayloadError}; diff --git a/actix-http/src/h1/service.rs b/actix-http/src/h1/service.rs index 192d1b598..89bf08e9b 100644 --- a/actix-http/src/h1/service.rs +++ b/actix-http/src/h1/service.rs @@ -5,11 +5,11 @@ use std::rc::Rc; use actix_codec::Framed; use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig}; use actix_service::{IntoNewService, NewService, Service}; -use actix_utils::cloneable::CloneableService; use futures::future::{ok, FutureResult}; use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream}; use crate::body::MessageBody; +use crate::cloneable::CloneableService; use crate::config::{KeepAlive, ServiceConfig}; use crate::error::{DispatchError, Error, ParseError}; use crate::helpers::DataFactory; @@ -26,7 +26,7 @@ pub struct H1Service> { cfg: ServiceConfig, expect: X, upgrade: Option, - on_connect: Option Box>>, + on_connect: Option Box>>, _t: PhantomData<(T, P, B)>, } @@ -108,7 +108,7 @@ where /// Set on connect callback. pub(crate) fn on_connect( mut self, - f: Option Box>>, + f: Option Box>>, ) -> Self { self.on_connect = f; self @@ -174,7 +174,7 @@ where fut_upg: Option, expect: Option, upgrade: Option, - on_connect: Option Box>>, + on_connect: Option Box>>, cfg: Option, _t: PhantomData<(T, P, B)>, } @@ -233,7 +233,7 @@ pub struct H1ServiceHandler { srv: CloneableService, expect: CloneableService, upgrade: Option>, - on_connect: Option Box>>, + on_connect: Option Box>>, cfg: ServiceConfig, _t: PhantomData<(T, P, B)>, } @@ -254,12 +254,12 @@ where srv: S, expect: X, upgrade: Option, - on_connect: Option Box>>, + on_connect: Option Box>>, ) -> H1ServiceHandler { H1ServiceHandler { srv: CloneableService::new(srv), expect: CloneableService::new(expect), - upgrade: upgrade.map(|s| CloneableService::new(s)), + upgrade: upgrade.map(CloneableService::new), cfg, on_connect, _t: PhantomData, diff --git a/actix-http/src/h2/dispatcher.rs b/actix-http/src/h2/dispatcher.rs index 48d32993d..2bd7940dd 100644 --- a/actix-http/src/h2/dispatcher.rs +++ b/actix-http/src/h2/dispatcher.rs @@ -6,7 +6,6 @@ use std::{fmt, mem, net}; use actix_codec::{AsyncRead, AsyncWrite}; use actix_server_config::IoStream; use actix_service::Service; -use actix_utils::cloneable::CloneableService; use bitflags::bitflags; use bytes::{Bytes, BytesMut}; use futures::{try_ready, Async, Future, Poll, Sink, Stream}; @@ -20,6 +19,7 @@ use log::{debug, error, trace}; use tokio_timer::Delay; use crate::body::{Body, BodySize, MessageBody, ResponseBody}; +use crate::cloneable::CloneableService; use crate::config::ServiceConfig; use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError}; use crate::helpers::DataFactory; diff --git a/actix-http/src/h2/service.rs b/actix-http/src/h2/service.rs index efc400da1..e894cf660 100644 --- a/actix-http/src/h2/service.rs +++ b/actix-http/src/h2/service.rs @@ -5,7 +5,6 @@ use std::{io, net, rc}; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig}; use actix_service::{IntoNewService, NewService, Service}; -use actix_utils::cloneable::CloneableService; use bytes::Bytes; use futures::future::{ok, FutureResult}; use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream}; @@ -14,6 +13,7 @@ use h2::RecvStream; use log::error; use crate::body::MessageBody; +use crate::cloneable::CloneableService; use crate::config::{KeepAlive, ServiceConfig}; use crate::error::{DispatchError, Error, ParseError, ResponseError}; use crate::helpers::DataFactory; @@ -27,7 +27,7 @@ use super::dispatcher::Dispatcher; pub struct H2Service { srv: S, cfg: ServiceConfig, - on_connect: Option Box>>, + on_connect: Option Box>>, _t: PhantomData<(T, P, B)>, } @@ -64,7 +64,7 @@ where /// Set on connect callback. pub(crate) fn on_connect( mut self, - f: Option Box>>, + f: Option Box>>, ) -> Self { self.on_connect = f; self @@ -102,7 +102,7 @@ where pub struct H2ServiceResponse { fut: ::Future, cfg: Option, - on_connect: Option Box>>, + on_connect: Option Box>>, _t: PhantomData<(T, P, B)>, } @@ -132,7 +132,7 @@ where pub struct H2ServiceHandler { srv: CloneableService, cfg: ServiceConfig, - on_connect: Option Box>>, + on_connect: Option Box>>, _t: PhantomData<(T, P, B)>, } @@ -146,7 +146,7 @@ where { fn new( cfg: ServiceConfig, - on_connect: Option Box>>, + on_connect: Option Box>>, srv: S, ) -> H2ServiceHandler { H2ServiceHandler { @@ -256,7 +256,7 @@ where on_connect.take(), config.take().unwrap(), None, - peer_addr.clone(), + *peer_addr, )); self.poll() } diff --git a/actix-http/src/header/common/content_disposition.rs b/actix-http/src/header/common/content_disposition.rs index badf307a0..14fcc3517 100644 --- a/actix-http/src/header/common/content_disposition.rs +++ b/actix-http/src/header/common/content_disposition.rs @@ -70,6 +70,7 @@ impl<'a> From<&'a str> for DispositionType { /// assert_eq!(param.as_filename().unwrap(), "sample.txt"); /// ``` #[derive(Clone, Debug, PartialEq)] +#[allow(clippy::large_enum_variant)] pub enum DispositionParam { /// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from /// the form. @@ -719,8 +720,10 @@ mod tests { }; assert_eq!(a, b); - let a = - HeaderValue::from_str("form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"").unwrap(); + let a = HeaderValue::from_str( + "form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"", + ) + .unwrap(); let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap(); let b = ContentDisposition { disposition: DispositionType::FormData, diff --git a/actix-http/src/lib.rs b/actix-http/src/lib.rs index ac085eaea..6b8874b23 100644 --- a/actix-http/src/lib.rs +++ b/actix-http/src/lib.rs @@ -1,8 +1,10 @@ //! Basic http primitives for actix-net framework. #![allow( clippy::type_complexity, + clippy::too_many_arguments, clippy::new_without_default, - clippy::borrow_interior_mutable_const + clippy::borrow_interior_mutable_const, + clippy::write_with_newline )] #[macro_use] @@ -11,6 +13,7 @@ extern crate log; pub mod body; mod builder; pub mod client; +mod cloneable; mod config; pub mod encoding; mod extensions; diff --git a/actix-http/src/message.rs b/actix-http/src/message.rs index f3c01a12b..cf23a401c 100644 --- a/actix-http/src/message.rs +++ b/actix-http/src/message.rs @@ -385,6 +385,7 @@ impl Drop for BoxedResponseHead { pub struct MessagePool(RefCell>>); #[doc(hidden)] +#[allow(clippy::vec_box)] /// Request's objects pool pub struct BoxedResponsePool(RefCell>>); diff --git a/actix-http/src/service.rs b/actix-http/src/service.rs index 6fd1cc0c0..09b8077b3 100644 --- a/actix-http/src/service.rs +++ b/actix-http/src/service.rs @@ -6,13 +6,13 @@ use actix_server_config::{ Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig, }; use actix_service::{IntoNewService, NewService, Service}; -use actix_utils::cloneable::CloneableService; use bytes::{Buf, BufMut, Bytes, BytesMut}; use futures::{try_ready, Async, Future, IntoFuture, Poll}; use h2::server::{self, Handshake}; use crate::body::MessageBody; use crate::builder::HttpServiceBuilder; +use crate::cloneable::CloneableService; use crate::config::{KeepAlive, ServiceConfig}; use crate::error::{DispatchError, Error}; use crate::helpers::DataFactory; @@ -26,7 +26,7 @@ pub struct HttpService, - on_connect: Option Box>>, + on_connect: Option Box>>, _t: PhantomData<(T, P, B)>, } @@ -140,7 +140,7 @@ where /// Set on connect callback. pub(crate) fn on_connect( mut self, - f: Option Box>>, + f: Option Box>>, ) -> Self { self.on_connect = f; self @@ -196,7 +196,7 @@ pub struct HttpServiceResponse, expect: Option, upgrade: Option, - on_connect: Option Box>>, + on_connect: Option Box>>, cfg: Option, _t: PhantomData<(T, P, B)>, } @@ -257,7 +257,7 @@ pub struct HttpServiceHandler { expect: CloneableService, upgrade: Option>, cfg: ServiceConfig, - on_connect: Option Box>>, + on_connect: Option Box>>, _t: PhantomData<(T, P, B, X)>, } @@ -278,14 +278,14 @@ where srv: S, expect: X, upgrade: Option, - on_connect: Option Box>>, + on_connect: Option Box>>, ) -> HttpServiceHandler { HttpServiceHandler { cfg, on_connect, srv: CloneableService::new(srv), expect: CloneableService::new(expect), - upgrade: upgrade.map(|s| CloneableService::new(s)), + upgrade: upgrade.map(CloneableService::new), _t: PhantomData, } } diff --git a/actix-http/src/ws/proto.rs b/actix-http/src/ws/proto.rs index eef874741..e14651a56 100644 --- a/actix-http/src/ws/proto.rs +++ b/actix-http/src/ws/proto.rs @@ -47,10 +47,7 @@ impl Into for OpCode { Ping => 9, Pong => 10, Bad => { - debug_assert!( - false, - "Attempted to convert invalid opcode to u8. This is a bug." - ); + log::error!("Attempted to convert invalid opcode to u8. This is a bug."); 8 // if this somehow happens, a close frame will help us tear down quickly } } @@ -206,7 +203,7 @@ impl> From<(CloseCode, T)> for CloseReason { } } -static WS_GUID: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; +static WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // TODO: hash is always same size, we dont need String pub fn hash_key(key: &[u8]) -> String { diff --git a/actix-identity/src/lib.rs b/actix-identity/src/lib.rs index 6664df676..7216104eb 100644 --- a/actix-identity/src/lib.rs +++ b/actix-identity/src/lib.rs @@ -261,7 +261,7 @@ where type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; - type Future = Box>; + type Future = Box>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.borrow_mut().poll_ready() @@ -283,7 +283,7 @@ where res.request().extensions_mut().remove::(); if let Some(id) = id { - return Either::A( + Either::A( backend .to_response(id.id, id.changed, &mut res) .into_future() @@ -291,7 +291,7 @@ where Ok(_) => Ok(res), Err(e) => Ok(res.error_response(e)), }), - ); + ) } else { Either::B(ok(res)) } @@ -333,8 +333,7 @@ struct CookieIdentityExtention { impl CookieIdentityInner { fn new(key: &[u8]) -> CookieIdentityInner { - let key_v2: Vec = - key.iter().chain([1, 0, 0, 0].iter()).map(|e| *e).collect(); + let key_v2: Vec = key.iter().chain([1, 0, 0, 0].iter()).cloned().collect(); CookieIdentityInner { key: Key::from_master(key), key_v2: Key::from_master(&key_v2), @@ -585,13 +584,14 @@ impl IdentityPolicy for CookieIdentityPolicy { ) } else if self.0.always_update_cookie() && id.is_some() { let visit_timestamp = SystemTime::now(); - let mut login_timestamp = None; - if self.0.requires_oob_data() { + let login_timestamp = if self.0.requires_oob_data() { let CookieIdentityExtention { login_timestamp: lt, } = res.request().extensions_mut().remove().unwrap(); - login_timestamp = lt; - } + lt + } else { + None + }; self.0.set_cookie( res, Some(CookieValue { diff --git a/actix-multipart/src/lib.rs b/actix-multipart/src/lib.rs index d8f365b2c..43eb048ca 100644 --- a/actix-multipart/src/lib.rs +++ b/actix-multipart/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::borrow_interior_mutable_const)] + mod error; mod extractor; mod server; diff --git a/actix-multipart/src/server.rs b/actix-multipart/src/server.rs index 1954a4c51..70eb61cb9 100644 --- a/actix-multipart/src/server.rs +++ b/actix-multipart/src/server.rs @@ -418,7 +418,7 @@ impl Stream for Field { inner.poll(&self.safety) } else if !self.safety.is_clean() { - return Err(MultipartError::NotConsumed); + Err(MultipartError::NotConsumed) } else { Ok(Async::NotReady) } @@ -533,11 +533,9 @@ impl InnerField { let b_size = boundary.len() + b_len; if len < b_size { return Ok(Async::NotReady); - } else { - if &payload.buf[b_len..b_size] == boundary.as_bytes() { - // found boundary - return Ok(Async::Ready(None)); - } + } else if &payload.buf[b_len..b_size] == boundary.as_bytes() { + // found boundary + return Ok(Async::Ready(None)); } } } @@ -557,7 +555,7 @@ impl InnerField { // check boundary if (&payload.buf[cur..cur + 2] == b"\r\n" && &payload.buf[cur + 2..cur + 4] == b"--") - || (&payload.buf[cur..cur + 1] == b"\r" + || (&payload.buf[cur..=cur] == b"\r" && &payload.buf[cur + 1..cur + 3] == b"--") { if cur != 0 { diff --git a/actix-session/src/cookie.rs b/actix-session/src/cookie.rs index 8627ce4c8..192737780 100644 --- a/actix-session/src/cookie.rs +++ b/actix-session/src/cookie.rs @@ -309,7 +309,7 @@ where type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; - type Future = Box>; + type Future = Box>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() @@ -342,7 +342,7 @@ where } } (SessionStatus::Purged, _) => { - inner.remove_cookie(&mut res); + let _ = inner.remove_cookie(&mut res); res } _ => res, diff --git a/actix-session/src/lib.rs b/actix-session/src/lib.rs index 27ad2b876..2e9e51714 100644 --- a/actix-session/src/lib.rs +++ b/actix-session/src/lib.rs @@ -282,7 +282,7 @@ mod tests { #[test] fn purge_session() { - let mut req = test::TestRequest::default().to_srv_request(); + let req = test::TestRequest::default().to_srv_request(); let session = Session::get_session(&mut *req.extensions_mut()); assert_eq!(session.0.borrow().status, SessionStatus::Unchanged); session.purge(); @@ -291,7 +291,7 @@ mod tests { #[test] fn renew_session() { - let mut req = test::TestRequest::default().to_srv_request(); + let req = test::TestRequest::default().to_srv_request(); let session = Session::get_session(&mut *req.extensions_mut()); assert_eq!(session.0.borrow().status, SessionStatus::Unchanged); session.renew(); diff --git a/actix-web-actors/src/lib.rs b/actix-web-actors/src/lib.rs index 5b64d7e0a..6360917cd 100644 --- a/actix-web-actors/src/lib.rs +++ b/actix-web-actors/src/lib.rs @@ -1,3 +1,4 @@ +#![allow(clippy::borrow_interior_mutable_const)] //! Actix actors integration for Actix web framework mod context; pub mod ws; diff --git a/actix-web-actors/src/ws.rs b/actix-web-actors/src/ws.rs index fece826dd..08d8b1089 100644 --- a/actix-web-actors/src/ws.rs +++ b/actix-web-actors/src/ws.rs @@ -435,7 +435,7 @@ where } } Frame::Binary(data) => Message::Binary( - data.map(|b| b.freeze()).unwrap_or_else(|| Bytes::new()), + data.map(|b| b.freeze()).unwrap_or_else(Bytes::new), ), Frame::Ping(s) => Message::Ping(s), Frame::Pong(s) => Message::Pong(s), diff --git a/actix-web-codegen/src/route.rs b/actix-web-codegen/src/route.rs index 268adecb0..5215f60c8 100644 --- a/actix-web-codegen/src/route.rs +++ b/actix-web-codegen/src/route.rs @@ -12,9 +12,9 @@ enum ResourceType { impl fmt::Display for ResourceType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &ResourceType::Async => write!(f, "to_async"), - &ResourceType::Sync => write!(f, "to"), + match *self { + ResourceType::Async => write!(f, "to_async"), + ResourceType::Sync => write!(f, "to"), } } } @@ -34,16 +34,16 @@ pub enum GuardType { impl fmt::Display for GuardType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &GuardType::Get => write!(f, "Get"), - &GuardType::Post => write!(f, "Post"), - &GuardType::Put => write!(f, "Put"), - &GuardType::Delete => write!(f, "Delete"), - &GuardType::Head => write!(f, "Head"), - &GuardType::Connect => write!(f, "Connect"), - &GuardType::Options => write!(f, "Options"), - &GuardType::Trace => write!(f, "Trace"), - &GuardType::Patch => write!(f, "Patch"), + match *self { + GuardType::Get => write!(f, "Get"), + GuardType::Post => write!(f, "Post"), + GuardType::Put => write!(f, "Put"), + GuardType::Delete => write!(f, "Delete"), + GuardType::Head => write!(f, "Head"), + GuardType::Connect => write!(f, "Connect"), + GuardType::Options => write!(f, "Options"), + GuardType::Trace => write!(f, "Trace"), + GuardType::Patch => write!(f, "Patch"), } } } @@ -92,37 +92,27 @@ impl actix_web::dev::HttpServiceFactory for {name} {{ fn guess_resource_type(typ: &syn::Type) -> ResourceType { let mut guess = ResourceType::Sync; - match typ { - syn::Type::ImplTrait(typ) => { - for bound in typ.bounds.iter() { - match bound { - syn::TypeParamBound::Trait(bound) => { - for bound in bound.path.segments.iter() { - if bound.ident == "Future" { - guess = ResourceType::Async; - break; - } else if bound.ident == "Responder" { - guess = ResourceType::Sync; - break; - } - } + if let syn::Type::ImplTrait(typ) = typ { + for bound in typ.bounds.iter() { + if let syn::TypeParamBound::Trait(bound) = bound { + for bound in bound.path.segments.iter() { + if bound.ident == "Future" { + guess = ResourceType::Async; + break; + } else if bound.ident == "Responder" { + guess = ResourceType::Sync; + break; } - _ => (), } } } - _ => (), } guess } impl Args { - pub fn new( - args: &Vec, - input: TokenStream, - guard: GuardType, - ) -> Self { + pub fn new(args: &[syn::NestedMeta], input: TokenStream, guard: GuardType) -> Self { if args.is_empty() { panic!( "invalid server definition, expected: #[{}(\"some path\")]", @@ -164,9 +154,10 @@ impl Args { ResourceType::Async } else { match ast.decl.output { - syn::ReturnType::Default => { - panic!("Function {} has no return type. Cannot be used as handler") - } + syn::ReturnType::Default => panic!( + "Function {} has no return type. Cannot be used as handler", + name + ), syn::ReturnType::Type(_, ref typ) => guess_resource_type(typ.as_ref()), } }; diff --git a/awc/src/builder.rs b/awc/src/builder.rs index a58265c5f..463f40303 100644 --- a/awc/src/builder.rs +++ b/awc/src/builder.rs @@ -21,6 +21,12 @@ pub struct ClientBuilder { max_redirects: usize, } +impl Default for ClientBuilder { + fn default() -> Self { + Self::new() + } +} + impl ClientBuilder { pub fn new() -> Self { ClientBuilder { diff --git a/awc/src/connect.rs b/awc/src/connect.rs index 4b564d777..04f08ecdc 100644 --- a/awc/src/connect.rs +++ b/awc/src/connect.rs @@ -20,7 +20,7 @@ pub(crate) trait Connect { head: RequestHead, body: Body, addr: Option, - ) -> Box>; + ) -> Box>; /// Send request, returns Response and Framed fn open_tunnel( @@ -28,7 +28,7 @@ pub(crate) trait Connect { head: RequestHead, addr: Option, ) -> Box< - Future< + dyn Future< Item = (ResponseHead, Framed), Error = SendRequestError, >, @@ -49,7 +49,7 @@ where head: RequestHead, body: Body, addr: Option, - ) -> Box> { + ) -> Box> { Box::new( self.0 // connect to the host @@ -69,7 +69,7 @@ where head: RequestHead, addr: Option, ) -> Box< - Future< + dyn Future< Item = (ResponseHead, Framed), Error = SendRequestError, >, @@ -93,21 +93,21 @@ where } trait AsyncSocket { - fn as_read(&self) -> &AsyncRead; - fn as_read_mut(&mut self) -> &mut AsyncRead; - fn as_write(&mut self) -> &mut AsyncWrite; + fn as_read(&self) -> &dyn AsyncRead; + fn as_read_mut(&mut self) -> &mut dyn AsyncRead; + fn as_write(&mut self) -> &mut dyn AsyncWrite; } struct Socket(T); impl AsyncSocket for Socket { - fn as_read(&self) -> &AsyncRead { + fn as_read(&self) -> &dyn AsyncRead { &self.0 } - fn as_read_mut(&mut self) -> &mut AsyncRead { + fn as_read_mut(&mut self) -> &mut dyn AsyncRead { &mut self.0 } - fn as_write(&mut self) -> &mut AsyncWrite { + fn as_write(&mut self) -> &mut dyn AsyncWrite { &mut self.0 } } diff --git a/awc/src/lib.rs b/awc/src/lib.rs index 9fbda8aa8..da63bbd93 100644 --- a/awc/src/lib.rs +++ b/awc/src/lib.rs @@ -1,7 +1,8 @@ +#![allow(clippy::borrow_interior_mutable_const)] //! An HTTP Client //! //! ```rust -//! # use futures::future::{Future, lazy}; +//! use futures::future::{lazy, Future}; //! use actix_rt::System; //! use awc::Client; //! diff --git a/awc/src/request.rs b/awc/src/request.rs index 36cd6fcf3..0e5445897 100644 --- a/awc/src/request.rs +++ b/awc/src/request.rs @@ -185,9 +185,7 @@ impl ClientRequest { { match HeaderName::try_from(key) { Ok(key) => match value.try_into() { - Ok(value) => { - let _ = self.head.headers.append(key, value); - } + Ok(value) => self.head.headers.append(key, value), Err(e) => self.err = Some(e.into()), }, Err(e) => self.err = Some(e.into()), @@ -203,9 +201,7 @@ impl ClientRequest { { match HeaderName::try_from(key) { Ok(key) => match value.try_into() { - Ok(value) => { - let _ = self.head.headers.insert(key, value); - } + Ok(value) => self.head.headers.insert(key, value), Err(e) => self.err = Some(e.into()), }, Err(e) => self.err = Some(e.into()), @@ -223,9 +219,7 @@ impl ClientRequest { Ok(key) => { if !self.head.headers.contains_key(&key) { match value.try_into() { - Ok(value) => { - let _ = self.head.headers.insert(key, value); - } + Ok(value) => self.head.headers.insert(key, value), Err(e) => self.err = Some(e.into()), } } @@ -257,9 +251,7 @@ impl ClientRequest { HeaderValue: HttpTryFrom, { match HeaderValue::try_from(value) { - Ok(value) => { - let _ = self.head.headers.insert(header::CONTENT_TYPE, value); - } + Ok(value) => self.head.headers.insert(header::CONTENT_TYPE, value), Err(e) => self.err = Some(e.into()), } self @@ -321,7 +313,7 @@ impl ClientRequest { /// })); /// } /// ``` - pub fn cookie<'c>(mut self, cookie: Cookie<'c>) -> Self { + pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { if self.cookies.is_none() { let mut jar = CookieJar::new(); jar.add(cookie.into_owned()); @@ -465,7 +457,7 @@ impl ClientRequest { }); // set request timeout - if let Some(timeout) = slf.timeout.or_else(|| config.timeout.clone()) { + if let Some(timeout) = slf.timeout.or_else(|| config.timeout) { Either::B(Either::A(Timeout::new(fut, timeout).map_err(|e| { if let Some(e) = e.into_inner() { e diff --git a/awc/src/test.rs b/awc/src/test.rs index f2c513bab..b852adb2d 100644 --- a/awc/src/test.rs +++ b/awc/src/test.rs @@ -68,7 +68,7 @@ impl TestResponse { } /// Set cookie for this response - pub fn cookie<'a>(mut self, cookie: Cookie<'a>) -> Self { + pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { self.cookies.add(cookie.into_owned()); self } diff --git a/awc/src/ws.rs b/awc/src/ws.rs index 95bf6ef70..27f454ed3 100644 --- a/awc/src/ws.rs +++ b/awc/src/ws.rs @@ -90,7 +90,7 @@ impl WebsocketsRequest { } /// Set a cookie - pub fn cookie<'c>(mut self, cookie: Cookie<'c>) -> Self { + pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { if self.cookies.is_none() { let mut jar = CookieJar::new(); jar.add(cookie.into_owned()); diff --git a/src/app.rs b/src/app.rs index 3b063a841..f93859c7e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,16 +23,17 @@ use crate::service::{ }; type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; -type FnDataFactory = Box Box, Error = ()>>>; +type FnDataFactory = + Box Box, Error = ()>>>; /// Application builder - structure that follows the builder pattern /// for building application instances. pub struct App { endpoint: T, - services: Vec>, + services: Vec>, default: Option>, factory_ref: Rc>>, - data: Vec>, + data: Vec>, data_factories: Vec, config: AppConfigInner, external: Vec, diff --git a/src/app_service.rs b/src/app_service.rs index 8ab9b352a..736c35010 100644 --- a/src/app_service.rs +++ b/src/app_service.rs @@ -18,14 +18,15 @@ use crate::request::{HttpRequest, HttpRequestPool}; use crate::rmap::ResourceMap; use crate::service::{ServiceFactory, ServiceRequest, ServiceResponse}; -type Guards = Vec>; +type Guards = Vec>; type HttpService = BoxedService; type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type BoxedResponse = Either< FutureResult, - Box>, + Box>, >; -type FnDataFactory = Box Box, Error = ()>>>; +type FnDataFactory = + Box Box, Error = ()>>>; /// Service factory to convert `Request` to a `ServiceRequest`. /// It also executes data factories. @@ -40,10 +41,10 @@ where >, { pub(crate) endpoint: T, - pub(crate) data: Rc>>, + pub(crate) data: Rc>>, pub(crate) data_factories: Rc>, pub(crate) config: RefCell, - pub(crate) services: Rc>>>, + pub(crate) services: Rc>>>, pub(crate) default: Option>, pub(crate) factory_ref: Rc>>, pub(crate) external: RefCell>, @@ -142,9 +143,9 @@ where endpoint_fut: T::Future, rmap: Rc, config: AppConfig, - data: Rc>>, - data_factories: Vec>, - data_factories_fut: Vec, Error = ()>>>, + data: Rc>>, + data_factories: Vec>, + data_factories_fut: Vec, Error = ()>>>, _t: PhantomData, } @@ -297,14 +298,14 @@ impl NewService for AppRoutingFactory { } } -type HttpServiceFut = Box>; +type HttpServiceFut = Box>; /// Create app service #[doc(hidden)] pub struct AppRoutingFactoryResponse { fut: Vec, default: Option, - default_fut: Option>>, + default_fut: Option>>, } enum CreateAppRoutingItem { diff --git a/src/config.rs b/src/config.rs index 8de43f36c..bbbb3bb01 100644 --- a/src/config.rs +++ b/src/config.rs @@ -16,7 +16,7 @@ use crate::service::{ ServiceResponse, }; -type Guards = Vec>; +type Guards = Vec>; type HttpNewService = boxed::BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; @@ -31,7 +31,7 @@ pub struct AppService { Option, Option>, )>, - service_data: Rc>>, + service_data: Rc>>, } impl AppService { @@ -39,7 +39,7 @@ impl AppService { pub(crate) fn new( config: AppConfig, default: Rc, - service_data: Rc>>, + service_data: Rc>>, ) -> Self { AppService { config, @@ -101,7 +101,7 @@ impl AppService { pub fn register_service( &mut self, rdef: ResourceDef, - guards: Option>>, + guards: Option>>, service: F, nested: Option>, ) where @@ -174,8 +174,8 @@ impl Default for AppConfigInner { /// to set of external methods. This could help with /// modularization of big application configuration. pub struct ServiceConfig { - pub(crate) services: Vec>, - pub(crate) data: Vec>, + pub(crate) services: Vec>, + pub(crate) data: Vec>, pub(crate) external: Vec, } diff --git a/src/data.rs b/src/data.rs index bd166b79c..3461d24f3 100644 --- a/src/data.rs +++ b/src/data.rs @@ -118,7 +118,7 @@ impl FromRequest for Data { impl DataFactory for Data { fn create(&self, extensions: &mut Extensions) -> bool { if !extensions.contains::>() { - let _ = extensions.insert(Data(self.0.clone())); + extensions.insert(Data(self.0.clone())); true } else { false diff --git a/src/extract.rs b/src/extract.rs index 17b5cb40c..1687973ac 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -94,7 +94,7 @@ where { type Config = T::Config; type Error = Error; - type Future = Box, Error = Error>>; + type Future = Box, Error = Error>>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { @@ -165,7 +165,7 @@ where { type Config = T::Config; type Error = Error; - type Future = Box, Error = Error>>; + type Future = Box, Error = Error>>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { diff --git a/src/guard.rs b/src/guard.rs index 0990e876a..6522a9845 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -100,7 +100,7 @@ pub fn Any(guard: F) -> AnyGuard { } /// Matches if any of supplied guards matche. -pub struct AnyGuard(Vec>); +pub struct AnyGuard(Vec>); impl AnyGuard { /// Add guard to a list of guards to check @@ -140,7 +140,7 @@ pub fn All(guard: F) -> AllGuard { } /// Matches if all of supplied guards. -pub struct AllGuard(Vec>); +pub struct AllGuard(Vec>); impl AllGuard { /// Add new guard to the list of guards to check @@ -167,7 +167,7 @@ pub fn Not(guard: F) -> NotGuard { } #[doc(hidden)] -pub struct NotGuard(Box); +pub struct NotGuard(Box); impl Guard for NotGuard { fn check(&self, request: &RequestHead) -> bool { diff --git a/src/handler.rs b/src/handler.rs index bd0b35517..078abbf1d 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -250,7 +250,7 @@ where Ok(Async::Ready(res)) => { self.fut2 = Some(res.respond_to(self.req.as_ref().unwrap()).into_future()); - return self.poll(); + self.poll() } Ok(Async::NotReady) => Ok(Async::NotReady), Err(e) => { diff --git a/src/info.rs b/src/info.rs index e9b375875..ba59605de 100644 --- a/src/info.rs +++ b/src/info.rs @@ -25,7 +25,7 @@ impl ConnectionInfo { Ref::map(req.extensions(), |e| e.get().unwrap()) } - #[allow(clippy::cyclomatic_complexity)] + #[allow(clippy::cognitive_complexity)] fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo { let mut host = None; let mut scheme = None; diff --git a/src/lib.rs b/src/lib.rs index fffbc2f5e..857bc294e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +#![allow(clippy::borrow_interior_mutable_const)] //! Actix web is a small, pragmatic, and extremely fast web framework //! for Rust. //! @@ -134,6 +135,8 @@ pub mod dev { //! ``` pub use crate::config::{AppConfig, AppService}; + #[doc(hidden)] + pub use crate::handler::{AsyncFactory, Factory}; pub use crate::info::ConnectionInfo; pub use crate::rmap::ResourceMap; pub use crate::service::{ diff --git a/src/middleware/defaultheaders.rs b/src/middleware/defaultheaders.rs index bddcdd552..ab2d36c2c 100644 --- a/src/middleware/defaultheaders.rs +++ b/src/middleware/defaultheaders.rs @@ -119,7 +119,7 @@ where type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; - type Future = Box>; + type Future = Box>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() diff --git a/src/middleware/errhandlers.rs b/src/middleware/errhandlers.rs index ac166e0eb..5f73d4d7e 100644 --- a/src/middleware/errhandlers.rs +++ b/src/middleware/errhandlers.rs @@ -15,10 +15,10 @@ pub enum ErrorHandlerResponse { /// New http response got generated Response(ServiceResponse), /// Result is a future that resolves to a new http response - Future(Box, Error = Error>>), + Future(Box, Error = Error>>), } -type ErrorHandler = Fn(ServiceResponse) -> Result>; +type ErrorHandler = dyn Fn(ServiceResponse) -> Result>; /// `Middleware` for allowing custom handlers for responses. /// @@ -117,7 +117,7 @@ where type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; - type Future = Box>; + type Future = Box>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() diff --git a/src/middleware/logger.rs b/src/middleware/logger.rs index d47e45023..9e332fb83 100644 --- a/src/middleware/logger.rs +++ b/src/middleware/logger.rs @@ -415,9 +415,9 @@ impl FormatText { )) }; } - FormatText::UrlPath => *self = FormatText::Str(format!("{}", req.path())), + FormatText::UrlPath => *self = FormatText::Str(req.path().to_string()), FormatText::RequestTime => { - *self = FormatText::Str(format!("{}", now.rfc3339())) + *self = FormatText::Str(now.rfc3339().to_string()) } FormatText::RequestHeader(ref name) => { let s = if let Some(val) = req.headers().get(name) { @@ -444,7 +444,9 @@ impl FormatText { } } -pub(crate) struct FormatDisplay<'a>(&'a Fn(&mut Formatter) -> Result<(), fmt::Error>); +pub(crate) struct FormatDisplay<'a>( + &'a dyn Fn(&mut Formatter) -> Result<(), fmt::Error>, +); impl<'a> fmt::Display for FormatDisplay<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { diff --git a/src/request.rs b/src/request.rs index 07aac8cf7..0fc0647ff 100644 --- a/src/request.rs +++ b/src/request.rs @@ -174,6 +174,12 @@ impl HttpRequest { self.url_for(name, &NO_PARAMS) } + #[inline] + /// Get a reference to a `ResourceMap` of current application. + pub fn resource_map(&self) -> &ResourceMap { + &self.0.rmap + } + /// Peer socket address /// /// Peer address is actual socket address, if proxy is used in front of @@ -186,6 +192,9 @@ impl HttpRequest { } /// Get *ConnectionInfo* for the current request. + /// + /// This method panics if request's extensions container is already + /// borrowed. #[inline] pub fn connection_info(&self) -> Ref { ConnectionInfo::get(self.head(), &*self.app_config()) diff --git a/src/resource.rs b/src/resource.rs index c2691eebe..0af43a424 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -50,7 +50,7 @@ pub struct Resource { name: Option, routes: Vec, data: Option, - guards: Vec>, + guards: Vec>, default: Rc>>>, factory_ref: Rc>>, } @@ -118,7 +118,7 @@ where self } - pub(crate) fn add_guards(mut self, guards: Vec>) -> Self { + pub(crate) fn add_guards(mut self, guards: Vec>) -> Self { self.guards.extend(guards); self } @@ -245,7 +245,7 @@ where /// ```rust /// # use actix_web::*; /// # use futures::future::Future; - /// # fn index(req: HttpRequest) -> Box> { + /// # fn index(req: HttpRequest) -> Box> { /// # unimplemented!() /// # } /// App::new().service(web::resource("/").route(web::route().to_async(index))); @@ -426,7 +426,7 @@ where fn into_new_service(self) -> T { *self.factory_ref.borrow_mut() = Some(ResourceFactory { routes: self.routes, - data: self.data.map(|data| Rc::new(data)), + data: self.data.map(Rc::new), default: self.default, }); @@ -478,7 +478,7 @@ pub struct CreateResourceService { fut: Vec, data: Option>, default: Option, - default_fut: Option>>, + default_fut: Option>>, } impl Future for CreateResourceService { @@ -542,7 +542,7 @@ impl Service for ResourceService { type Error = Error; type Future = Either< FutureResult, - Box>, + Box>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { diff --git a/src/responder.rs b/src/responder.rs index 47a8800ef..4988ad5bc 100644 --- a/src/responder.rs +++ b/src/responder.rs @@ -137,6 +137,22 @@ impl Responder for () { } } +impl Responder for (T, StatusCode) +where + T: Responder, +{ + type Error = T::Error; + type Future = CustomResponderFut; + + fn respond_to(self, req: &HttpRequest) -> Self::Future { + CustomResponderFut { + fut: self.0.respond_to(req).into_future(), + status: Some(self.1), + headers: None, + } + } +} + impl Responder for &'static str { type Error = Error; type Future = FutureResult; @@ -321,7 +337,7 @@ impl Future for CustomResponderFut { /// use actix_web::{Either, Error, HttpResponse}; /// /// type RegisterResult = -/// Either>>; +/// Either>>; /// /// fn index() -> RegisterResult { /// if is_a_variant() { @@ -395,13 +411,13 @@ where } } -impl Responder for Box> +impl Responder for Box> where I: Responder + 'static, E: Into + 'static, { type Error = Error; - type Future = Box>; + type Future = Box>; #[inline] fn respond_to(self, req: &HttpRequest) -> Self::Future { @@ -624,4 +640,28 @@ pub(crate) mod tests { HeaderValue::from_static("json") ); } + + #[test] + fn test_tuple_responder_with_status_code() { + let req = TestRequest::default().to_http_request(); + let res = + block_on(("test".to_string(), StatusCode::BAD_REQUEST).respond_to(&req)) + .unwrap(); + assert_eq!(res.status(), StatusCode::BAD_REQUEST); + assert_eq!(res.body().bin_ref(), b"test"); + + let req = TestRequest::default().to_http_request(); + let res = block_on( + ("test".to_string(), StatusCode::OK) + .with_header("content-type", "json") + .respond_to(&req), + ) + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + assert_eq!(res.body().bin_ref(), b"test"); + assert_eq!( + res.headers().get(CONTENT_TYPE).unwrap(), + HeaderValue::from_static("json") + ); + } } diff --git a/src/rmap.rs b/src/rmap.rs index cad62dca0..42ddb1349 100644 --- a/src/rmap.rs +++ b/src/rmap.rs @@ -123,7 +123,7 @@ impl ResourceMap { I: AsRef, { if let Some(pattern) = self.named.get(name) { - if pattern.pattern().starts_with("/") { + if pattern.pattern().starts_with('/') { self.fill_root(path, elements)?; } if pattern.resource_path(path, elements) { diff --git a/src/route.rs b/src/route.rs index 660b82002..f4d303632 100644 --- a/src/route.rs +++ b/src/route.rs @@ -13,26 +13,26 @@ use crate::service::{ServiceRequest, ServiceResponse}; use crate::HttpResponse; type BoxedRouteService = Box< - Service< + dyn Service< Request = Req, Response = Res, Error = Error, Future = Either< FutureResult, - Box>, + Box>, >, >, >; type BoxedRouteNewService = Box< - NewService< + dyn NewService< Config = (), Request = Req, Response = Res, Error = Error, InitError = (), Service = BoxedRouteService, - Future = Box, Error = ()>>, + Future = Box, Error = ()>>, >, >; @@ -42,7 +42,7 @@ type BoxedRouteNewService = Box< /// If handler is not explicitly set, default *404 Not Found* handler is used. pub struct Route { service: BoxedRouteNewService, - guards: Rc>>, + guards: Rc>>, } impl Route { @@ -56,7 +56,7 @@ impl Route { } } - pub(crate) fn take_guards(&mut self) -> Vec> { + pub(crate) fn take_guards(&mut self) -> Vec> { std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new()) } } @@ -78,12 +78,13 @@ impl NewService for Route { } } -type RouteFuture = - Box, Error = ()>>; +type RouteFuture = Box< + dyn Future, Error = ()>, +>; pub struct CreateRouteService { fut: RouteFuture, - guards: Rc>>, + guards: Rc>>, } impl Future for CreateRouteService { @@ -103,7 +104,7 @@ impl Future for CreateRouteService { pub struct RouteService { service: BoxedRouteService, - guards: Rc>>, + guards: Rc>>, } impl RouteService { @@ -123,7 +124,7 @@ impl Service for RouteService { type Error = Error; type Future = Either< FutureResult, - Box>, + Box>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { @@ -317,7 +318,7 @@ where type Error = Error; type InitError = (); type Service = BoxedRouteService; - type Future = Box>; + type Future = Box>; fn new_service(&self, _: &()) -> Self::Future { Box::new( @@ -351,7 +352,7 @@ where type Error = Error; type Future = Either< FutureResult, - Box>, + Box>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { diff --git a/src/scope.rs b/src/scope.rs index 400da668d..760fee478 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -23,12 +23,12 @@ use crate::service::{ ServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse, }; -type Guards = Vec>; +type Guards = Vec>; type HttpService = BoxedService; type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type BoxedResponse = Either< FutureResult, - Box>, + Box>, >; /// Resources scope. @@ -64,8 +64,8 @@ pub struct Scope { endpoint: T, rdef: String, data: Option, - services: Vec>, - guards: Vec>, + services: Vec>, + guards: Vec>, default: Rc>>>, external: Vec, factory_ref: Rc>>, @@ -195,7 +195,7 @@ where self.external.extend(cfg.external); if !cfg.data.is_empty() { - let mut data = self.data.unwrap_or_else(|| Extensions::new()); + let mut data = self.data.unwrap_or_else(Extensions::new); for value in cfg.data.iter() { value.create(&mut data); @@ -425,7 +425,7 @@ where // complete scope pipeline creation *self.factory_ref.borrow_mut() = Some(ScopeFactory { - data: self.data.take().map(|data| Rc::new(data)), + data: self.data.take().map(Rc::new), default: self.default.clone(), services: Rc::new( cfg.into_services() @@ -503,10 +503,10 @@ pub struct ScopeFactoryResponse { fut: Vec, data: Option>, default: Option, - default_fut: Option>>, + default_fut: Option>>, } -type HttpServiceFut = Box>; +type HttpServiceFut = Box>; enum CreateScopeServiceItem { Future(Option, Option, HttpServiceFut), @@ -578,7 +578,7 @@ impl Future for ScopeFactoryResponse { pub struct ScopeService { data: Option>, - router: Router>>, + router: Router>>, default: Option, _ready: Option<(ServiceRequest, ResourceInfo)>, } diff --git a/src/server.rs b/src/server.rs index 353f29ba9..43236fa34 100644 --- a/src/server.rs +++ b/src/server.rs @@ -288,13 +288,13 @@ where lst, move || { let c = cfg.lock(); - acceptor.clone().map_err(|e| SslError::Ssl(e)).and_then( + acceptor.clone().map_err(SslError::Ssl).and_then( HttpService::build() .keep_alive(c.keep_alive) .client_timeout(c.client_timeout) .client_disconnect(c.client_shutdown) .finish(factory()) - .map_err(|e| SslError::Service(e)) + .map_err(SslError::Service) .map_init_err(|_| ()), ) }, @@ -339,13 +339,13 @@ where lst, move || { let c = cfg.lock(); - acceptor.clone().map_err(|e| SslError::Ssl(e)).and_then( + acceptor.clone().map_err(SslError::Ssl).and_then( HttpService::build() .keep_alive(c.keep_alive) .client_timeout(c.client_timeout) .client_disconnect(c.client_shutdown) .finish(factory()) - .map_err(|e| SslError::Service(e)) + .map_err(SslError::Service) .map_init_err(|_| ()), ) }, diff --git a/src/service.rs b/src/service.rs index 722813a9f..1d475cf15 100644 --- a/src/service.rs +++ b/src/service.rs @@ -18,6 +18,7 @@ use crate::dev::insert_slash; use crate::guard::Guard; use crate::info::ConnectionInfo; use crate::request::HttpRequest; +use crate::rmap::ResourceMap; pub trait HttpServiceFactory { fn register(self, config: &mut AppService); @@ -169,10 +170,17 @@ impl ServiceRequest { } #[inline] + /// Get a mutable reference to the Path parameters. pub fn match_info_mut(&mut self) -> &mut Path { self.0.match_info_mut() } + #[inline] + /// Get a reference to a `ResourceMap` of current application. + pub fn resource_map(&self) -> &ResourceMap { + self.0.resource_map() + } + /// Service configuration #[inline] pub fn app_config(&self) -> &AppConfig { @@ -399,7 +407,7 @@ impl fmt::Debug for ServiceResponse { pub struct WebService { rdef: String, name: Option, - guards: Vec>, + guards: Vec>, } impl WebService { @@ -468,7 +476,7 @@ struct WebServiceImpl { srv: T, rdef: String, name: Option, - guards: Vec>, + guards: Vec>, } impl HttpServiceFactory for WebServiceImpl diff --git a/src/test.rs b/src/test.rs index 208360a29..562fdf436 100644 --- a/src/test.rs +++ b/src/test.rs @@ -79,7 +79,7 @@ where F: FnOnce() -> R, R: IntoFuture, { - RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f()))) + RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(f))) } #[doc(hidden)] diff --git a/src/types/form.rs b/src/types/form.rs index 32d0edb69..42e6363f1 100644 --- a/src/types/form.rs +++ b/src/types/form.rs @@ -73,7 +73,7 @@ where { type Config = FormConfig; type Error = Error; - type Future = Box>; + type Future = Box>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { @@ -141,7 +141,7 @@ impl fmt::Display for Form { #[derive(Clone)] pub struct FormConfig { limit: usize, - ehandler: Option Error>>, + ehandler: Option Error>>, } impl FormConfig { @@ -187,7 +187,7 @@ pub struct UrlEncoded { length: Option, encoding: &'static Encoding, err: Option, - fut: Option>>, + fut: Option>>, } impl UrlEncoded { diff --git a/src/types/json.rs b/src/types/json.rs index de0ffb54c..f309a3c5a 100644 --- a/src/types/json.rs +++ b/src/types/json.rs @@ -169,7 +169,7 @@ where T: DeserializeOwned + 'static, { type Error = Error; - type Future = Box>; + type Future = Box>; type Config = JsonConfig; #[inline] @@ -290,7 +290,7 @@ pub struct JsonBody { length: Option, stream: Option>, err: Option, - fut: Option>>, + fut: Option>>, } impl JsonBody diff --git a/src/types/path.rs b/src/types/path.rs index 2a6ce2879..a46575764 100644 --- a/src/types/path.rs +++ b/src/types/path.rs @@ -224,7 +224,7 @@ where /// ``` #[derive(Clone)] pub struct PathConfig { - ehandler: Option Error + Send + Sync>>, + ehandler: Option Error + Send + Sync>>, } impl PathConfig { diff --git a/src/types/payload.rs b/src/types/payload.rs index a8e85e4f3..f33e2e5f1 100644 --- a/src/types/payload.rs +++ b/src/types/payload.rs @@ -124,11 +124,11 @@ impl FromRequest for Bytes { type Config = PayloadConfig; type Error = Error; type Future = - Either>, FutureResult>; + Either>, FutureResult>; #[inline] fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { - let mut tmp; + let tmp; let cfg = if let Some(cfg) = req.app_data::() { cfg } else { @@ -177,12 +177,14 @@ impl FromRequest for Bytes { impl FromRequest for String { type Config = PayloadConfig; type Error = Error; - type Future = - Either>, FutureResult>; + type Future = Either< + Box>, + FutureResult, + >; #[inline] fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { - let mut tmp; + let tmp; let cfg = if let Some(cfg) = req.app_data::() { cfg } else { @@ -291,7 +293,7 @@ pub struct HttpMessageBody { length: Option, stream: Option>, err: Option, - fut: Option>>, + fut: Option>>, } impl HttpMessageBody { diff --git a/src/types/query.rs b/src/types/query.rs index 17240c0b5..2ad7106d0 100644 --- a/src/types/query.rs +++ b/src/types/query.rs @@ -192,7 +192,8 @@ where /// ``` #[derive(Clone)] pub struct QueryConfig { - ehandler: Option Error + Send + Sync>>, + ehandler: + Option Error + Send + Sync>>, } impl QueryConfig { diff --git a/test-server/CHANGES.md b/test-server/CHANGES.md index e7292c0ec..f3e98010a 100644 --- a/test-server/CHANGES.md +++ b/test-server/CHANGES.md @@ -1,5 +1,9 @@ # Changes +## [0.2.3] - 2019-07-16 + +* Add `delete`, `options`, `patch` methods to `TestServerRunner` + ## [0.2.2] - 2019-06-16 * Add .put() and .sput() methods diff --git a/test-server/Cargo.toml b/test-server/Cargo.toml index 4231b17bf..445ed33e6 100644 --- a/test-server/Cargo.toml +++ b/test-server/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "actix-http-test" -version = "0.2.2" +version = "0.2.3" authors = ["Nikolay Kim "] description = "Actix http test server" readme = "README.md" @@ -35,7 +35,7 @@ actix-rt = "0.2.2" actix-service = "0.4.1" actix-server = "0.5.1" actix-utils = "0.4.1" -awc = "0.2.1" +awc = "0.2.2" base64 = "0.10" bytes = "0.4" diff --git a/test-server/src/lib.rs b/test-server/src/lib.rs index 1fbaa6c74..38405cd55 100644 --- a/test-server/src/lib.rs +++ b/test-server/src/lib.rs @@ -65,7 +65,7 @@ where F: FnOnce() -> R, R: IntoFuture, { - RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f()))) + RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(f))) } /// The `TestServer` type. @@ -107,6 +107,7 @@ pub struct TestServerRuntime { } impl TestServer { + #[allow(clippy::new_ret_no_self)] /// Start new test server with application factory pub fn new(factory: F) -> TestServerRuntime { let (tx, rx) = mpsc::channel(); @@ -191,7 +192,7 @@ impl TestServerRuntime { F: FnOnce() -> R, R: Future, { - self.rt.block_on(lazy(|| f())) + self.rt.block_on(lazy(f)) } /// Execute function on current core @@ -265,6 +266,36 @@ impl TestServerRuntime { self.client.put(self.surl(path.as_ref()).as_str()) } + /// Create `PATCH` request + pub fn patch>(&self, path: S) -> ClientRequest { + self.client.patch(self.url(path.as_ref()).as_str()) + } + + /// Create https `PATCH` request + pub fn spatch>(&self, path: S) -> ClientRequest { + self.client.patch(self.surl(path.as_ref()).as_str()) + } + + /// Create `DELETE` request + pub fn delete>(&self, path: S) -> ClientRequest { + self.client.delete(self.url(path.as_ref()).as_str()) + } + + /// Create https `DELETE` request + pub fn sdelete>(&self, path: S) -> ClientRequest { + self.client.delete(self.surl(path.as_ref()).as_str()) + } + + /// Create `OPTIONS` request + pub fn options>(&self, path: S) -> ClientRequest { + self.client.options(self.url(path.as_ref()).as_str()) + } + + /// Create https `OPTIONS` request + pub fn soptions>(&self, path: S) -> ClientRequest { + self.client.options(self.surl(path.as_ref()).as_str()) + } + /// Connect to test http server pub fn request>(&self, method: Method, path: S) -> ClientRequest { self.client.request(method, path.as_ref())