Skip to content

Commit

Permalink
Various refactorings (actix#2281)
Browse files Browse the repository at this point in the history
Co-authored-by: Rob Ede <[email protected]>
  • Loading branch information
popzxc and robjtede authored Jun 26, 2021
1 parent 5eba95b commit 262c6bc
Show file tree
Hide file tree
Showing 30 changed files with 97 additions and 120 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ guide/build/

# Configuration directory generated by CLion
.idea

# Configuration directory generated by VSCode
.vscode
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* Deprecate `App::data` and `App::data_factory`. [#2271]
* Smarter extraction of `ConnectionInfo` parts. [#2282]


### Fixed
* Scope and Resource middleware can access data items set on their own layer. [#2288]

Expand Down
8 changes: 4 additions & 4 deletions actix-files/src/named.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,8 @@ impl NamedFile {
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
(last_modified, req.get_header())
{
let t1: SystemTime = m.clone().into();
let t2: SystemTime = since.clone().into();
let t1: SystemTime = (*m).into();
let t2: SystemTime = (*since).into();

match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
(Ok(t1), Ok(t2)) => t1.as_secs() > t2.as_secs(),
Expand All @@ -374,8 +374,8 @@ impl NamedFile {
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
(last_modified, req.get_header())
{
let t1: SystemTime = m.clone().into();
let t2: SystemTime = since.clone().into();
let t1: SystemTime = (*m).into();
let t2: SystemTime = (*since).into();

match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
(Ok(t1), Ok(t2)) => t1.as_secs() <= t2.as_secs(),
Expand Down
6 changes: 4 additions & 2 deletions actix-http/benches/uninit-headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ impl HeaderIndex {
// test cases taken from:
// https://github.com/seanmonstar/httparse/blob/master/benches/parse.rs

const REQ_SHORT: &'static [u8] = b"\
const REQ_SHORT: &[u8] = b"\
GET / HTTP/1.0\r\n\
Host: example.com\r\n\
Cookie: session=60; user_id=1\r\n\r\n";

const REQ: &'static [u8] = b"\
const REQ: &[u8] = b"\
GET /wp-content/uploads/2010/03/hello-kitty-darth-vader-pink.jpg HTTP/1.1\r\n\
Host: www.kittyhell.com\r\n\
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; ja-JP-mac; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 Pathtraq/0.9\r\n\
Expand Down Expand Up @@ -119,6 +119,8 @@ mod _original {
use std::mem::MaybeUninit;

pub fn parse_headers(src: &mut BytesMut) -> usize {
#![allow(clippy::uninit_assumed_init)]

let mut headers: [HeaderIndex; MAX_HEADERS] =
unsafe { MaybeUninit::uninit().assume_init() };

Expand Down
8 changes: 3 additions & 5 deletions actix-http/src/client/connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl Connector<()> {
use bytes::{BufMut, BytesMut};

let mut alpn = BytesMut::with_capacity(20);
for proto in protocols.iter() {
for proto in &protocols {
alpn.put_u8(proto.len() as u8);
alpn.put(proto.as_slice());
}
Expand Down Expand Up @@ -290,8 +290,7 @@ where
let h2 = sock
.ssl()
.selected_alpn_protocol()
.map(|protos| protos.windows(2).any(|w| w == H2))
.unwrap_or(false);
.map_or(false, |protos| protos.windows(2).any(|w| w == H2));
if h2 {
(Box::new(sock), Protocol::Http2)
} else {
Expand Down Expand Up @@ -325,8 +324,7 @@ where
.get_ref()
.1
.get_alpn_protocol()
.map(|protos| protos.windows(2).any(|w| w == H2))
.unwrap_or(false);
.map_or(false, |protos| protos.windows(2).any(|w| w == H2));
if h2 {
(Box::new(sock), Protocol::Http2)
} else {
Expand Down
11 changes: 5 additions & 6 deletions actix-http/src/client/h2proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,13 @@ where

if let Err(e) = send.send_data(bytes, false) {
return Err(e.into());
}
if !b.is_empty() {
send.reserve_capacity(b.len());
} else {
if !b.is_empty() {
send.reserve_capacity(b.len());
} else {
buf = None;
}
continue;
buf = None;
}
continue;
}
Some(Err(e)) => return Err(e.into()),
}
Expand Down
8 changes: 4 additions & 4 deletions actix-http/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,8 @@ impl ServiceConfig {
}
}

#[inline]
/// Return keep-alive timer delay is configured.
#[inline]
pub fn keep_alive_timer(&self) -> Option<Sleep> {
self.keep_alive().map(|ka| sleep_until(self.now() + ka))
}
Expand Down Expand Up @@ -365,11 +365,11 @@ mod tests {
let clone3 = service.clone();

drop(clone1);
assert_eq!(false, notify_on_drop::is_dropped());
assert!(!notify_on_drop::is_dropped());
drop(clone2);
assert_eq!(false, notify_on_drop::is_dropped());
assert!(!notify_on_drop::is_dropped());
drop(clone3);
assert_eq!(false, notify_on_drop::is_dropped());
assert!(!notify_on_drop::is_dropped());

drop(service);
assert!(notify_on_drop::is_dropped());
Expand Down
2 changes: 1 addition & 1 deletion actix-http/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl fmt::Display for Error {

impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.inner.cause.as_ref().map(|err| err.as_ref())
self.inner.cause.as_ref().map(Box::as_ref)
}
}

Expand Down
6 changes: 3 additions & 3 deletions actix-http/src/h1/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,15 @@ pub(crate) trait MessageType: Sized {
}
// transfer-encoding
header::TRANSFER_ENCODING => {
if let Ok(s) = value.to_str().map(|s| s.trim()) {
if let Ok(s) = value.to_str().map(str::trim) {
chunked = s.eq_ignore_ascii_case("chunked");
} else {
return Err(ParseError::Header);
}
}
// connection keep-alive state
header::CONNECTION => {
ka = if let Ok(conn) = value.to_str().map(|conn| conn.trim()) {
ka = if let Ok(conn) = value.to_str().map(str::trim) {
if conn.eq_ignore_ascii_case("keep-alive") {
Some(ConnectionType::KeepAlive)
} else if conn.eq_ignore_ascii_case("close") {
Expand All @@ -125,7 +125,7 @@ pub(crate) trait MessageType: Sized {
};
}
header::UPGRADE => {
if let Ok(val) = value.to_str().map(|val| val.trim()) {
if let Ok(val) = value.to_str().map(str::trim) {
if val.eq_ignore_ascii_case("websocket") {
has_upgrade_websocket = true;
}
Expand Down
3 changes: 1 addition & 2 deletions actix-http/src/h1/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,14 +515,13 @@ where
cx: &mut Context<'_>,
) -> Result<(), DispatchError> {
// Handle `EXPECT: 100-Continue` header
let mut this = self.as_mut().project();
if req.head().expect() {
// set dispatcher state so the future is pinned.
let mut this = self.as_mut().project();
let task = this.flow.expect.call(req);
this.state.set(State::ExpectCall(task));
} else {
// the same as above.
let mut this = self.as_mut().project();
let task = this.flow.service.call(req);
this.state.set(State::ServiceCall(task));
};
Expand Down
6 changes: 2 additions & 4 deletions actix-http/src/h1/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,7 @@ impl Inner {
if self
.task
.as_ref()
.map(|w| !cx.waker().will_wake(w))
.unwrap_or(true)
.map_or(true, |w| !cx.waker().will_wake(w))
{
self.task = Some(cx.waker().clone());
}
Expand All @@ -199,8 +198,7 @@ impl Inner {
if self
.io_task
.as_ref()
.map(|w| !cx.waker().will_wake(w))
.unwrap_or(true)
.map_or(true, |w| !cx.waker().will_wake(w))
{
self.io_task = Some(cx.waker().clone());
}
Expand Down
6 changes: 3 additions & 3 deletions actix-http/src/header/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ impl HeaderMap {
/// assert!(map.get("INVALID HEADER NAME").is_none());
/// ```
pub fn get(&self, key: impl AsHeaderName) -> Option<&HeaderValue> {
self.get_value(key).map(|val| val.first())
self.get_value(key).map(Value::first)
}

/// Returns a mutable reference to the _first_ value associated a header name.
Expand Down Expand Up @@ -280,8 +280,8 @@ impl HeaderMap {
/// ```
pub fn get_mut(&mut self, key: impl AsHeaderName) -> Option<&mut HeaderValue> {
match key.try_as_name(super::as_name::Seal).ok()? {
Cow::Borrowed(name) => self.inner.get_mut(name).map(|v| v.first_mut()),
Cow::Owned(name) => self.inner.get_mut(&name).map(|v| v.first_mut()),
Cow::Borrowed(name) => self.inner.get_mut(name).map(Value::first_mut),
Cow::Owned(name) => self.inner.get_mut(&name).map(Value::first_mut),
}
}

Expand Down
27 changes: 13 additions & 14 deletions actix-http/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,16 @@ impl RequestHead {

/// Connection upgrade status
pub fn upgrade(&self) -> bool {
if let Some(hdr) = self.headers().get(header::CONNECTION) {
if let Ok(s) = hdr.to_str() {
s.to_ascii_lowercase().contains("upgrade")
} else {
false
}
} else {
false
}
self.headers()
.get(header::CONNECTION)
.map(|hdr| {
if let Ok(s) = hdr.to_str() {
s.to_ascii_lowercase().contains("upgrade")
} else {
false
}
})
.unwrap_or(false)
}

#[inline]
Expand Down Expand Up @@ -308,13 +309,11 @@ impl ResponseHead {
/// Get custom reason for the response
#[inline]
pub fn reason(&self) -> &str {
if let Some(reason) = self.reason {
reason
} else {
self.reason.unwrap_or_else(|| {
self.status
.canonical_reason()
.unwrap_or("<unknown status code>")
}
})
}

#[inline]
Expand Down Expand Up @@ -356,7 +355,7 @@ pub struct Message<T: Head> {
impl<T: Head> Message<T> {
/// Get new message from the pool of objects
pub fn new() -> Self {
T::with_pool(|p| p.get_message())
T::with_pool(MessagePool::get_message)
}
}

Expand Down
7 changes: 3 additions & 4 deletions actix-web-codegen/src/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::convert::TryFrom;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use syn::{parse_macro_input, AttributeArgs, Ident, NestedMeta};
use syn::{parse_macro_input, AttributeArgs, Ident, LitStr, NestedMeta};

enum ResourceType {
Async,
Expand Down Expand Up @@ -227,8 +227,7 @@ impl Route {
format!(
r#"invalid service definition, expected #[{}("<some path>")]"#,
method
.map(|it| it.as_str())
.unwrap_or("route")
.map_or("route", |it| it.as_str())
.to_ascii_lowercase()
),
));
Expand Down Expand Up @@ -298,7 +297,7 @@ impl ToTokens for Route {
} = self;
let resource_name = resource_name
.as_ref()
.map_or_else(|| name.to_string(), |n| n.value());
.map_or_else(|| name.to_string(), LitStr::value);
let method_guards = {
let mut others = methods.iter();
// unwrapping since length is checked to be at least one
Expand Down
4 changes: 3 additions & 1 deletion awc/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,9 @@ impl ClientRequest {
let mut encoding = vec![];

#[cfg(feature = "compress-brotli")]
encoding.push("br");
{
encoding.push("br");
}

#[cfg(feature = "compress-gzip")]
{
Expand Down
2 changes: 1 addition & 1 deletion awc/src/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ mod tests {
"test-origin"
);
assert_eq!(req.max_size, 100);
assert_eq!(req.server_mode, true);
assert!(req.server_mode);
assert_eq!(req.protocols, Some("v1,v2".to_string()));
assert_eq!(
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
Expand Down
11 changes: 5 additions & 6 deletions benches/responder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{future::Future, time::Instant};

use actix_http::Response;
use actix_utils::future::{ready, Ready};
use actix_web::http::StatusCode;
use actix_web::test::TestRequest;
Expand All @@ -24,11 +23,11 @@ struct StringResponder(String);

impl FutureResponder for StringResponder {
type Error = Error;
type Future = Ready<Result<Response, Self::Error>>;
type Future = Ready<Result<HttpResponse, Self::Error>>;

fn future_respond_to(self, _: &HttpRequest) -> Self::Future {
// this is default builder for string response in both new and old responder trait.
ready(Ok(Response::build(StatusCode::OK)
ready(Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self.0)))
}
Expand All @@ -37,7 +36,7 @@ impl FutureResponder for StringResponder {
impl<T> FutureResponder for OptionResponder<T>
where
T: FutureResponder,
T::Future: Future<Output = Result<Response, Error>>,
T::Future: Future<Output = Result<HttpResponse, Error>>,
{
type Error = Error;
type Future = Either<T::Future, Ready<Result<HttpResponse, Self::Error>>>;
Expand All @@ -52,7 +51,7 @@ where

impl Responder for StringResponder {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
Response::build(StatusCode::OK)
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self.0)
}
Expand All @@ -62,7 +61,7 @@ impl<T: Responder> Responder for OptionResponder<T> {
fn respond_to(self, req: &HttpRequest) -> HttpResponse {
match self.0 {
Some(t) => t.respond_to(req),
None => Response::from_error(error::ErrorInternalServerError("err")),
None => HttpResponse::from_error(error::ErrorInternalServerError("err")),
}
}
}
Expand Down
6 changes: 2 additions & 4 deletions benches/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,8 @@ where
fut.await.unwrap();
}
});
let elapsed = start.elapsed();
// check that at least first request succeeded
elapsed
start.elapsed()
})
});
}
Expand Down Expand Up @@ -93,9 +92,8 @@ fn async_web_service(c: &mut Criterion) {
fut.await.unwrap();
}
});
let elapsed = start.elapsed();
// check that at least first request succeeded
elapsed
start.elapsed()
})
});
}
Expand Down
Loading

0 comments on commit 262c6bc

Please sign in to comment.