1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 01:32:57 +01:00

rustfmt 0.7

This commit is contained in:
Nikolay Kim 2018-05-17 12:20:20 -07:00
parent 564cc15c04
commit 45e9aaa462
58 changed files with 508 additions and 758 deletions

View File

@ -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);
}

View File

@ -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>) {
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()))
}
}

View File

@ -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};

View File

@ -270,7 +270,8 @@ impl Pipeline {
#[inline]
fn parse(&mut self) -> Poll<ClientResponse, HttpResponseParserError> {
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(_)) => {

View File

@ -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<Item = Bytes, Error = E> + 'static,
E: Into<Error>,
{
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`

View File

@ -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"));

View File

@ -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(_) => {

View File

@ -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]

View File

@ -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<V>(
@ -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))
}
}

View File

@ -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<S: 'static> FromRequest<S> 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());

124
src/fs.rs
View File

@ -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_() {
@ -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<S: 'static> Handler<S> for StaticFiles<S> {
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,9 +766,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"
);
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
@ -783,7 +778,8 @@ mod tests {
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();

View File

@ -362,7 +362,8 @@ where
self, req: &HttpRequest<S>,
) -> Result<AsyncResult<HttpResponse>, 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<S>) -> AsyncResult<HttpResponse> {
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))
}
}

View File

@ -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.

View File

@ -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]

View File

@ -105,9 +105,7 @@ mod tests {
#[test]
fn test_date() {
assert_eq!(
"Sun, 07 Nov 1994 08:48:37 GMT"
.parse::<HttpDate>()
.unwrap(),
"Sun, 07 Nov 1994 08:48:37 GMT".parse::<HttpDate>().unwrap(),
NOV_07
);
assert_eq!(
@ -117,9 +115,7 @@ mod tests {
NOV_07
);
assert_eq!(
"Sun Nov 7 08:48:37 1994"
.parse::<HttpDate>()
.unwrap(),
"Sun Nov 7 08:48:37 1994".parse::<HttpDate>().unwrap(),
NOV_07
);
assert!("this-is-no-date".parse::<HttpDate>().is_err());

View File

@ -63,11 +63,7 @@ impl<T: fmt::Display> fmt::Display for QualityItem<T> {
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::<QualityItem<String>>().is_err());
assert!(
"\x0d;;;=\u{d6aa}=="
.parse::<QualityItem<String>>()
.is_err()
)
assert!("\x0d;;;=\u{d6aa}==".parse::<QualityItem<String>>().is_err())
}
}

View File

@ -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()
);
}
}

View File

@ -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);
}

View File

@ -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<Vec<HttpRange>, 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"),

View File

@ -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<Payload>,
) -> HttpRequest {
let url = InnerUrl::new(uri);
@ -304,9 +301,7 @@ impl<S> HttpRequest<S> {
/// }
/// ```
pub fn url_for<U, I>(
&self,
name: &str,
elements: U,
&self, name: &str, elements: U,
) -> Result<Url, UrlGenerationError>
where
U: IntoIterator<Item = I>,

View File

@ -600,8 +600,7 @@ impl HttpResponseBuilder {
#[inline]
#[cfg_attr(feature = "cargo-clippy", allow(borrowed_box))]
fn parts<'a>(
parts: &'a mut Option<Box<InnerHttpResponse>>,
err: &Option<HttpError>,
parts: &'a mut Option<Box<InnerHttpResponse>>, err: &Option<HttpError>,
) -> Option<&'a mut Box<InnerHttpResponse>> {
if err.is_some() {
return None;
@ -648,7 +647,8 @@ impl Responder for &'static str {
type Error = Error;
fn respond_to<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, Error> {
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<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, Error> {
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<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, Error> {
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<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, Error> {
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<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, Error> {
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<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, Error> {
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<UnsafeCell<HttpResponsePool>>,
status: StatusCode,
pool: &Rc<UnsafeCell<HttpResponsePool>>, 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<UnsafeCell<HttpResponsePool>>,
status: StatusCode,
body: Body,
pool: &Rc<UnsafeCell<HttpResponsePool>>, 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<UnsafeCell<HttpResponsePool>>,
mut inner: Box<InnerHttpResponse>,
pool: &Rc<UnsafeCell<HttpResponsePool>>, mut inner: Box<InnerHttpResponse>,
) {
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())

View File

@ -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");

View File

@ -121,7 +121,8 @@ impl<T: Serialize> Responder for Json<T> {
fn respond_to<S>(self, req: &HttpRequest<S>) -> Result<HttpResponse, Error> {
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::<MyObject>();
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::<MyObject>();
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(

View File

@ -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<S: 'static>(self, resource: &mut ResourceHandler<S>) {
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<S>(
&self, req: &mut HttpRequest<S>,
) -> 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<S> Middleware<S> 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<S> Middleware<S> 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<S: 'static> CorsBuilder<S> {
}
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()

View File

@ -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!(),

View File

@ -179,7 +179,8 @@ impl<S: 'static, T: IdentityPolicy<S>> Middleware<S> for IdentityService<T> {
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
let mut req = req.clone();
let fut = self.backend
let fut = self
.backend
.from_request(&mut req)
.then(move |res| match res {
Ok(id) => {

View File

@ -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| {

View File

@ -267,9 +267,7 @@ impl<S: 'static, T: SessionBackend<S>> Middleware<S> for SessionStorage<T, S> {
}
fn response(
&self,
req: &mut HttpRequest<S>,
resp: HttpResponse,
&self, req: &mut HttpRequest<S>, resp: HttpResponse,
) -> Result<Response> {
if let Some(s_box) = req.extensions_mut().remove::<Arc<SessionImplCell>>() {
s_box.0.borrow_mut().write(resp)
@ -385,9 +383,7 @@ impl CookieSessionInner {
}
fn set_cookie(
&self,
resp: &mut HttpResponse,
state: &HashMap<String, String>,
&self, resp: &mut HttpResponse, state: &HashMap<String, String>,
) -> Result<()> {
let value =
serde_json::to_string(&state).map_err(CookieSessionError::Serialize)?;

View File

@ -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);

View File

@ -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"));

View File

@ -29,9 +29,7 @@ pub(crate) trait PipelineHandler<S> {
fn encoding(&self) -> ContentEncoding;
fn handle(
&mut self,
req: HttpRequest<S>,
htype: HandlerType,
&mut self, req: HttpRequest<S>, htype: HandlerType,
) -> AsyncResult<HttpResponse>;
}
@ -122,10 +120,8 @@ impl<S> PipelineInfo<S> {
impl<S: 'static, H: PipelineHandler<S>> Pipeline<S, H> {
pub fn new(
req: HttpRequest<S>,
mws: Rc<Vec<Box<Middleware<S>>>>,
handler: Rc<UnsafeCell<H>>,
htype: HandlerType,
req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>,
handler: Rc<UnsafeCell<H>>, htype: HandlerType,
) -> Pipeline<S, H> {
let mut info = PipelineInfo {
mws,
@ -243,9 +239,7 @@ struct StartMiddlewares<S, H> {
impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> {
fn init(
info: &mut PipelineInfo<S>,
hnd: Rc<UnsafeCell<H>>,
htype: HandlerType,
info: &mut PipelineInfo<S>, hnd: Rc<UnsafeCell<H>>, htype: HandlerType,
) -> PipelineState<S, H> {
// 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<S, H> {
impl<S: 'static, H> WaitingResponse<S, H> {
#[inline]
fn init(
info: &mut PipelineInfo<S>,
reply: AsyncResult<HttpResponse>,
info: &mut PipelineInfo<S>, reply: AsyncResult<HttpResponse>,
) -> PipelineState<S, H> {
match reply.into() {
AsyncResultItem::Err(err) => RunMiddlewares::init(info, err.into()),
@ -475,9 +468,7 @@ impl<S: 'static, H> ProcessResponse<S, H> {
}
fn poll_io(
mut self,
io: &mut Writer,
info: &mut PipelineInfo<S>,
mut self, io: &mut Writer, info: &mut PipelineInfo<S>,
) -> Result<PipelineState<S, H>, PipelineState<S, H>> {
loop {
if self.drain.is_none() && self.running != RunningState::Paused {

View File

@ -181,11 +181,7 @@ pub fn Header<S: 'static>(
}
#[doc(hidden)]
pub struct HeaderPredicate<S>(
header::HeaderName,
header::HeaderValue,
PhantomData<S>,
);
pub struct HeaderPredicate<S>(header::HeaderName, header::HeaderValue, PhantomData<S>);
impl<S: 'static> Predicate<S> for HeaderPredicate<S> {
fn check(&self, req: &mut HttpRequest<S>) -> bool {

View File

@ -134,10 +134,7 @@ impl<S: 'static> ResourceHandler<S> {
/// ```
pub fn method(&mut self, method: Method) -> &mut Route<S> {
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.

View File

@ -55,9 +55,7 @@ impl<S: 'static> Route<S> {
#[inline]
pub(crate) fn compose(
&mut self,
req: HttpRequest<S>,
mws: Rc<Vec<Box<Middleware<S>>>>,
&mut self, req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>,
) -> AsyncResult<HttpResponse> {
AsyncResult::async(Box::new(Compose::new(req, mws, self.handler.clone())))
}
@ -248,8 +246,7 @@ impl<S: 'static> Route<S> {
/// }
/// ```
pub fn with2<T1, T2, F, R>(
&mut self,
handler: F,
&mut self, handler: F,
) -> (ExtractorConfig<S, T1>, ExtractorConfig<S, T2>)
where
F: Fn(T1, T2) -> R + 'static,
@ -270,8 +267,7 @@ impl<S: 'static> Route<S> {
#[doc(hidden)]
/// Set handler function, use request extractor for all parameters.
pub fn with3<T1, T2, T3, F, R>(
&mut self,
handler: F,
&mut self, handler: F,
) -> (
ExtractorConfig<S, T1>,
ExtractorConfig<S, T2>,
@ -368,9 +364,7 @@ impl<S: 'static> ComposeState<S> {
impl<S: 'static> Compose<S> {
fn new(
req: HttpRequest<S>,
mws: Rc<Vec<Box<Middleware<S>>>>,
handler: InnerHandler<S>,
req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>, handler: InnerHandler<S>,
) -> Self {
let mut info = ComposeInfo {
count: 0,
@ -485,8 +479,7 @@ struct WaitingResponse<S> {
impl<S: 'static> WaitingResponse<S> {
#[inline]
fn init(
info: &mut ComposeInfo<S>,
reply: AsyncResult<HttpResponse>,
info: &mut ComposeInfo<S>, reply: AsyncResult<HttpResponse>,
) -> ComposeState<S> {
match reply.into() {
AsyncResultItem::Err(err) => RunMiddlewares::init(info, err.into()),

View File

@ -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()),

View File

@ -459,8 +459,7 @@ impl<S: 'static> ComposeState<S> {
impl<S: 'static> Compose<S> {
fn new(
req: HttpRequest<S>,
mws: Rc<Vec<Box<Middleware<S>>>>,
req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>,
resource: Rc<UnsafeCell<ResourceHandler<S>>>,
default: Option<Rc<UnsafeCell<ResourceHandler<S>>>>,
) -> Self {
@ -585,8 +584,7 @@ struct WaitingResponse<S> {
impl<S: 'static> WaitingResponse<S> {
#[inline]
fn init(
info: &mut ComposeInfo<S>,
reply: AsyncResult<HttpResponse>,
info: &mut ComposeInfo<S>, reply: AsyncResult<HttpResponse>,
) -> ComposeState<S> {
match reply.into() {
AsyncResultItem::Ok(resp) => RunMiddlewares::init(info, resp),

View File

@ -38,9 +38,7 @@ where
H: HttpHandler + 'static,
{
pub(crate) fn new(
settings: Rc<WorkerSettings<H>>,
mut io: T,
peer: Option<SocketAddr>,
settings: Rc<WorkerSettings<H>>, mut io: T, peer: Option<SocketAddr>,
http2: bool,
) -> HttpChannel<T, H> {
settings.add_channel();

View File

@ -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();

View File

@ -67,9 +67,7 @@ where
H: HttpHandler + 'static,
{
pub fn new(
settings: Rc<WorkerSettings<H>>,
stream: T,
addr: Option<SocketAddr>,
settings: Rc<WorkerSettings<H>>, stream: T, addr: Option<SocketAddr>,
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())

View File

@ -46,9 +46,7 @@ impl H1Decoder {
}
pub fn decode<H>(
&mut self,
src: &mut BytesMut,
settings: &WorkerSettings<H>,
&mut self, src: &mut BytesMut, settings: &WorkerSettings<H>,
) -> Result<Option<Message>, 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<H>(
&self,
buf: &mut BytesMut,
settings: &WorkerSettings<H>,
&self, buf: &mut BytesMut, settings: &WorkerSettings<H>,
) -> Poll<(SharedHttpInnerMessage, Option<EncodingDecoder>), 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<Bytes>,
&self, body: &mut BytesMut, size: &mut u64, buf: &mut Option<Bytes>,
) -> Poll<ChunkedState, io::Error> {
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<ChunkedState, io::Error> {
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<Bytes>,
rdr: &mut BytesMut, rem: &mut u64, buf: &mut Option<Bytes>,
) -> Poll<ChunkedState, io::Error> {
trace!("Chunked read, remaining={:?}", rem);

View File

@ -42,9 +42,7 @@ pub(crate) struct H1Writer<T: AsyncWrite, H: 'static> {
impl<T: AsyncWrite, H: 'static> H1Writer<T, H> {
pub fn new(
stream: T,
buf: SharedBytes,
settings: Rc<WorkerSettings<H>>,
stream: T, buf: SharedBytes, settings: Rc<WorkerSettings<H>>,
) -> H1Writer<T, H> {
H1Writer {
flags: Flags::empty(),
@ -103,9 +101,7 @@ impl<T: AsyncWrite, H: 'static> Writer for H1Writer<T, H> {
}
fn start(
&mut self,
req: &mut HttpInnerMessage,
msg: &mut HttpResponse,
&mut self, req: &mut HttpInnerMessage, msg: &mut HttpResponse,
encoding: ContentEncoding,
) -> io::Result<WriterState> {
// prepare task

View File

@ -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);

View File

@ -120,7 +120,8 @@ impl<H: 'static> Writer for H2Writer<H> {
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),

View File

@ -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"[..]);
}
}

View File

@ -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]

View File

@ -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<Self> {
pub fn listen_ssl(
mut self, lst: net::TcpListener, mut builder: SslAcceptorBuilder,
) -> io::Result<Self> {
// 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(
&reg,
CMD,
mio::Ready::readable(),
mio::PollOpt::edge(),
) {
if let Err(err) =
poll.register(&reg, CMD, mio::Ready::readable(), mio::PollOpt::edge())
{
panic!("Can not register Registration: {}", err);
}

View File

@ -85,9 +85,7 @@ impl<H: HttpHandler + 'static> Worker<H> {
fn update_time(&self, ctx: &mut Context<Self>) {
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(()))
}));
}
}
}

View File

@ -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),

View File

@ -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

View File

@ -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
}

View File

@ -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
}

View File

@ -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<S>(
}
// 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(),

View File

@ -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()

View File

@ -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<PParam>, _: Query<PParam>, data: Json<Value>| {
r.route()
.with3(|p: Path<PParam>, _: Query<PParam>, data: Json<Value>| {
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<PParam>, data: Json<Value>, _: Query<PParam>| {
r.route()
.with3(|p: Path<PParam>, data: Json<Value>, _: Query<PParam>| {
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<Value>, p: Path<PParam>, _: Query<PParam>| {
r.route()
.with3(|data: Json<Value>, p: Path<PParam>, _: Query<PParam>| {
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<Item = String, Error = io::Error> {
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();

View File

@ -27,9 +27,7 @@ impl<S> middleware::Middleware<S> for MiddlewareTest {
}
fn response(
&self,
_: &mut HttpRequest<S>,
resp: HttpResponse,
&self, _: &mut HttpRequest<S>, resp: HttpResponse,
) -> Result<middleware::Response> {
self.response
.store(self.response.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
@ -450,9 +448,7 @@ impl<S> middleware::Middleware<S> for MiddlewareAsyncTest {
}
fn response(
&self,
_: &mut HttpRequest<S>,
resp: HttpResponse,
&self, _: &mut HttpRequest<S>, resp: HttpResponse,
) -> Result<middleware::Response> {
let to = Timeout::new(Duration::from_millis(10), &Arbiter::handle()).unwrap();

View File

@ -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();

View File

@ -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)));

View File

@ -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<Syn, _> =
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<Syn, _> = 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
{