diff --git a/src/application.rs b/src/application.rs index 4b5747a4d..481430aab 100644 --- a/src/application.rs +++ b/src/application.rs @@ -780,9 +780,7 @@ mod tests { #[test] fn test_handler() { - let mut app = App::new() - .handler("/test", |_| HttpResponse::Ok()) - .finish(); + let mut app = App::new().handler("/test", |_| HttpResponse::Ok()).finish(); let req = TestRequest::with_uri("/test").finish(); let resp = app.run(req); @@ -807,9 +805,7 @@ mod tests { #[test] fn test_handler2() { - let mut app = App::new() - .handler("test", |_| HttpResponse::Ok()) - .finish(); + let mut app = App::new().handler("test", |_| HttpResponse::Ok()).finish(); let req = TestRequest::with_uri("/test").finish(); let resp = app.run(req); @@ -863,29 +859,21 @@ mod tests { #[test] fn test_route() { let mut app = App::new() - .route("/test", Method::GET, |_: HttpRequest| { - HttpResponse::Ok() - }) + .route("/test", Method::GET, |_: HttpRequest| HttpResponse::Ok()) .route("/test", Method::POST, |_: HttpRequest| { HttpResponse::Created() }) .finish(); - let req = TestRequest::with_uri("/test") - .method(Method::GET) - .finish(); + let req = TestRequest::with_uri("/test").method(Method::GET).finish(); let resp = app.run(req); assert_eq!(resp.as_msg().status(), StatusCode::OK); - let req = TestRequest::with_uri("/test") - .method(Method::POST) - .finish(); + let req = TestRequest::with_uri("/test").method(Method::POST).finish(); let resp = app.run(req); assert_eq!(resp.as_msg().status(), StatusCode::CREATED); - let req = TestRequest::with_uri("/test") - .method(Method::HEAD) - .finish(); + let req = TestRequest::with_uri("/test").method(Method::HEAD).finish(); let resp = app.run(req); assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND); } diff --git a/src/client/connector.rs b/src/client/connector.rs index e082c9ed5..6389b8972 100644 --- a/src/client/connector.rs +++ b/src/client/connector.rs @@ -8,8 +8,10 @@ use std::{fmt, io, mem, time}; use actix::actors::{Connect as ResolveConnect, Connector, ConnectorError}; use actix::fut::WrapFuture; use actix::registry::ArbiterService; -use actix::{fut, Actor, ActorFuture, ActorResponse, Arbiter, AsyncContext, Context, - ContextFutureSpawner, Handler, Message, Recipient, Supervised, Syn}; +use actix::{ + fut, Actor, ActorFuture, ActorResponse, Arbiter, AsyncContext, Context, + ContextFutureSpawner, Handler, Message, Recipient, Supervised, Syn, +}; use futures::task::{current as current_task, Task}; use futures::unsync::oneshot; @@ -429,8 +431,7 @@ impl ClientConnector { } else { 0 }; - self.acquired_per_host - .insert(key.clone(), per_host + 1); + self.acquired_per_host.insert(key.clone(), per_host + 1); } fn release_key(&mut self, key: &Key) { @@ -441,8 +442,7 @@ impl ClientConnector { return; }; if per_host > 1 { - self.acquired_per_host - .insert(key.clone(), per_host - 1); + self.acquired_per_host.insert(key.clone(), per_host - 1); } else { self.acquired_per_host.remove(key); } @@ -518,9 +518,7 @@ impl ClientConnector { fn collect_periodic(&mut self, ctx: &mut Context) { self.collect(true); // re-schedule next collect period - ctx.run_later(Duration::from_secs(1), |act, ctx| { - act.collect_periodic(ctx) - }); + ctx.run_later(Duration::from_secs(1), |act, ctx| act.collect_periodic(ctx)); // send stats let stats = mem::replace(&mut self.stats, ClientConnectorStats::default()); @@ -1107,10 +1105,7 @@ impl Pool { if self.to_close.borrow().is_empty() { None } else { - Some(mem::replace( - &mut *self.to_close.borrow_mut(), - Vec::new(), - )) + Some(mem::replace(&mut *self.to_close.borrow_mut(), Vec::new())) } } @@ -1118,10 +1113,7 @@ impl Pool { if self.to_release.borrow().is_empty() { None } else { - Some(mem::replace( - &mut *self.to_release.borrow_mut(), - Vec::new(), - )) + Some(mem::replace(&mut *self.to_release.borrow_mut(), Vec::new())) } } diff --git a/src/client/mod.rs b/src/client/mod.rs index 2116ae360..9fd885faa 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -33,8 +33,10 @@ mod request; mod response; mod writer; -pub use self::connector::{ClientConnector, ClientConnectorError, ClientConnectorStats, - Connect, Connection, Pause, Resume}; +pub use self::connector::{ + ClientConnector, ClientConnectorError, ClientConnectorStats, Connect, Connection, + Pause, Resume, +}; pub(crate) use self::parser::{HttpResponseParser, HttpResponseParserError}; pub use self::pipeline::{SendRequest, SendRequestError}; pub use self::request::{ClientRequest, ClientRequestBuilder}; diff --git a/src/client/pipeline.rs b/src/client/pipeline.rs index 6a36bdd23..dae7bbaf8 100644 --- a/src/client/pipeline.rs +++ b/src/client/pipeline.rs @@ -270,7 +270,8 @@ impl Pipeline { #[inline] fn parse(&mut self) -> Poll { if let Some(ref mut conn) = self.conn { - match self.parser + match self + .parser .as_mut() .unwrap() .parse(conn, &mut self.parser_buf) @@ -311,7 +312,8 @@ impl Pipeline { let mut need_run = false; // need write? - match self.poll_write() + match self + .poll_write() .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}", e)))? { Async::NotReady => need_run = true, @@ -325,7 +327,8 @@ impl Pipeline { // need read? if self.parser.is_some() { loop { - match self.parser + match self + .parser .as_mut() .unwrap() .parse_payload(conn, &mut self.parser_buf)? @@ -469,7 +472,8 @@ impl Pipeline { } // flush io but only if we need to - match self.writer + match self + .writer .poll_completed(self.conn.as_mut().unwrap(), false) { Ok(Async::Ready(_)) => { diff --git a/src/client/request.rs b/src/client/request.rs index 4eaf8002b..2f9ce12f9 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -499,10 +499,7 @@ impl ClientRequestBuilder { jar.add(cookie.into_owned()); self.cookies = Some(jar) } else { - self.cookies - .as_mut() - .unwrap() - .add(cookie.into_owned()); + self.cookies.as_mut().unwrap().add(cookie.into_owned()); } self } @@ -610,9 +607,7 @@ impl ClientRequestBuilder { } } - let mut request = self.request - .take() - .expect("cannot reuse request builder"); + let mut request = self.request.take().expect("cannot reuse request builder"); // set cookies if let Some(ref mut jar) = self.cookies { @@ -657,9 +652,7 @@ impl ClientRequestBuilder { S: Stream + 'static, E: Into, { - self.body(Body::Streaming(Box::new( - stream.map_err(|e| e.into()), - ))) + self.body(Body::Streaming(Box::new(stream.map_err(|e| e.into())))) } /// Set an empty body and generate `ClientRequest` diff --git a/src/client/response.rs b/src/client/response.rs index 4d186d19c..f76d058e5 100644 --- a/src/client/response.rs +++ b/src/client/response.rs @@ -103,12 +103,7 @@ impl ClientResponse { impl fmt::Debug for ClientResponse { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let res = writeln!( - f, - "\nClientResponse {:?} {}", - self.version(), - self.status() - ); + let res = writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status()); let _ = writeln!(f, " headers:"); for (key, val) in self.headers().iter() { let _ = writeln!(f, " {:?}: {:?}", key, val); @@ -138,14 +133,12 @@ mod tests { #[test] fn test_debug() { let resp = ClientResponse::new(ClientMessage::default()); - resp.as_mut().headers.insert( - header::COOKIE, - HeaderValue::from_static("cookie1=value1"), - ); - resp.as_mut().headers.insert( - header::COOKIE, - HeaderValue::from_static("cookie2=value2"), - ); + resp.as_mut() + .headers + .insert(header::COOKIE, HeaderValue::from_static("cookie1=value1")); + resp.as_mut() + .headers + .insert(header::COOKIE, HeaderValue::from_static("cookie2=value2")); let dbg = format!("{:?}", resp); assert!(dbg.contains("ClientResponse")); diff --git a/src/client/writer.rs b/src/client/writer.rs index 36c9d6ee0..addc03240 100644 --- a/src/client/writer.rs +++ b/src/client/writer.rs @@ -12,8 +12,9 @@ use flate2::write::{DeflateEncoder, GzEncoder}; #[cfg(feature = "flate2")] use flate2::Compression; use futures::{Async, Poll}; -use http::header::{HeaderValue, CONNECTION, CONTENT_ENCODING, CONTENT_LENGTH, DATE, - TRANSFER_ENCODING}; +use http::header::{ + HeaderValue, CONNECTION, CONTENT_ENCODING, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, +}; use http::{HttpTryFrom, Version}; use time::{self, Duration}; use tokio_io::AsyncWrite; @@ -253,10 +254,8 @@ fn content_encoder(buf: SharedBytes, req: &mut ClientRequest) -> ContentEncoder } let mut b = BytesMut::new(); let _ = write!(b, "{}", bytes.len()); - req.headers_mut().insert( - CONTENT_LENGTH, - HeaderValue::try_from(b.freeze()).unwrap(), - ); + req.headers_mut() + .insert(CONTENT_LENGTH, HeaderValue::try_from(b.freeze()).unwrap()); TransferEncoding::eof(buf) } Body::Streaming(_) | Body::Actor(_) => { diff --git a/src/context.rs b/src/context.rs index 933fed506..375e8ef1d 100644 --- a/src/context.rs +++ b/src/context.rs @@ -6,8 +6,10 @@ use std::marker::PhantomData; use actix::dev::{ContextImpl, SyncEnvelope, ToEnvelope}; use actix::fut::ActorFuture; -use actix::{Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, - SpawnHandle, Syn, Unsync}; +use actix::{ + Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, SpawnHandle, + Syn, Unsync, +}; use body::{Binary, Body}; use error::{Error, ErrorInternalServerError}; @@ -80,7 +82,8 @@ where #[doc(hidden)] #[inline] fn waiting(&self) -> bool { - self.inner.waiting() || self.inner.state() == ActorState::Stopping + self.inner.waiting() + || self.inner.state() == ActorState::Stopping || self.inner.state() == ActorState::Stopped } #[inline] diff --git a/src/de.rs b/src/de.rs index 3ab3646e3..ad3327870 100644 --- a/src/de.rs +++ b/src/de.rs @@ -202,7 +202,8 @@ impl<'de> de::MapAccess<'de> for ParamsDeserializer<'de> { where K: de::DeserializeSeed<'de>, { - self.current = self.params + self.current = self + .params .next() .map(|&(ref k, ref v)| (k.as_ref(), v.as_ref())); match self.current { @@ -336,9 +337,7 @@ impl<'de> Deserializer<'de> for Value<'de> { where V: Visitor<'de>, { - visitor.visit_enum(ValueEnum { - value: self.value, - }) + visitor.visit_enum(ValueEnum { value: self.value }) } fn deserialize_newtype_struct( @@ -372,9 +371,7 @@ impl<'de> Deserializer<'de> for Value<'de> { where V: Visitor<'de>, { - Err(de::value::Error::custom( - "unsupported type: tuple struct", - )) + Err(de::value::Error::custom("unsupported type: tuple struct")) } unsupported_type!(deserialize_any, "any"); @@ -415,10 +412,7 @@ impl<'de> de::EnumAccess<'de> for ValueEnum<'de> { where V: de::DeserializeSeed<'de>, { - Ok(( - seed.deserialize(Key { key: self.value })?, - UnitVariant, - )) + Ok((seed.deserialize(Key { key: self.value })?, UnitVariant)) } } diff --git a/src/extractor.rs b/src/extractor.rs index a08e96674..fc9145b92 100644 --- a/src/extractor.rs +++ b/src/extractor.rs @@ -11,7 +11,7 @@ use serde::de::{self, DeserializeOwned}; use serde_urlencoded; use de::PathDeserializer; -use error::{Error, ErrorNotFound, ErrorBadRequest}; +use error::{Error, ErrorBadRequest, ErrorNotFound}; use handler::{AsyncResult, FromRequest}; use httpmessage::{HttpMessage, MessageBody, UrlEncoded}; use httprequest::HttpRequest; @@ -330,9 +330,7 @@ impl FromRequest for Bytes { cfg.check_mimetype(req)?; Ok(Box::new( - MessageBody::new(req.clone()) - .limit(cfg.limit) - .from_err(), + MessageBody::new(req.clone()).limit(cfg.limit).from_err(), )) } } @@ -512,14 +510,7 @@ tuple_from_req!(TupleFromRequest1, (0, A)); tuple_from_req!(TupleFromRequest2, (0, A), (1, B)); tuple_from_req!(TupleFromRequest3, (0, A), (1, B), (2, C)); tuple_from_req!(TupleFromRequest4, (0, A), (1, B), (2, C), (3, D)); -tuple_from_req!( - TupleFromRequest5, - (0, A), - (1, B), - (2, C), - (3, D), - (4, E) -); +tuple_from_req!(TupleFromRequest5, (0, A), (1, B), (2, C), (3, D), (4, E)); tuple_from_req!( TupleFromRequest6, (0, A), @@ -587,11 +578,7 @@ mod tests { req.payload_mut() .unread_data(Bytes::from_static(b"hello=world")); - match Bytes::from_request(&req, &cfg) - .unwrap() - .poll() - .unwrap() - { + match Bytes::from_request(&req, &cfg).unwrap().poll().unwrap() { Async::Ready(s) => { assert_eq!(s, Bytes::from_static(b"hello=world")); } @@ -606,11 +593,7 @@ mod tests { req.payload_mut() .unread_data(Bytes::from_static(b"hello=world")); - match String::from_request(&req, &cfg) - .unwrap() - .poll() - .unwrap() - { + match String::from_request(&req, &cfg).unwrap().poll().unwrap() { Async::Ready(s) => { assert_eq!(s, "hello=world"); } @@ -680,10 +663,7 @@ mod tests { let mut resource = ResourceHandler::<()>::default(); resource.name("index"); let mut routes = Vec::new(); - routes.push(( - Resource::new("index", "/{key}/{value}/"), - Some(resource), - )); + routes.push((Resource::new("index", "/{key}/{value}/"), Some(resource))); let (router, _) = Router::new("", ServerSettings::default(), routes); assert!(router.recognize(&mut req).is_some()); @@ -735,10 +715,7 @@ mod tests { let mut resource = ResourceHandler::<()>::default(); resource.name("index"); let mut routes = Vec::new(); - routes.push(( - Resource::new("index", "/{key}/{value}/"), - Some(resource), - )); + routes.push((Resource::new("index", "/{key}/{value}/"), Some(resource))); let (router, _) = Router::new("", ServerSettings::default(), routes); assert!(router.recognize(&mut req).is_some()); diff --git a/src/fs.rs b/src/fs.rs index 106d187a2..2de35994e 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -203,29 +203,26 @@ impl Responder for NamedFile { if self.status_code != StatusCode::OK { let mut resp = HttpResponse::build(self.status_code); resp.if_some(self.path().extension(), |ext, resp| { - resp.set(header::ContentType(get_mime_type( - &ext.to_string_lossy(), - ))); + resp.set(header::ContentType(get_mime_type(&ext.to_string_lossy()))); }).if_some(self.path().file_name(), |file_name, resp| { - let mime_type = guess_mime_type(self.path()); - let inline_or_attachment = match mime_type.type_() { - mime::IMAGE | mime::TEXT | mime::VIDEO => "inline", - _ => "attachment", - }; - resp.header( - "Content-Disposition", - format!( - "{inline_or_attachment}; filename={filename}", - inline_or_attachment = inline_or_attachment, - filename = file_name.to_string_lossy() - ), - ); - }); + let mime_type = guess_mime_type(self.path()); + let inline_or_attachment = match mime_type.type_() { + mime::IMAGE | mime::TEXT | mime::VIDEO => "inline", + _ => "attachment", + }; + resp.header( + "Content-Disposition", + format!( + "{inline_or_attachment}; filename={filename}", + inline_or_attachment = inline_or_attachment, + filename = file_name.to_string_lossy() + ), + ); + }); let reader = ChunkedReadFile { size: self.md.len(), offset: 0, - cpu_pool: self.cpu_pool - .unwrap_or_else(|| req.cpu_pool().clone()), + cpu_pool: self.cpu_pool.unwrap_or_else(|| req.cpu_pool().clone()), file: Some(self.file), fut: None, counter: 0, @@ -269,9 +266,7 @@ impl Responder for NamedFile { let mut resp = HttpResponse::build(self.status_code); resp.if_some(self.path().extension(), |ext, resp| { - resp.set(header::ContentType(get_mime_type( - &ext.to_string_lossy(), - ))); + resp.set(header::ContentType(get_mime_type(&ext.to_string_lossy()))); }).if_some(self.path().file_name(), |file_name, resp| { let mime_type = guess_mime_type(self.path()); let inline_or_attachment = match mime_type.type_() { @@ -293,9 +288,9 @@ impl Responder for NamedFile { .if_some(etag, |etag, resp| { resp.set(header::ETag(etag)); }); - - // TODO: Debug, enabling "accept-ranges: bytes" causes problems with - // certain clients when not using the ranges header. + + // TODO: Debug, enabling "accept-ranges: bytes" causes problems with + // certain clients when not using the ranges header. //resp.header(header::ACCEPT_RANGES, format!("bytes")); let mut length = self.md.len(); @@ -307,7 +302,15 @@ impl Responder for NamedFile { if let Ok(rangesvec) = HttpRange::parse(rangesheader, length) { length = rangesvec[0].length - 1; offset = rangesvec[0].start; - resp.header(header::RANGE, format!("bytes={}-{}/{}", offset, offset+length, self.md.len())); + resp.header( + header::RANGE, + format!( + "bytes={}-{}/{}", + offset, + offset + length, + self.md.len() + ), + ); } else { resp.header(header::RANGE, format!("*/{}", length)); return Ok(resp.status(StatusCode::RANGE_NOT_SATISFIABLE).finish()); @@ -331,8 +334,7 @@ impl Responder for NamedFile { let reader = ChunkedReadFile { size: length, offset: offset, - cpu_pool: self.cpu_pool - .unwrap_or_else(|| req.cpu_pool().clone()), + cpu_pool: self.cpu_pool.unwrap_or_else(|| req.cpu_pool().clone()), file: Some(self.file), fut: None, counter: 0, @@ -618,7 +620,8 @@ impl Handler for StaticFiles { if !self.accessible { Ok(self.default.handle(req)) } else { - let relpath = match req.match_info() + let relpath = match req + .match_info() .get("tail") .map(|tail| PathBuf::from_param(tail.trim_left_matches('/'))) { @@ -690,9 +693,7 @@ mod tests { "text/x-toml" ); assert_eq!( - resp.headers() - .get(header::CONTENT_DISPOSITION) - .unwrap(), + resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=Cargo.toml" ); } @@ -716,9 +717,7 @@ mod tests { "image/png" ); assert_eq!( - resp.headers() - .get(header::CONTENT_DISPOSITION) - .unwrap(), + resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=test.png" ); } @@ -742,9 +741,7 @@ mod tests { "application/octet-stream" ); assert_eq!( - resp.headers() - .get(header::CONTENT_DISPOSITION) - .unwrap(), + resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "attachment; filename=test.binary" ); } @@ -769,21 +766,20 @@ mod tests { "text/x-toml" ); assert_eq!( - resp.headers() - .get(header::CONTENT_DISPOSITION) - .unwrap(), + resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=Cargo.toml" ); assert_eq!(resp.status(), StatusCode::NOT_FOUND); } - + #[test] fn test_named_file_ranges_status_code() { let mut srv = test::TestServer::with_factory(|| { App::new().handler("test", StaticFiles::new(".").index_file("Cargo.toml")) }); - let request = srv.get() + let request = srv + .get() .uri(srv.url("/t%65st/Cargo.toml")) .header(header::RANGE, "bytes=10-20") .finish() @@ -796,26 +792,41 @@ mod tests { #[test] fn test_named_file_ranges_headers() { let mut srv = test::TestServer::with_factory(|| { - App::new().handler("test", StaticFiles::new(".").index_file("tests/test.binary")) + App::new().handler( + "test", + StaticFiles::new(".").index_file("tests/test.binary"), + ) }); - let request = srv.get() + let request = srv + .get() .uri(srv.url("/t%65st/tests/test.binary")) .header(header::RANGE, "bytes=10-20") .finish() .unwrap(); let response = srv.execute(request.send()).unwrap(); - let contentlength = response.headers().get(header::CONTENT_LENGTH).unwrap().to_str().unwrap(); + let contentlength = response + .headers() + .get(header::CONTENT_LENGTH) + .unwrap() + .to_str() + .unwrap(); assert_eq!(contentlength, "10"); - let request = srv.get() + let request = srv + .get() .uri(srv.url("/t%65st/tests/test.binary")) .header(header::RANGE, "bytes=10-20") .finish() .unwrap(); let response = srv.execute(request.send()).unwrap(); - let range = response.headers().get(header::RANGE).unwrap().to_str().unwrap(); + let range = response + .headers() + .get(header::RANGE) + .unwrap() + .to_str() + .unwrap(); assert_eq!(range, "bytes=10-20/100"); } @@ -841,7 +852,8 @@ mod tests { fn test_static_files() { let mut st = StaticFiles::new(".").show_files_listing(); st.accessible = false; - let resp = st.handle(HttpRequest::default()) + let resp = st + .handle(HttpRequest::default()) .respond_to(&HttpRequest::default()) .unwrap(); let resp = resp.as_msg(); @@ -849,7 +861,8 @@ mod tests { st.accessible = true; st.show_index = false; - let resp = st.handle(HttpRequest::default()) + let resp = st + .handle(HttpRequest::default()) .respond_to(&HttpRequest::default()) .unwrap(); let resp = resp.as_msg(); @@ -859,9 +872,7 @@ mod tests { req.match_info_mut().add("tail", ""); st.show_index = true; - let resp = st.handle(req) - .respond_to(&HttpRequest::default()) - .unwrap(); + let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap(); let resp = resp.as_msg(); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), @@ -877,9 +888,7 @@ mod tests { let mut req = HttpRequest::default(); req.match_info_mut().add("tail", "tests"); - let resp = st.handle(req) - .respond_to(&HttpRequest::default()) - .unwrap(); + let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap(); let resp = resp.as_msg(); assert_eq!(resp.status(), StatusCode::FOUND); assert_eq!( @@ -890,9 +899,7 @@ mod tests { let mut req = HttpRequest::default(); req.match_info_mut().add("tail", "tests/"); - let resp = st.handle(req) - .respond_to(&HttpRequest::default()) - .unwrap(); + let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap(); let resp = resp.as_msg(); assert_eq!(resp.status(), StatusCode::FOUND); assert_eq!( @@ -907,9 +914,7 @@ mod tests { let mut req = HttpRequest::default(); req.match_info_mut().add("tail", "tools/wsload"); - let resp = st.handle(req) - .respond_to(&HttpRequest::default()) - .unwrap(); + let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap(); let resp = resp.as_msg(); assert_eq!(resp.status(), StatusCode::FOUND); assert_eq!( @@ -984,7 +989,8 @@ mod tests { App::new().handler("test", StaticFiles::new(".").index_file("Cargo.toml")) }); - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test/%43argo.toml")) .finish() .unwrap(); diff --git a/src/handler.rs b/src/handler.rs index a10a6f9c9..759291a20 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -362,7 +362,8 @@ where self, req: &HttpRequest, ) -> Result, Error> { let req = req.clone(); - let fut = self.map_err(|e| e.into()) + let fut = self + .map_err(|e| e.into()) .then(move |r| match r.respond_to(&req) { Ok(reply) => match reply.into().into() { AsyncResultItem::Ok(resp) => ok(resp), @@ -397,10 +398,7 @@ where S: 'static, { pub fn new(h: H) -> Self { - WrapHandler { - h, - s: PhantomData, - } + WrapHandler { h, s: PhantomData } } } @@ -456,16 +454,16 @@ where S: 'static, { fn handle(&mut self, req: HttpRequest) -> AsyncResult { - let fut = (self.h)(req.clone()) - .map_err(|e| e.into()) - .then(move |r| match r.respond_to(&req) { + let fut = (self.h)(req.clone()).map_err(|e| e.into()).then(move |r| { + match r.respond_to(&req) { Ok(reply) => match reply.into().into() { AsyncResultItem::Ok(resp) => Either::A(ok(resp)), AsyncResultItem::Err(e) => Either::A(err(e)), AsyncResultItem::Future(fut) => Either::B(fut), }, Err(e) => Either::A(err(e)), - }); + } + }); AsyncResult::async(Box::new(fut)) } } diff --git a/src/header/shared/encoding.rs b/src/header/shared/encoding.rs index e4abe470c..64027d8a5 100644 --- a/src/header/shared/encoding.rs +++ b/src/header/shared/encoding.rs @@ -1,8 +1,9 @@ use std::fmt; use std::str; -pub use self::Encoding::{Brotli, Chunked, Compress, Deflate, EncodingExt, Gzip, - Identity, Trailers}; +pub use self::Encoding::{ + Brotli, Chunked, Compress, Deflate, EncodingExt, Gzip, Identity, Trailers, +}; /// A value to represent an encoding used in `Transfer-Encoding` /// or `Accept-Encoding` header. diff --git a/src/header/shared/entity.rs b/src/header/shared/entity.rs index 347c4c028..a83ce1956 100644 --- a/src/header/shared/entity.rs +++ b/src/header/shared/entity.rs @@ -132,7 +132,8 @@ impl FromStr for EntityTag { return Err(::error::ParseError::Header); } // The etag is weak if its first char is not a DQUOTE. - if slice.len() >= 2 && slice.starts_with('"') + if slice.len() >= 2 + && slice.starts_with('"') && check_slice_validity(&slice[1..length - 1]) { // No need to check if the last char is a DQUOTE, @@ -141,7 +142,8 @@ impl FromStr for EntityTag { weak: false, tag: slice[1..length - 1].to_owned(), }); - } else if slice.len() >= 4 && slice.starts_with("W/\"") + } else if slice.len() >= 4 + && slice.starts_with("W/\"") && check_slice_validity(&slice[3..length - 1]) { return Ok(EntityTag { @@ -213,10 +215,7 @@ mod tests { format!("{}", EntityTag::strong("foobar".to_owned())), "\"foobar\"" ); - assert_eq!( - format!("{}", EntityTag::strong("".to_owned())), - "\"\"" - ); + assert_eq!(format!("{}", EntityTag::strong("".to_owned())), "\"\""); assert_eq!( format!("{}", EntityTag::weak("weak-etag".to_owned())), "W/\"weak-etag\"" @@ -225,10 +224,7 @@ mod tests { format!("{}", EntityTag::weak("\u{0065}".to_owned())), "W/\"\x65\"" ); - assert_eq!( - format!("{}", EntityTag::weak("".to_owned())), - "W/\"\"" - ); + assert_eq!(format!("{}", EntityTag::weak("".to_owned())), "W/\"\""); } #[test] diff --git a/src/header/shared/httpdate.rs b/src/header/shared/httpdate.rs index 5de1e3f9f..60075e1a2 100644 --- a/src/header/shared/httpdate.rs +++ b/src/header/shared/httpdate.rs @@ -105,9 +105,7 @@ mod tests { #[test] fn test_date() { assert_eq!( - "Sun, 07 Nov 1994 08:48:37 GMT" - .parse::() - .unwrap(), + "Sun, 07 Nov 1994 08:48:37 GMT".parse::().unwrap(), NOV_07 ); assert_eq!( @@ -117,9 +115,7 @@ mod tests { NOV_07 ); assert_eq!( - "Sun Nov 7 08:48:37 1994" - .parse::() - .unwrap(), + "Sun Nov 7 08:48:37 1994".parse::().unwrap(), NOV_07 ); assert!("this-is-no-date".parse::().is_err()); diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs index 5f1e5977a..a9488e81f 100644 --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -63,11 +63,7 @@ impl fmt::Display for QualityItem { match self.quality.0 { 1000 => Ok(()), 0 => f.write_str("; q=0"), - x => write!( - f, - "; q=0.{}", - format!("{:03}", x).trim_right_matches('0') - ), + x => write!(f, "; q=0.{}", format!("{:03}", x).trim_right_matches('0')), } } } @@ -295,10 +291,6 @@ mod tests { #[test] fn test_fuzzing_bugs() { assert!("99999;".parse::>().is_err()); - assert!( - "\x0d;;;=\u{d6aa}==" - .parse::>() - .is_err() - ) + assert!("\x0d;;;=\u{d6aa}==".parse::>().is_err()) } } diff --git a/src/helpers.rs b/src/helpers.rs index 9db0e8638..c94c24d90 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -190,16 +190,8 @@ mod tests { // trailing slashes let params = vec![ ("/resource1", "", StatusCode::OK), - ( - "/resource1/", - "/resource1", - StatusCode::MOVED_PERMANENTLY, - ), - ( - "/resource2", - "/resource2/", - StatusCode::MOVED_PERMANENTLY, - ), + ("/resource1/", "/resource1", StatusCode::MOVED_PERMANENTLY), + ("/resource2", "/resource2/", StatusCode::MOVED_PERMANENTLY), ("/resource2/", "", StatusCode::OK), ("/resource1?p1=1&p2=2", "", StatusCode::OK), ( @@ -222,11 +214,7 @@ mod tests { if !target.is_empty() { assert_eq!( target, - r.headers() - .get(header::LOCATION) - .unwrap() - .to_str() - .unwrap() + r.headers().get(header::LOCATION).unwrap().to_str().unwrap() ); } } @@ -276,16 +264,8 @@ mod tests { // trailing slashes let params = vec![ ("/resource1/a/b", "", StatusCode::OK), - ( - "/resource1/", - "/resource1", - StatusCode::MOVED_PERMANENTLY, - ), - ( - "/resource1//", - "/resource1", - StatusCode::MOVED_PERMANENTLY, - ), + ("/resource1/", "/resource1", StatusCode::MOVED_PERMANENTLY), + ("/resource1//", "/resource1", StatusCode::MOVED_PERMANENTLY), ( "//resource1//a//b", "/resource1/a/b", @@ -356,11 +336,7 @@ mod tests { if !target.is_empty() { assert_eq!( target, - r.headers() - .get(header::LOCATION) - .unwrap() - .to_str() - .unwrap() + r.headers().get(header::LOCATION).unwrap().to_str().unwrap() ); } } @@ -540,11 +516,7 @@ mod tests { if !target.is_empty() { assert_eq!( target, - r.headers() - .get(header::LOCATION) - .unwrap() - .to_str() - .unwrap() + r.headers().get(header::LOCATION).unwrap().to_str().unwrap() ); } } diff --git a/src/httpcodes.rs b/src/httpcodes.rs index 6d1c5ed15..2933cf175 100644 --- a/src/httpcodes.rs +++ b/src/httpcodes.rs @@ -55,10 +55,7 @@ impl HttpResponse { STATIC_RESP!(PreconditionFailed, StatusCode::PRECONDITION_FAILED); STATIC_RESP!(PayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE); STATIC_RESP!(UriTooLong, StatusCode::URI_TOO_LONG); - STATIC_RESP!( - UnsupportedMediaType, - StatusCode::UNSUPPORTED_MEDIA_TYPE - ); + STATIC_RESP!(UnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE); STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE); STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED); @@ -67,14 +64,8 @@ impl HttpResponse { STATIC_RESP!(BadGateway, StatusCode::BAD_GATEWAY); STATIC_RESP!(ServiceUnavailable, StatusCode::SERVICE_UNAVAILABLE); STATIC_RESP!(GatewayTimeout, StatusCode::GATEWAY_TIMEOUT); - STATIC_RESP!( - VersionNotSupported, - StatusCode::HTTP_VERSION_NOT_SUPPORTED - ); - STATIC_RESP!( - VariantAlsoNegotiates, - StatusCode::VARIANT_ALSO_NEGOTIATES - ); + STATIC_RESP!(VersionNotSupported, StatusCode::HTTP_VERSION_NOT_SUPPORTED); + STATIC_RESP!(VariantAlsoNegotiates, StatusCode::VARIANT_ALSO_NEGOTIATES); STATIC_RESP!(InsufficientStorage, StatusCode::INSUFFICIENT_STORAGE); STATIC_RESP!(LoopDetected, StatusCode::LOOP_DETECTED); } diff --git a/src/httpmessage.rs b/src/httpmessage.rs index d80ed7039..2f23e6536 100644 --- a/src/httpmessage.rs +++ b/src/httpmessage.rs @@ -11,7 +11,9 @@ use serde::de::DeserializeOwned; use serde_urlencoded; use std::str; -use error::{ContentTypeError, HttpRangeError, ParseError, PayloadError, UrlencodedError}; +use error::{ + ContentTypeError, HttpRangeError, ParseError, PayloadError, UrlencodedError, +}; use header::Header; use json::JsonBody; use multipart::Multipart; @@ -96,10 +98,8 @@ pub trait HttpMessage { /// `size` is full size of response (file). fn range(&self, size: u64) -> Result, HttpRangeError> { if let Some(range) = self.headers().get(header::RANGE) { - HttpRange::parse( - unsafe { str::from_utf8_unchecked(range.as_bytes()) }, - size, - ).map_err(|e| e.into()) + HttpRange::parse(unsafe { str::from_utf8_unchecked(range.as_bytes()) }, size) + .map_err(|e| e.into()) } else { Ok(Vec::new()) } @@ -385,12 +385,12 @@ where if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" { return Err(UrlencodedError::ContentType); } - let encoding = req.encoding() - .map_err(|_| UrlencodedError::ContentType)?; + let encoding = req.encoding().map_err(|_| UrlencodedError::ContentType)?; // future let limit = self.limit; - let fut = req.from_err() + let fut = req + .from_err() .fold(BytesMut::new(), move |mut body, chunk| { if (body.len() + chunk.len()) > limit { Err(UrlencodedError::Overflow) @@ -488,10 +488,7 @@ mod tests { #[test] fn test_encoding_error() { let req = TestRequest::with_header("content-type", "applicatjson").finish(); - assert_eq!( - Some(ContentTypeError::ParseError), - req.encoding().err() - ); + assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err()); let req = TestRequest::with_header( "content-type", @@ -664,8 +661,7 @@ mod tests { } let mut req = HttpRequest::default(); - req.payload_mut() - .unread_data(Bytes::from_static(b"test")); + req.payload_mut().unread_data(Bytes::from_static(b"test")); match req.body().poll().ok().unwrap() { Async::Ready(bytes) => assert_eq!(bytes, Bytes::from_static(b"test")), _ => unreachable!("error"), diff --git a/src/httprequest.rs b/src/httprequest.rs index 0c3ee31de..a21c92298 100644 --- a/src/httprequest.rs +++ b/src/httprequest.rs @@ -106,10 +106,7 @@ impl HttpRequest<()> { /// Construct a new Request. #[inline] pub fn new( - method: Method, - uri: Uri, - version: Version, - headers: HeaderMap, + method: Method, uri: Uri, version: Version, headers: HeaderMap, payload: Option, ) -> HttpRequest { let url = InnerUrl::new(uri); @@ -304,9 +301,7 @@ impl HttpRequest { /// } /// ``` pub fn url_for( - &self, - name: &str, - elements: U, + &self, name: &str, elements: U, ) -> Result where U: IntoIterator, diff --git a/src/httpresponse.rs b/src/httpresponse.rs index a71f53fbb..428ca0148 100644 --- a/src/httpresponse.rs +++ b/src/httpresponse.rs @@ -600,8 +600,7 @@ impl HttpResponseBuilder { #[inline] #[cfg_attr(feature = "cargo-clippy", allow(borrowed_box))] fn parts<'a>( - parts: &'a mut Option>, - err: &Option, + parts: &'a mut Option>, err: &Option, ) -> Option<&'a mut Box> { if err.is_some() { return None; @@ -648,7 +647,8 @@ impl Responder for &'static str { type Error = Error; fn respond_to(self, req: &HttpRequest) -> Result { - Ok(req.build_response(StatusCode::OK) + Ok(req + .build_response(StatusCode::OK) .content_type("text/plain; charset=utf-8") .body(self)) } @@ -667,7 +667,8 @@ impl Responder for &'static [u8] { type Error = Error; fn respond_to(self, req: &HttpRequest) -> Result { - Ok(req.build_response(StatusCode::OK) + Ok(req + .build_response(StatusCode::OK) .content_type("application/octet-stream") .body(self)) } @@ -686,7 +687,8 @@ impl Responder for String { type Error = Error; fn respond_to(self, req: &HttpRequest) -> Result { - Ok(req.build_response(StatusCode::OK) + Ok(req + .build_response(StatusCode::OK) .content_type("text/plain; charset=utf-8") .body(self)) } @@ -705,7 +707,8 @@ impl<'a> Responder for &'a String { type Error = Error; fn respond_to(self, req: &HttpRequest) -> Result { - Ok(req.build_response(StatusCode::OK) + Ok(req + .build_response(StatusCode::OK) .content_type("text/plain; charset=utf-8") .body(self)) } @@ -724,7 +727,8 @@ impl Responder for Bytes { type Error = Error; fn respond_to(self, req: &HttpRequest) -> Result { - Ok(req.build_response(StatusCode::OK) + Ok(req + .build_response(StatusCode::OK) .content_type("application/octet-stream") .body(self)) } @@ -743,7 +747,8 @@ impl Responder for BytesMut { type Error = Error; fn respond_to(self, req: &HttpRequest) -> Result { - Ok(req.build_response(StatusCode::OK) + Ok(req + .build_response(StatusCode::OK) .content_type("application/octet-stream") .body(self)) } @@ -823,8 +828,7 @@ impl HttpResponsePool { #[inline] pub fn get_builder( - pool: &Rc>, - status: StatusCode, + pool: &Rc>, status: StatusCode, ) -> HttpResponseBuilder { let p = unsafe { &mut *pool.as_ref().get() }; if let Some(mut msg) = p.0.pop_front() { @@ -848,9 +852,7 @@ impl HttpResponsePool { #[inline] pub fn get_response( - pool: &Rc>, - status: StatusCode, - body: Body, + pool: &Rc>, status: StatusCode, body: Body, ) -> HttpResponse { let p = unsafe { &mut *pool.as_ref().get() }; if let Some(mut msg) = p.0.pop_front() { @@ -876,8 +878,7 @@ impl HttpResponsePool { #[inline(always)] #[cfg_attr(feature = "cargo-clippy", allow(boxed_local, inline_always))] fn release( - pool: &Rc>, - mut inner: Box, + pool: &Rc>, mut inner: Box, ) { let pool = unsafe { &mut *pool.as_ref().get() }; if pool.0.len() < 128 { @@ -942,7 +943,8 @@ mod tests { .del_cookie(&cookies[0]) .finish(); - let mut val: Vec<_> = resp.headers() + let mut val: Vec<_> = resp + .headers() .get_all("Set-Cookie") .iter() .map(|v| v.to_str().unwrap().to_owned()) diff --git a/src/info.rs b/src/info.rs index 762885396..05d35f470 100644 --- a/src/info.rs +++ b/src/info.rs @@ -53,7 +53,8 @@ impl<'a> ConnectionInfo<'a> { // scheme if scheme.is_none() { - if let Some(h) = req.headers() + if let Some(h) = req + .headers() .get(HeaderName::from_str(X_FORWARDED_PROTO).unwrap()) { if let Ok(h) = h.to_str() { @@ -74,7 +75,8 @@ impl<'a> ConnectionInfo<'a> { // host if host.is_none() { - if let Some(h) = req.headers() + if let Some(h) = req + .headers() .get(HeaderName::from_str(X_FORWARDED_HOST).unwrap()) { if let Ok(h) = h.to_str() { @@ -98,7 +100,8 @@ impl<'a> ConnectionInfo<'a> { // remote addr if remote.is_none() { - if let Some(h) = req.headers() + if let Some(h) = req + .headers() .get(HeaderName::from_str(X_FORWARDED_FOR).unwrap()) { if let Ok(h) = h.to_str() { @@ -189,10 +192,8 @@ mod tests { assert_eq!(info.remote(), Some("192.0.2.60")); let mut req = HttpRequest::default(); - req.headers_mut().insert( - header::HOST, - HeaderValue::from_static("rust-lang.org"), - ); + req.headers_mut() + .insert(header::HOST, HeaderValue::from_static("rust-lang.org")); let info = ConnectionInfo::new(&req); assert_eq!(info.scheme(), "http"); diff --git a/src/json.rs b/src/json.rs index 6711de391..e48c27ef4 100644 --- a/src/json.rs +++ b/src/json.rs @@ -121,7 +121,8 @@ impl Responder for Json { fn respond_to(self, req: &HttpRequest) -> Result { let body = serde_json::to_string(&self.0)?; - Ok(req.build_response(StatusCode::OK) + Ok(req + .build_response(StatusCode::OK) .content_type("application/json") .body(body)) } @@ -295,7 +296,8 @@ where } let limit = self.limit; - let fut = req.from_err() + let fut = req + .from_err() .fold(BytesMut::new(), move |mut body, chunk| { if (body.len() + chunk.len()) > limit { Err(JsonPayloadError::Overflow) @@ -362,10 +364,7 @@ mod tests { fn test_json_body() { let req = HttpRequest::default(); let mut json = req.json::(); - assert_eq!( - json.poll().err().unwrap(), - JsonPayloadError::ContentType - ); + assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType); let mut req = HttpRequest::default(); req.headers_mut().insert( @@ -373,10 +372,7 @@ mod tests { header::HeaderValue::from_static("application/text"), ); let mut json = req.json::(); - assert_eq!( - json.poll().err().unwrap(), - JsonPayloadError::ContentType - ); + assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType); let mut req = HttpRequest::default(); req.headers_mut().insert( diff --git a/src/middleware/cors.rs b/src/middleware/cors.rs index 5b5036300..a7b0110f8 100644 --- a/src/middleware/cors.rs +++ b/src/middleware/cors.rs @@ -275,9 +275,7 @@ impl Cors { /// `ResourceHandler::middleware()` method, but in that case *Cors* /// middleware wont be able to handle *OPTIONS* requests. pub fn register(self, resource: &mut ResourceHandler) { - resource - .method(Method::OPTIONS) - .h(|_| HttpResponse::Ok()); + resource.method(Method::OPTIONS).h(|_| HttpResponse::Ok()); resource.middleware(self); } @@ -304,12 +302,11 @@ impl Cors { fn validate_allowed_method( &self, req: &mut HttpRequest, ) -> Result<(), CorsError> { - if let Some(hdr) = req.headers() - .get(header::ACCESS_CONTROL_REQUEST_METHOD) - { + if let Some(hdr) = req.headers().get(header::ACCESS_CONTROL_REQUEST_METHOD) { if let Ok(meth) = hdr.to_str() { if let Ok(method) = Method::try_from(meth) { - return self.inner + return self + .inner .methods .get(&method) .and_then(|_| Some(())) @@ -328,8 +325,8 @@ impl Cors { match self.inner.headers { AllOrSome::All => Ok(()), AllOrSome::Some(ref allowed_headers) => { - if let Some(hdr) = req.headers() - .get(header::ACCESS_CONTROL_REQUEST_HEADERS) + if let Some(hdr) = + req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS) { if let Ok(headers) = hdr.to_str() { let mut hdrs = HashSet::new(); @@ -371,8 +368,8 @@ impl Middleware for Cors { .as_str()[1..], ).unwrap(), ) - } else if let Some(hdr) = req.headers() - .get(header::ACCESS_CONTROL_REQUEST_HEADERS) + } else if let Some(hdr) = + req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS) { Some(hdr.clone()) } else { @@ -413,7 +410,8 @@ impl Middleware for Cors { }) .header( header::ACCESS_CONTROL_ALLOW_METHODS, - &self.inner + &self + .inner .methods .iter() .fold(String::new(), |s, v| s + "," + v.as_str()) @@ -866,7 +864,8 @@ impl CorsBuilder { } let cors = self.construct(); - let mut app = self.app + let mut app = self + .app .take() .expect("CorsBuilder has to be constructed with Cors::for_app(app)"); @@ -1094,9 +1093,8 @@ mod tests { resp.headers().get(header::VARY).unwrap().as_bytes() ); - let resp: HttpResponse = HttpResponse::Ok() - .header(header::VARY, "Accept") - .finish(); + let resp: HttpResponse = + HttpResponse::Ok().header(header::VARY, "Accept").finish(); let resp = cors.response(&mut req, resp).unwrap().response(); assert_eq!( &b"Accept, Origin"[..], @@ -1133,7 +1131,8 @@ mod tests { let response = srv.execute(request.send()).unwrap(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test")) .header("ORIGIN", "https://www.example.com") .finish() diff --git a/src/middleware/defaultheaders.rs b/src/middleware/defaultheaders.rs index bab5ff0bd..ebe3ea1d4 100644 --- a/src/middleware/defaultheaders.rs +++ b/src/middleware/defaultheaders.rs @@ -112,9 +112,7 @@ mod tests { }; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); - let resp = HttpResponse::Ok() - .header(CONTENT_TYPE, "0002") - .finish(); + let resp = HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish(); let resp = match mw.response(&mut req, resp) { Ok(Response::Done(resp)) => resp, _ => panic!(), diff --git a/src/middleware/identity.rs b/src/middleware/identity.rs index ce18e858a..36317ebcf 100644 --- a/src/middleware/identity.rs +++ b/src/middleware/identity.rs @@ -179,7 +179,8 @@ impl> Middleware for IdentityService { fn start(&self, req: &mut HttpRequest) -> Result { let mut req = req.clone(); - let fut = self.backend + let fut = self + .backend .from_request(&mut req) .then(move |res| match res { Ok(id) => { diff --git a/src/middleware/logger.rs b/src/middleware/logger.rs index 086c232cc..985a5dfe1 100644 --- a/src/middleware/logger.rs +++ b/src/middleware/logger.rs @@ -376,9 +376,7 @@ mod tests { headers, None, ); - let resp = HttpResponse::build(StatusCode::OK) - .force_close() - .finish(); + let resp = HttpResponse::build(StatusCode::OK).force_close().finish(); let entry_time = time::now(); let render = |fmt: &mut Formatter| { @@ -399,9 +397,7 @@ mod tests { HeaderMap::new(), None, ); - let resp = HttpResponse::build(StatusCode::OK) - .force_close() - .finish(); + let resp = HttpResponse::build(StatusCode::OK).force_close().finish(); let entry_time = time::now(); let render = |fmt: &mut Formatter| { diff --git a/src/middleware/session.rs b/src/middleware/session.rs index 6225bc34f..ba385d83e 100644 --- a/src/middleware/session.rs +++ b/src/middleware/session.rs @@ -267,9 +267,7 @@ impl> Middleware for SessionStorage { } fn response( - &self, - req: &mut HttpRequest, - resp: HttpResponse, + &self, req: &mut HttpRequest, resp: HttpResponse, ) -> Result { if let Some(s_box) = req.extensions_mut().remove::>() { s_box.0.borrow_mut().write(resp) @@ -385,9 +383,7 @@ impl CookieSessionInner { } fn set_cookie( - &self, - resp: &mut HttpResponse, - state: &HashMap, + &self, resp: &mut HttpResponse, state: &HashMap, ) -> Result<()> { let value = serde_json::to_string(&state).map_err(CookieSessionError::Serialize)?; diff --git a/src/multipart.rs b/src/multipart.rs index 056332b53..365a101c1 100644 --- a/src/multipart.rs +++ b/src/multipart.rs @@ -122,11 +122,7 @@ where if let Some(err) = self.error.take() { Err(err) } else if self.safety.current() { - self.inner - .as_mut() - .unwrap() - .borrow_mut() - .poll(&self.safety) + self.inner.as_mut().unwrap().borrow_mut().poll(&self.safety) } else { Ok(Async::NotReady) } @@ -175,11 +171,13 @@ where Async::NotReady => Ok(Async::NotReady), Async::Ready(None) => Err(MultipartError::Incomplete), Async::Ready(Some(chunk)) => { - if chunk.len() == boundary.len() + 4 && &chunk[..2] == b"--" + if chunk.len() == boundary.len() + 4 + && &chunk[..2] == b"--" && &chunk[2..boundary.len() + 2] == boundary.as_bytes() { Ok(Async::Ready(false)) - } else if chunk.len() == boundary.len() + 6 && &chunk[..2] == b"--" + } else if chunk.len() == boundary.len() + 6 + && &chunk[..2] == b"--" && &chunk[2..boundary.len() + 2] == boundary.as_bytes() && &chunk[boundary.len() + 2..boundary.len() + 4] == b"--" { @@ -514,7 +512,8 @@ where Async::NotReady => Ok(Async::NotReady), Async::Ready(None) => Err(MultipartError::Incomplete), Async::Ready(Some(chunk)) => { - if &chunk[..2] == b"\r\n" && &chunk[2..4] == b"--" + if &chunk[..2] == b"\r\n" + && &chunk[2..4] == b"--" && &chunk[4..] == boundary.as_bytes() { payload.unread_data(chunk); diff --git a/src/payload.rs b/src/payload.rs index a394c1069..dd0b197b4 100644 --- a/src/payload.rs +++ b/src/payload.rs @@ -671,10 +671,7 @@ mod tests { let (mut sender, payload) = Payload::new(false); let mut payload = PayloadHelper::new(payload); - assert_eq!( - Async::NotReady, - payload.read_until(b"ne").ok().unwrap() - ); + assert_eq!(Async::NotReady, payload.read_until(b"ne").ok().unwrap()); sender.feed_data(Bytes::from("line1")); sender.feed_data(Bytes::from("line2")); diff --git a/src/pipeline.rs b/src/pipeline.rs index 82ec45a74..f5c338e6b 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -29,9 +29,7 @@ pub(crate) trait PipelineHandler { fn encoding(&self) -> ContentEncoding; fn handle( - &mut self, - req: HttpRequest, - htype: HandlerType, + &mut self, req: HttpRequest, htype: HandlerType, ) -> AsyncResult; } @@ -122,10 +120,8 @@ impl PipelineInfo { impl> Pipeline { pub fn new( - req: HttpRequest, - mws: Rc>>>, - handler: Rc>, - htype: HandlerType, + req: HttpRequest, mws: Rc>>>, + handler: Rc>, htype: HandlerType, ) -> Pipeline { let mut info = PipelineInfo { mws, @@ -243,9 +239,7 @@ struct StartMiddlewares { impl> StartMiddlewares { fn init( - info: &mut PipelineInfo, - hnd: Rc>, - htype: HandlerType, + info: &mut PipelineInfo, hnd: Rc>, htype: HandlerType, ) -> PipelineState { // execute middlewares, we need this stage because middlewares could be // non-async and we can move to next state immediately @@ -322,8 +316,7 @@ struct WaitingResponse { impl WaitingResponse { #[inline] fn init( - info: &mut PipelineInfo, - reply: AsyncResult, + info: &mut PipelineInfo, reply: AsyncResult, ) -> PipelineState { match reply.into() { AsyncResultItem::Err(err) => RunMiddlewares::init(info, err.into()), @@ -475,9 +468,7 @@ impl ProcessResponse { } fn poll_io( - mut self, - io: &mut Writer, - info: &mut PipelineInfo, + mut self, io: &mut Writer, info: &mut PipelineInfo, ) -> Result, PipelineState> { loop { if self.drain.is_none() && self.running != RunningState::Paused { diff --git a/src/pred.rs b/src/pred.rs index 34792e366..90a0d61f6 100644 --- a/src/pred.rs +++ b/src/pred.rs @@ -181,11 +181,7 @@ pub fn Header( } #[doc(hidden)] -pub struct HeaderPredicate( - header::HeaderName, - header::HeaderValue, - PhantomData, -); +pub struct HeaderPredicate(header::HeaderName, header::HeaderValue, PhantomData); impl Predicate for HeaderPredicate { fn check(&self, req: &mut HttpRequest) -> bool { diff --git a/src/resource.rs b/src/resource.rs index e52760f4e..7b1a7502d 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -134,10 +134,7 @@ impl ResourceHandler { /// ``` pub fn method(&mut self, method: Method) -> &mut Route { self.routes.push(Route::default()); - self.routes - .last_mut() - .unwrap() - .filter(pred::Method(method)) + self.routes.last_mut().unwrap().filter(pred::Method(method)) } /// Register a new route and add handler object. diff --git a/src/route.rs b/src/route.rs index b109fd609..ff19db802 100644 --- a/src/route.rs +++ b/src/route.rs @@ -55,9 +55,7 @@ impl Route { #[inline] pub(crate) fn compose( - &mut self, - req: HttpRequest, - mws: Rc>>>, + &mut self, req: HttpRequest, mws: Rc>>>, ) -> AsyncResult { AsyncResult::async(Box::new(Compose::new(req, mws, self.handler.clone()))) } @@ -248,8 +246,7 @@ impl Route { /// } /// ``` pub fn with2( - &mut self, - handler: F, + &mut self, handler: F, ) -> (ExtractorConfig, ExtractorConfig) where F: Fn(T1, T2) -> R + 'static, @@ -270,8 +267,7 @@ impl Route { #[doc(hidden)] /// Set handler function, use request extractor for all parameters. pub fn with3( - &mut self, - handler: F, + &mut self, handler: F, ) -> ( ExtractorConfig, ExtractorConfig, @@ -368,9 +364,7 @@ impl ComposeState { impl Compose { fn new( - req: HttpRequest, - mws: Rc>>>, - handler: InnerHandler, + req: HttpRequest, mws: Rc>>>, handler: InnerHandler, ) -> Self { let mut info = ComposeInfo { count: 0, @@ -485,8 +479,7 @@ struct WaitingResponse { impl WaitingResponse { #[inline] fn init( - info: &mut ComposeInfo, - reply: AsyncResult, + info: &mut ComposeInfo, reply: AsyncResult, ) -> ComposeState { match reply.into() { AsyncResultItem::Err(err) => RunMiddlewares::init(info, err.into()), diff --git a/src/router.rs b/src/router.rs index 1e7126b63..44fde0a40 100644 --- a/src/router.rs +++ b/src/router.rs @@ -216,7 +216,8 @@ impl Resource { Ok(re) => re, Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err), }; - let names = re.capture_names() + let names = re + .capture_names() .filter_map(|name| name.map(|name| name.to_owned())) .collect(); PatternType::Dynamic(re, names, len) @@ -440,10 +441,7 @@ mod tests { #[test] fn test_recognizer() { let routes = vec![ - ( - Resource::new("", "/name"), - Some(ResourceHandler::default()), - ), + (Resource::new("", "/name"), Some(ResourceHandler::default())), ( Resource::new("", "/name/{val}"), Some(ResourceHandler::default()), @@ -530,10 +528,7 @@ mod tests { #[test] fn test_recognizer_with_prefix() { let routes = vec![ - ( - Resource::new("", "/name"), - Some(ResourceHandler::default()), - ), + (Resource::new("", "/name"), Some(ResourceHandler::default())), ( Resource::new("", "/name/{val}"), Some(ResourceHandler::default()), @@ -554,10 +549,7 @@ mod tests { // same patterns let routes = vec![ - ( - Resource::new("", "/name"), - Some(ResourceHandler::default()), - ), + (Resource::new("", "/name"), Some(ResourceHandler::default())), ( Resource::new("", "/name/{val}"), Some(ResourceHandler::default()), diff --git a/src/scope.rs b/src/scope.rs index 00bcadad9..7cf9c6463 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -459,8 +459,7 @@ impl ComposeState { impl Compose { fn new( - req: HttpRequest, - mws: Rc>>>, + req: HttpRequest, mws: Rc>>>, resource: Rc>>, default: Option>>>, ) -> Self { @@ -585,8 +584,7 @@ struct WaitingResponse { impl WaitingResponse { #[inline] fn init( - info: &mut ComposeInfo, - reply: AsyncResult, + info: &mut ComposeInfo, reply: AsyncResult, ) -> ComposeState { match reply.into() { AsyncResultItem::Ok(resp) => RunMiddlewares::init(info, resp), diff --git a/src/server/channel.rs b/src/server/channel.rs index 9c30fe01c..34f6733c0 100644 --- a/src/server/channel.rs +++ b/src/server/channel.rs @@ -38,9 +38,7 @@ where H: HttpHandler + 'static, { pub(crate) fn new( - settings: Rc>, - mut io: T, - peer: Option, + settings: Rc>, mut io: T, peer: Option, http2: bool, ) -> HttpChannel { settings.add_channel(); diff --git a/src/server/encoding.rs b/src/server/encoding.rs index 07438b50b..17209041b 100644 --- a/src/server/encoding.rs +++ b/src/server/encoding.rs @@ -380,9 +380,7 @@ impl ContentEncoder { } pub fn for_server( - buf: SharedBytes, - req: &HttpInnerMessage, - resp: &mut HttpResponse, + buf: SharedBytes, req: &HttpInnerMessage, resp: &mut HttpResponse, response_encoding: ContentEncoding, ) -> ContentEncoder { let version = resp.version().unwrap_or_else(|| req.version); @@ -522,9 +520,7 @@ impl ContentEncoder { } fn streaming_encoding( - buf: SharedBytes, - version: Version, - resp: &mut HttpResponse, + buf: SharedBytes, version: Version, resp: &mut HttpResponse, ) -> TransferEncoding { match resp.chunked() { Some(true) => { @@ -867,7 +863,8 @@ impl AcceptEncoding { /// Parse a raw Accept-Encoding header value into an ordered list. pub fn parse(raw: &str) -> ContentEncoding { - let mut encodings: Vec<_> = raw.replace(' ', "") + let mut encodings: Vec<_> = raw + .replace(' ', "") .split(',') .map(|l| AcceptEncoding::new(l)) .collect(); diff --git a/src/server/h1.rs b/src/server/h1.rs index 46ec3473e..491c667c3 100644 --- a/src/server/h1.rs +++ b/src/server/h1.rs @@ -67,9 +67,7 @@ where H: HttpHandler + 'static, { pub fn new( - settings: Rc>, - stream: T, - addr: Option, + settings: Rc>, stream: T, addr: Option, buf: BytesMut, ) -> Self { let bytes = settings.get_shared_bytes(); @@ -765,7 +763,8 @@ mod tests { let msg = reader.decode(&mut buf, &settings).unwrap().unwrap(); let req = HttpRequest::from_message(msg.message()); - let val: Vec<_> = req.headers() + let val: Vec<_> = req + .headers() .get_all("Set-Cookie") .iter() .map(|v| v.to_str().unwrap().to_owned()) diff --git a/src/server/h1decoder.rs b/src/server/h1decoder.rs index 0d83bfbdd..976a079e4 100644 --- a/src/server/h1decoder.rs +++ b/src/server/h1decoder.rs @@ -46,9 +46,7 @@ impl H1Decoder { } pub fn decode( - &mut self, - src: &mut BytesMut, - settings: &WorkerSettings, + &mut self, src: &mut BytesMut, settings: &WorkerSettings, ) -> Result, DecoderError> { // read payload if self.decoder.is_some() { @@ -62,7 +60,8 @@ impl H1Decoder { } } - match self.parse_message(src, settings) + match self + .parse_message(src, settings) .map_err(DecoderError::Error)? { Async::Ready((msg, decoder)) => { @@ -84,9 +83,7 @@ impl H1Decoder { } fn parse_message( - &self, - buf: &mut BytesMut, - settings: &WorkerSettings, + &self, buf: &mut BytesMut, settings: &WorkerSettings, ) -> Poll<(SharedHttpInnerMessage, Option), ParseError> { // Parse http message let mut has_upgrade = false; @@ -348,10 +345,7 @@ macro_rules! byte ( impl ChunkedState { fn step( - &self, - body: &mut BytesMut, - size: &mut u64, - buf: &mut Option, + &self, body: &mut BytesMut, size: &mut u64, buf: &mut Option, ) -> Poll { use self::ChunkedState::*; match *self { @@ -414,8 +408,7 @@ impl ChunkedState { } } fn read_size_lf( - rdr: &mut BytesMut, - size: &mut u64, + rdr: &mut BytesMut, size: &mut u64, ) -> Poll { match byte!(rdr) { b'\n' if *size > 0 => Ok(Async::Ready(ChunkedState::Body)), @@ -428,9 +421,7 @@ impl ChunkedState { } fn read_body( - rdr: &mut BytesMut, - rem: &mut u64, - buf: &mut Option, + rdr: &mut BytesMut, rem: &mut u64, buf: &mut Option, ) -> Poll { trace!("Chunked read, remaining={:?}", rem); diff --git a/src/server/h1writer.rs b/src/server/h1writer.rs index ec5bfde18..5bb23dd98 100644 --- a/src/server/h1writer.rs +++ b/src/server/h1writer.rs @@ -42,9 +42,7 @@ pub(crate) struct H1Writer { impl H1Writer { pub fn new( - stream: T, - buf: SharedBytes, - settings: Rc>, + stream: T, buf: SharedBytes, settings: Rc>, ) -> H1Writer { H1Writer { flags: Flags::empty(), @@ -103,9 +101,7 @@ impl Writer for H1Writer { } fn start( - &mut self, - req: &mut HttpInnerMessage, - msg: &mut HttpResponse, + &mut self, req: &mut HttpInnerMessage, msg: &mut HttpResponse, encoding: ContentEncoding, ) -> io::Result { // prepare task diff --git a/src/server/h2.rs b/src/server/h2.rs index fc7824b22..c730ac409 100644 --- a/src/server/h2.rs +++ b/src/server/h2.rs @@ -133,7 +133,8 @@ where Err(err) => { error!("Unhandled error: {}", err); item.flags.insert( - EntryFlags::EOF | EntryFlags::ERROR + EntryFlags::EOF + | EntryFlags::ERROR | EntryFlags::WRITE_DONE, ); item.stream.reset(Reason::INTERNAL_ERROR); @@ -150,7 +151,8 @@ where } Err(err) => { item.flags.insert( - EntryFlags::ERROR | EntryFlags::WRITE_DONE + EntryFlags::ERROR + | EntryFlags::WRITE_DONE | EntryFlags::FINISHED, ); error!("Unhandled error: {}", err); @@ -248,7 +250,8 @@ where if not_ready { if self.tasks.is_empty() && self.flags.contains(Flags::DISCONNECTED) { - return conn.poll_close() + return conn + .poll_close() .map_err(|e| error!("Error during connection close: {}", e)); } else { return Ok(Async::NotReady); diff --git a/src/server/h2writer.rs b/src/server/h2writer.rs index 575d41765..a20d77593 100644 --- a/src/server/h2writer.rs +++ b/src/server/h2writer.rs @@ -120,7 +120,8 @@ impl Writer for H2Writer { resp.headers_mut().insert(key, value.clone()); } - match self.respond + match self + .respond .send_response(resp, self.flags.contains(Flags::EOF)) { Ok(stream) => self.stream = Some(stream), diff --git a/src/server/helpers.rs b/src/server/helpers.rs index c579ec07e..7f2f47346 100644 --- a/src/server/helpers.rs +++ b/src/server/helpers.rs @@ -251,63 +251,33 @@ mod tests { let mut bytes = BytesMut::new(); bytes.reserve(50); write_content_length(0, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 0\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 0\r\n"[..]); bytes.reserve(50); write_content_length(9, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 9\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 9\r\n"[..]); bytes.reserve(50); write_content_length(10, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 10\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 10\r\n"[..]); bytes.reserve(50); write_content_length(99, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 99\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 99\r\n"[..]); bytes.reserve(50); write_content_length(100, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 100\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 100\r\n"[..]); bytes.reserve(50); write_content_length(101, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 101\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 101\r\n"[..]); bytes.reserve(50); write_content_length(998, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 998\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 998\r\n"[..]); bytes.reserve(50); write_content_length(1000, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 1000\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 1000\r\n"[..]); bytes.reserve(50); write_content_length(1001, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 1001\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 1001\r\n"[..]); bytes.reserve(50); write_content_length(5909, &mut bytes); - assert_eq!( - bytes.take().freeze(), - b"\r\ncontent-length: 5909\r\n"[..] - ); + assert_eq!(bytes.take().freeze(), b"\r\ncontent-length: 5909\r\n"[..]); } } diff --git a/src/server/settings.rs b/src/server/settings.rs index f75033c1b..59917b87c 100644 --- a/src/server/settings.rs +++ b/src/server/settings.rs @@ -266,10 +266,7 @@ mod tests { #[test] fn test_date_len() { - assert_eq!( - DATE_VALUE_LENGTH, - "Sun, 06 Nov 1994 08:49:37 GMT".len() - ); + assert_eq!(DATE_VALUE_LENGTH, "Sun, 06 Nov 1994 08:49:37 GMT".len()); } #[test] diff --git a/src/server/srv.rs b/src/server/srv.rs index 30b7b4e45..22091e22b 100644 --- a/src/server/srv.rs +++ b/src/server/srv.rs @@ -218,7 +218,10 @@ where /// and the user should be presented with an enumeration of which /// socket requires which protocol. pub fn addrs_with_scheme(&self) -> Vec<(net::SocketAddr, &str)> { - self.sockets.iter().map(|s| (s.addr, s.tp.scheme())).collect() + self.sockets + .iter() + .map(|s| (s.addr, s.tp.scheme())) + .collect() } /// Use listener for accepting incoming connection requests @@ -254,7 +257,9 @@ where /// Use listener for accepting incoming tls connection requests /// /// This method sets alpn protocols to "h2" and "http/1.1" - pub fn listen_ssl(mut self, lst: net::TcpListener, mut builder: SslAcceptorBuilder) -> io::Result { + pub fn listen_ssl( + mut self, lst: net::TcpListener, mut builder: SslAcceptorBuilder, + ) -> io::Result { // alpn support if !self.no_http2 { configure_alpn(&mut builder)?; @@ -814,12 +819,9 @@ fn start_accept_thread( } // Start listening for incoming commands - if let Err(err) = poll.register( - ®, - CMD, - mio::Ready::readable(), - mio::PollOpt::edge(), - ) { + if let Err(err) = + poll.register(®, CMD, mio::Ready::readable(), mio::PollOpt::edge()) + { panic!("Can not register Registration: {}", err); } diff --git a/src/server/worker.rs b/src/server/worker.rs index a926a6c8f..012acd6e8 100644 --- a/src/server/worker.rs +++ b/src/server/worker.rs @@ -85,9 +85,7 @@ impl Worker { fn update_time(&self, ctx: &mut Context) { self.settings.update_date(); - ctx.run_later(time::Duration::new(1, 0), |slf, ctx| { - slf.update_time(ctx) - }); + ctx.run_later(time::Duration::new(1, 0), |slf, ctx| slf.update_time(ctx)); } fn shutdown_timeout( @@ -195,18 +193,17 @@ impl StreamHandlerType { let io = TcpStream::from_stream(io, hnd) .expect("failed to associate TCP stream"); - hnd.spawn( - TlsAcceptorExt::accept_async(acceptor, io).then(move |res| { - match res { - Ok(io) => Arbiter::handle() - .spawn(HttpChannel::new(h, io, peer, http2)), - Err(err) => { - trace!("Error during handling tls connection: {}", err) - } - }; - future::result(Ok(())) - }), - ); + hnd.spawn(TlsAcceptorExt::accept_async(acceptor, io).then(move |res| { + match res { + Ok(io) => { + Arbiter::handle().spawn(HttpChannel::new(h, io, peer, http2)) + } + Err(err) => { + trace!("Error during handling tls connection: {}", err) + } + }; + future::result(Ok(())) + })); } #[cfg(feature = "alpn")] StreamHandlerType::Alpn(ref acceptor) => { @@ -215,27 +212,25 @@ impl StreamHandlerType { let io = TcpStream::from_stream(io, hnd) .expect("failed to associate TCP stream"); - hnd.spawn( - SslAcceptorExt::accept_async(acceptor, io).then(move |res| { - match res { - Ok(io) => { - let http2 = if let Some(p) = - io.get_ref().ssl().selected_alpn_protocol() - { - p.len() == 2 && &p == b"h2" - } else { - false - }; - Arbiter::handle() - .spawn(HttpChannel::new(h, io, peer, http2)); - } - Err(err) => { - trace!("Error during handling tls connection: {}", err) - } - }; - future::result(Ok(())) - }), - ); + hnd.spawn(SslAcceptorExt::accept_async(acceptor, io).then(move |res| { + match res { + Ok(io) => { + let http2 = if let Some(p) = + io.get_ref().ssl().selected_alpn_protocol() + { + p.len() == 2 && &p == b"h2" + } else { + false + }; + Arbiter::handle() + .spawn(HttpChannel::new(h, io, peer, http2)); + } + Err(err) => { + trace!("Error during handling tls connection: {}", err) + } + }; + future::result(Ok(())) + })); } } } diff --git a/src/with.rs b/src/with.rs index fa4f4dc41..ea549e31d 100644 --- a/src/with.rs +++ b/src/with.rs @@ -794,15 +794,13 @@ where }; let hnd: &mut F = unsafe { &mut *self.hnd.get() }; - let item = match (*hnd)( - self.item1.take().unwrap(), - self.item2.take().unwrap(), - item, - ).respond_to(&self.req) - { - Ok(item) => item.into(), - Err(err) => return Err(err.into()), - }; + let item = + match (*hnd)(self.item1.take().unwrap(), self.item2.take().unwrap(), item) + .respond_to(&self.req) + { + Ok(item) => item.into(), + Err(err) => return Err(err.into()), + }; match item.into() { AsyncResultItem::Err(err) => return Err(err), diff --git a/src/ws/client.rs b/src/ws/client.rs index 92087efa5..1f35c1867 100644 --- a/src/ws/client.rs +++ b/src/ws/client.rs @@ -22,8 +22,10 @@ use header::IntoHeaderValue; use httpmessage::HttpMessage; use payload::PayloadHelper; -use client::{ClientConnector, ClientRequest, ClientRequestBuilder, ClientResponse, - HttpResponseParserError, SendRequest, SendRequestError}; +use client::{ + ClientConnector, ClientRequest, ClientRequestBuilder, ClientResponse, + HttpResponseParserError, SendRequest, SendRequestError, +}; use super::frame::Frame; use super::proto::{CloseReason, OpCode}; @@ -218,8 +220,7 @@ impl Client { self.request.upgrade(); self.request.set_header(header::UPGRADE, "websocket"); self.request.set_header(header::CONNECTION, "upgrade"); - self.request - .set_header(header::SEC_WEBSOCKET_VERSION, "13"); + self.request.set_header(header::SEC_WEBSOCKET_VERSION, "13"); self.request.with_connector(self.conn.clone()); if let Some(protocols) = self.protocols.take() { @@ -235,7 +236,9 @@ impl Client { return ClientHandshake::error(ClientError::InvalidUrl); } if let Some(scheme) = request.uri().scheme_part() { - if scheme != "http" && scheme != "https" && scheme != "ws" + if scheme != "http" + && scheme != "https" + && scheme != "ws" && scheme != "wss" { return ClientHandshake::error(ClientError::InvalidUrl); @@ -394,10 +397,7 @@ impl Future for ClientHandshake { encoded, key ); - return Err(ClientError::InvalidChallengeResponse( - encoded, - key.clone(), - )); + return Err(ClientError::InvalidChallengeResponse(encoded, key.clone())); } } else { trace!("Missing SEC-WEBSOCKET-ACCEPT header"); @@ -534,23 +534,13 @@ impl ClientWriter { /// Send ping frame #[inline] pub fn ping(&mut self, message: &str) { - self.write(Frame::message( - Vec::from(message), - OpCode::Ping, - true, - true, - )); + self.write(Frame::message(Vec::from(message), OpCode::Ping, true, true)); } /// Send pong frame #[inline] pub fn pong(&mut self, message: &str) { - self.write(Frame::message( - Vec::from(message), - OpCode::Pong, - true, - true, - )); + self.write(Frame::message(Vec::from(message), OpCode::Pong, true, true)); } /// Send close frame diff --git a/src/ws/context.rs b/src/ws/context.rs index 79c3aa356..226d93a14 100644 --- a/src/ws/context.rs +++ b/src/ws/context.rs @@ -5,8 +5,10 @@ use smallvec::SmallVec; use actix::dev::{ContextImpl, SyncEnvelope, ToEnvelope}; use actix::fut::ActorFuture; -use actix::{Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, - SpawnHandle, Syn, Unsync}; +use actix::{ + Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, SpawnHandle, + Syn, Unsync, +}; use body::{Binary, Body}; use context::{ActorHttpContext, Drain, Frame as ContextFrame}; @@ -64,7 +66,8 @@ where #[doc(hidden)] #[inline] fn waiting(&self) -> bool { - self.inner.waiting() || self.inner.state() == ActorState::Stopping + self.inner.waiting() + || self.inner.state() == ActorState::Stopping || self.inner.state() == ActorState::Stopped } diff --git a/src/ws/frame.rs b/src/ws/frame.rs index a5c02442d..8eaef72df 100644 --- a/src/ws/frame.rs +++ b/src/ws/frame.rs @@ -123,9 +123,7 @@ impl Frame { None }; - Ok(Async::Ready(Some(( - idx, finished, opcode, length, mask, - )))) + Ok(Async::Ready(Some((idx, finished, opcode, length, mask)))) } fn read_chunk_md( @@ -284,10 +282,7 @@ impl Frame { } else { None }; - Some(CloseReason { - code, - description, - }) + Some(CloseReason { code, description }) } else { None } diff --git a/src/ws/mod.rs b/src/ws/mod.rs index 9fb40dd97..7f72dea1d 100644 --- a/src/ws/mod.rs +++ b/src/ws/mod.rs @@ -62,7 +62,9 @@ mod frame; mod mask; mod proto; -pub use self::client::{Client, ClientError, ClientHandshake, ClientReader, ClientWriter}; +pub use self::client::{ + Client, ClientError, ClientHandshake, ClientReader, ClientWriter, +}; pub use self::context::WebsocketContext; pub use self::frame::Frame; pub use self::proto::{CloseCode, CloseReason, OpCode}; @@ -216,9 +218,7 @@ pub fn handshake( } // check supported version - if !req.headers() - .contains_key(header::SEC_WEBSOCKET_VERSION) - { + if !req.headers().contains_key(header::SEC_WEBSOCKET_VERSION) { return Err(HandshakeError::NoVersionHeader); } let supported_ver = { @@ -387,10 +387,7 @@ mod tests { ); let mut headers = HeaderMap::new(); - headers.insert( - header::UPGRADE, - header::HeaderValue::from_static("test"), - ); + headers.insert(header::UPGRADE, header::HeaderValue::from_static("test")); let req = HttpRequest::new( Method::GET, Uri::from_str("/").unwrap(), diff --git a/tests/test_client.rs b/tests/test_client.rs index 094656840..5496e59fd 100644 --- a/tests/test_client.rs +++ b/tests/test_client.rs @@ -73,10 +73,7 @@ fn test_with_query_parameter() { }) }); - let request = srv.get() - .uri(srv.url("/?qp=5").as_str()) - .finish() - .unwrap(); + let request = srv.get().uri(srv.url("/?qp=5").as_str()).finish().unwrap(); let response = srv.execute(request.send()).unwrap(); assert!(response.status().is_success()); @@ -125,7 +122,8 @@ fn test_client_gzip_encoding() { }); // client request - let request = srv.post() + let request = srv + .post() .content_encoding(http::ContentEncoding::Gzip) .body(STR) .unwrap(); @@ -154,7 +152,8 @@ fn test_client_gzip_encoding_large() { }); // client request - let request = srv.post() + let request = srv + .post() .content_encoding(http::ContentEncoding::Gzip) .body(data.clone()) .unwrap(); @@ -186,7 +185,8 @@ fn test_client_gzip_encoding_large_random() { }); // client request - let request = srv.post() + let request = srv + .post() .content_encoding(http::ContentEncoding::Gzip) .body(data.clone()) .unwrap(); @@ -214,7 +214,8 @@ fn test_client_brotli_encoding() { }); // client request - let request = srv.client(http::Method::POST, "/") + let request = srv + .client(http::Method::POST, "/") .content_encoding(http::ContentEncoding::Br) .body(STR) .unwrap(); @@ -247,7 +248,8 @@ fn test_client_brotli_encoding_large_random() { }); // client request - let request = srv.client(http::Method::POST, "/") + let request = srv + .client(http::Method::POST, "/") .content_encoding(http::ContentEncoding::Br) .body(data.clone()) .unwrap(); @@ -276,7 +278,8 @@ fn test_client_deflate_encoding() { }); // client request - let request = srv.post() + let request = srv + .post() .content_encoding(http::ContentEncoding::Deflate) .body(STR) .unwrap(); @@ -309,7 +312,8 @@ fn test_client_deflate_encoding_large_random() { }); // client request - let request = srv.post() + let request = srv + .post() .content_encoding(http::ContentEncoding::Deflate) .body(data.clone()) .unwrap(); @@ -339,9 +343,7 @@ fn test_client_streaming_explicit() { let body = once(Ok(Bytes::from_static(STR.as_ref()))); - let request = srv.get() - .body(Body::Streaming(Box::new(body))) - .unwrap(); + let request = srv.get().body(Body::Streaming(Box::new(body))).unwrap(); let response = srv.execute(request.send()).unwrap(); assert!(response.status().is_success()); @@ -414,7 +416,8 @@ fn test_client_cookie_handling() { }) }); - let request = srv.get() + let request = srv + .get() .cookie(cookie1.clone()) .cookie(cookie2.clone()) .finish() diff --git a/tests/test_handlers.rs b/tests/test_handlers.rs index 42a9f3ace..11565fd37 100644 --- a/tests/test_handlers.rs +++ b/tests/test_handlers.rs @@ -34,10 +34,7 @@ fn test_path_extractor() { }); // client request - let request = srv.get() - .uri(srv.url("/test/index.html")) - .finish() - .unwrap(); + let request = srv.get().uri(srv.url("/test/index.html")).finish().unwrap(); let response = srv.execute(request.send()).unwrap(); assert!(response.status().is_success()); @@ -55,7 +52,8 @@ fn test_query_extractor() { }); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/index.html?username=test")) .finish() .unwrap(); @@ -67,10 +65,7 @@ fn test_query_extractor() { assert_eq!(bytes, Bytes::from_static(b"Welcome test!")); // client request - let request = srv.get() - .uri(srv.url("/index.html")) - .finish() - .unwrap(); + let request = srv.get().uri(srv.url("/index.html")).finish().unwrap(); let response = srv.execute(request.send()).unwrap(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); } @@ -89,7 +84,8 @@ fn test_async_extractor_async() { }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -113,7 +109,8 @@ fn test_path_and_query_extractor() { }); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html?username=test2")) .finish() .unwrap(); @@ -125,7 +122,8 @@ fn test_path_and_query_extractor() { assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - test2!")); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html")) .finish() .unwrap(); @@ -145,7 +143,8 @@ fn test_path_and_query_extractor2() { }); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html?username=test2")) .finish() .unwrap(); @@ -157,7 +156,8 @@ fn test_path_and_query_extractor2() { assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - test2!")); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html")) .finish() .unwrap(); @@ -169,21 +169,21 @@ fn test_path_and_query_extractor2() { fn test_path_and_query_extractor2_async() { let mut srv = test::TestServer::new(|app| { app.resource("/{username}/index.html", |r| { - r.route().with3( - |p: Path, _: Query, data: Json| { + r.route() + .with3(|p: Path, _: Query, data: Json| { Timeout::new(Duration::from_millis(10), &Arbiter::handle()) .unwrap() .and_then(move |_| { Ok(format!("Welcome {} - {}!", p.username, data.0)) }) .responder() - }, - ) + }) }); }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html?username=test2")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -193,10 +193,7 @@ fn test_path_and_query_extractor2_async() { // read response let bytes = srv.execute(response.body()).unwrap(); - assert_eq!( - bytes, - Bytes::from_static(b"Welcome test1 - {\"test\":1}!") - ); + assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - {\"test\":1}!")); } #[test] @@ -215,7 +212,8 @@ fn test_path_and_query_extractor3_async() { }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -240,7 +238,8 @@ fn test_path_and_query_extractor4_async() { }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -253,21 +252,21 @@ fn test_path_and_query_extractor4_async() { fn test_path_and_query_extractor2_async2() { let mut srv = test::TestServer::new(|app| { app.resource("/{username}/index.html", |r| { - r.route().with3( - |p: Path, data: Json, _: Query| { + r.route() + .with3(|p: Path, data: Json, _: Query| { Timeout::new(Duration::from_millis(10), &Arbiter::handle()) .unwrap() .and_then(move |_| { Ok(format!("Welcome {} - {}!", p.username, data.0)) }) .responder() - }, - ) + }) }); }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html?username=test2")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -277,13 +276,11 @@ fn test_path_and_query_extractor2_async2() { // read response let bytes = srv.execute(response.body()).unwrap(); - assert_eq!( - bytes, - Bytes::from_static(b"Welcome test1 - {\"test\":1}!") - ); + assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - {\"test\":1}!")); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html")) .finish() .unwrap(); @@ -295,21 +292,21 @@ fn test_path_and_query_extractor2_async2() { fn test_path_and_query_extractor2_async3() { let mut srv = test::TestServer::new(|app| { app.resource("/{username}/index.html", |r| { - r.route().with3( - |data: Json, p: Path, _: Query| { + r.route() + .with3(|data: Json, p: Path, _: Query| { Timeout::new(Duration::from_millis(10), &Arbiter::handle()) .unwrap() .and_then(move |_| { Ok(format!("Welcome {} - {}!", p.username, data.0)) }) .responder() - }, - ) + }) }); }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html?username=test2")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -319,13 +316,11 @@ fn test_path_and_query_extractor2_async3() { // read response let bytes = srv.execute(response.body()).unwrap(); - assert_eq!( - bytes, - Bytes::from_static(b"Welcome test1 - {\"test\":1}!") - ); + assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - {\"test\":1}!")); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html")) .finish() .unwrap(); @@ -342,11 +337,7 @@ fn test_path_and_query_extractor2_async4() { Timeout::new(Duration::from_millis(10), &Arbiter::handle()) .unwrap() .and_then(move |_| { - Ok(format!( - "Welcome {} - {}!", - data.1.username, - (data.0).0 - )) + Ok(format!("Welcome {} - {}!", data.1.username, (data.0).0)) }) .responder() }) @@ -354,7 +345,8 @@ fn test_path_and_query_extractor2_async4() { }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html?username=test2")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -364,13 +356,11 @@ fn test_path_and_query_extractor2_async4() { // read response let bytes = srv.execute(response.body()).unwrap(); - assert_eq!( - bytes, - Bytes::from_static(b"Welcome test1 - {\"test\":1}!") - ); + assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - {\"test\":1}!")); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html")) .finish() .unwrap(); @@ -384,13 +374,7 @@ fn test_impl_trait( ) -> impl Future { Timeout::new(Duration::from_millis(10), &Arbiter::handle()) .unwrap() - .and_then(move |_| { - Ok(format!( - "Welcome {} - {}!", - data.1.username, - (data.0).0 - )) - }) + .and_then(move |_| Ok(format!("Welcome {} - {}!", data.1.username, (data.0).0))) } #[cfg(actix_impl_trait)] @@ -412,7 +396,8 @@ fn test_path_and_query_extractor2_async4_impl_trait() { }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html?username=test2")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -422,13 +407,11 @@ fn test_path_and_query_extractor2_async4_impl_trait() { // read response let bytes = srv.execute(response.body()).unwrap(); - assert_eq!( - bytes, - Bytes::from_static(b"Welcome test1 - {\"test\":1}!") - ); + assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - {\"test\":1}!")); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test1/index.html")) .finish() .unwrap(); @@ -446,7 +429,8 @@ fn test_path_and_query_extractor2_async4_impl_trait_err() { }); // client request - let request = srv.post() + let request = srv + .post() .uri(srv.url("/test1/index.html?username=test2")) .header("content-type", "application/json") .body("{\"test\": 1}") @@ -462,7 +446,8 @@ fn test_non_ascii_route() { }); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/中文/index.html")) .finish() .unwrap(); @@ -483,7 +468,8 @@ fn test_unsafe_path_route() { }); // client request - let request = srv.get() + let request = srv + .get() .uri(srv.url("/test/http%3A%2F%2Fexample.com")) .finish() .unwrap(); diff --git a/tests/test_middleware.rs b/tests/test_middleware.rs index 2c9160b61..8435e7464 100644 --- a/tests/test_middleware.rs +++ b/tests/test_middleware.rs @@ -27,9 +27,7 @@ impl middleware::Middleware for MiddlewareTest { } fn response( - &self, - _: &mut HttpRequest, - resp: HttpResponse, + &self, _: &mut HttpRequest, resp: HttpResponse, ) -> Result { self.response .store(self.response.load(Ordering::Relaxed) + 1, Ordering::Relaxed); @@ -450,9 +448,7 @@ impl middleware::Middleware for MiddlewareAsyncTest { } fn response( - &self, - _: &mut HttpRequest, - resp: HttpResponse, + &self, _: &mut HttpRequest, resp: HttpResponse, ) -> Result { let to = Timeout::new(Duration::from_millis(10), &Arbiter::handle()).unwrap(); diff --git a/tests/test_server.rs b/tests/test_server.rs index 863f800ac..7eb0bfaac 100644 --- a/tests/test_server.rs +++ b/tests/test_server.rs @@ -337,11 +337,7 @@ fn test_body_br_streaming() { #[test] fn test_head_empty() { let mut srv = test::TestServer::new(|app| { - app.handler(|_| { - HttpResponse::Ok() - .content_length(STR.len() as u64) - .finish() - }) + app.handler(|_| HttpResponse::Ok().content_length(STR.len() as u64).finish()) }); let request = srv.head().finish().unwrap(); @@ -529,7 +525,8 @@ fn test_gzip_encoding() { e.write_all(STR.as_ref()).unwrap(); let enc = e.finish().unwrap(); - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "gzip") .body(enc.clone()) .unwrap(); @@ -561,7 +558,8 @@ fn test_gzip_encoding_large() { e.write_all(data.as_ref()).unwrap(); let enc = e.finish().unwrap(); - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "gzip") .body(enc.clone()) .unwrap(); @@ -597,7 +595,8 @@ fn test_reading_gzip_encoding_large_random() { e.write_all(data.as_ref()).unwrap(); let enc = e.finish().unwrap(); - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "gzip") .body(enc.clone()) .unwrap(); @@ -629,7 +628,8 @@ fn test_reading_deflate_encoding() { let enc = e.finish().unwrap(); // client request - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "deflate") .body(enc) .unwrap(); @@ -661,7 +661,8 @@ fn test_reading_deflate_encoding_large() { let enc = e.finish().unwrap(); // client request - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "deflate") .body(enc) .unwrap(); @@ -697,7 +698,8 @@ fn test_reading_deflate_encoding_large_random() { let enc = e.finish().unwrap(); // client request - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "deflate") .body(enc) .unwrap(); @@ -730,7 +732,8 @@ fn test_brotli_encoding() { let enc = e.finish().unwrap(); // client request - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "br") .body(enc) .unwrap(); @@ -763,7 +766,8 @@ fn test_brotli_encoding_large() { let enc = e.finish().unwrap(); // client request - let request = srv.post() + let request = srv + .post() .header(http::header::CONTENT_ENCODING, "br") .body(enc) .unwrap(); @@ -784,7 +788,8 @@ fn test_h2() { let handle = core.handle(); let tcp = TcpStream::connect(&addr, &handle); - let tcp = tcp.then(|res| h2client::handshake(res.unwrap())) + let tcp = tcp + .then(|res| h2client::handshake(res.unwrap())) .then(move |res| { let (mut client, h2) = res.unwrap(); diff --git a/tests/test_ws.rs b/tests/test_ws.rs index 9dbc11b0e..0d75bc3f2 100644 --- a/tests/test_ws.rs +++ b/tests/test_ws.rs @@ -46,9 +46,7 @@ fn test_simple() { let (item, reader) = srv.execute(reader.into_future()).unwrap(); assert_eq!( item, - Some(ws::Message::Binary( - Bytes::from_static(b"text").into() - )) + Some(ws::Message::Binary(Bytes::from_static(b"text").into())) ); writer.ping("ping"); @@ -117,10 +115,7 @@ fn test_large_bin() { writer.binary(data.clone()); let (item, r) = srv.execute(reader.into_future()).unwrap(); reader = r; - assert_eq!( - item, - Some(ws::Message::Binary(Binary::from(data.clone()))) - ); + assert_eq!(item, Some(ws::Message::Binary(Binary::from(data.clone())))); } } @@ -231,19 +226,17 @@ fn test_ws_server_ssl() { .set_certificate_chain_file("tests/cert.pem") .unwrap(); - let mut srv = test::TestServer::build() - .ssl(builder.build()) - .start(|app| { - app.handler(|req| { - ws::start( - req, - Ws2 { - count: 0, - bin: false, - }, - ) - }) - }); + let mut srv = test::TestServer::build().ssl(builder.build()).start(|app| { + app.handler(|req| { + ws::start( + req, + Ws2 { + count: 0, + bin: false, + }, + ) + }) + }); let (mut reader, _writer) = srv.ws().unwrap(); let data = Some(ws::Message::Text("0".repeat(65_536))); diff --git a/tools/wsload/src/wsclient.rs b/tools/wsload/src/wsclient.rs index 186d63176..f28156b8e 100644 --- a/tools/wsload/src/wsclient.rs +++ b/tools/wsload/src/wsclient.rs @@ -82,43 +82,40 @@ fn main() { let perf = perf_counters.clone(); let addr = Arbiter::new(format!("test {}", t)); - addr.do_send(actix::msgs::Execute::new( - move || -> Result<(), ()> { - for _ in 0..concurrency { - let pl2 = pl.clone(); - let perf2 = perf.clone(); - let ws2 = ws.clone(); + addr.do_send(actix::msgs::Execute::new(move || -> Result<(), ()> { + for _ in 0..concurrency { + let pl2 = pl.clone(); + let perf2 = perf.clone(); + let ws2 = ws.clone(); - Arbiter::handle().spawn( - ws::Client::new(&ws) - .write_buffer_capacity(0) - .connect() - .map_err(|e| { - println!("Error: {}", e); - //Arbiter::system().do_send(actix::msgs::SystemExit(0)); - () - }) - .map(move |(reader, writer)| { - let addr: Addr = - ChatClient::create(move |ctx| { - ChatClient::add_stream(reader, ctx); - ChatClient { - url: ws2, - conn: writer, - payload: pl2, - bin: bin, - ts: time::precise_time_ns(), - perf_counters: perf2, - sent: 0, - max_payload_size: max_payload_size, - } - }); - }), - ); - } - Ok(()) - }, - )); + Arbiter::handle().spawn( + ws::Client::new(&ws) + .write_buffer_capacity(0) + .connect() + .map_err(|e| { + println!("Error: {}", e); + //Arbiter::system().do_send(actix::msgs::SystemExit(0)); + () + }) + .map(move |(reader, writer)| { + let addr: Addr = ChatClient::create(move |ctx| { + ChatClient::add_stream(reader, ctx); + ChatClient { + url: ws2, + conn: writer, + payload: pl2, + bin: bin, + ts: time::precise_time_ns(), + perf_counters: perf2, + sent: 0, + max_payload_size: max_payload_size, + } + }); + }), + ); + } + Ok(()) + })); } let res = sys.run(); @@ -126,10 +123,7 @@ fn main() { fn parse_u64_default(input: Option<&str>, default: u64) -> u64 { input - .map(|v| { - v.parse() - .expect(&format!("not a valid number: {}", v)) - }) + .map(|v| v.parse().expect(&format!("not a valid number: {}", v))) .unwrap_or(default) } @@ -314,7 +308,8 @@ impl PerfCounters { loop { let current = self.lat_max.load(Ordering::SeqCst); if current >= nanos - || self.lat_max + || self + .lat_max .compare_and_swap(current, nanos, Ordering::SeqCst) == current {