1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 00:21:08 +01:00

rust 1.64 clippy run (#2891)

This commit is contained in:
Rob Ede 2022-09-25 20:54:17 +01:00 committed by GitHub
parent 172c4c7a0a
commit cc7145d41d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 58 additions and 67 deletions

View File

@ -23,7 +23,7 @@ impl Deref for FilesService {
type Target = FilesServiceInner; type Target = FilesServiceInner;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&*self.0 &self.0
} }
} }

View File

@ -131,7 +131,7 @@ mod foreign_impls {
type Error = B::Error; type Error = B::Error;
fn size(&self) -> BodySize { fn size(&self) -> BodySize {
(&**self).size() (**self).size()
} }
fn poll_next( fn poll_next(

View File

@ -42,7 +42,7 @@ pub async fn to_bytes<B: MessageBody>(body: B) -> Result<Bytes, B::Error> {
let body = body.as_mut(); let body = body.as_mut();
match ready!(body.poll_next(cx)) { match ready!(body.poll_next(cx)) {
Some(Ok(bytes)) => buf.extend_from_slice(&*bytes), Some(Ok(bytes)) => buf.extend_from_slice(&bytes),
None => return Poll::Ready(Ok(())), None => return Poll::Ready(Ok(())),
Some(Err(err)) => return Poll::Ready(Err(err)), Some(Err(err)) => return Poll::Ready(Err(err)),
} }

View File

@ -637,7 +637,7 @@ async fn expect_handling() {
if let DispatcherState::Normal { ref inner } = h1.inner { if let DispatcherState::Normal { ref inner } = h1.inner {
let io = inner.io.as_ref().unwrap(); let io = inner.io.as_ref().unwrap();
let mut res = (&io.write_buf()[..]).to_owned(); let mut res = io.write_buf()[..].to_owned();
stabilize_date_header(&mut res); stabilize_date_header(&mut res);
assert_eq!( assert_eq!(
@ -699,7 +699,7 @@ async fn expect_eager() {
if let DispatcherState::Normal { ref inner } = h1.inner { if let DispatcherState::Normal { ref inner } = h1.inner {
let io = inner.io.as_ref().unwrap(); let io = inner.io.as_ref().unwrap();
let mut res = (&io.write_buf()[..]).to_owned(); let mut res = io.write_buf()[..].to_owned();
stabilize_date_header(&mut res); stabilize_date_header(&mut res);
// Despite the content-length header and even though the request payload has not // Despite the content-length header and even though the request payload has not

View File

@ -309,7 +309,7 @@ impl HeaderMap {
pub fn get_all(&self, key: impl AsHeaderName) -> std::slice::Iter<'_, HeaderValue> { pub fn get_all(&self, key: impl AsHeaderName) -> std::slice::Iter<'_, HeaderValue> {
match self.get_value(key) { match self.get_value(key) {
Some(value) => value.iter(), Some(value) => value.iter(),
None => (&[]).iter(), None => [].iter(),
} }
} }

View File

@ -113,14 +113,14 @@ impl<P> Request<P> {
#[inline] #[inline]
/// Http message part of the request /// Http message part of the request
pub fn head(&self) -> &RequestHead { pub fn head(&self) -> &RequestHead {
&*self.head &self.head
} }
#[inline] #[inline]
#[doc(hidden)] #[doc(hidden)]
/// Mutable reference to a HTTP message part of the request /// Mutable reference to a HTTP message part of the request
pub fn head_mut(&mut self) -> &mut RequestHead { pub fn head_mut(&mut self) -> &mut RequestHead {
&mut *self.head &mut self.head
} }
/// Mutable reference to the message's headers. /// Mutable reference to the message's headers.

View File

@ -83,13 +83,13 @@ impl<B> Response<B> {
/// Returns a reference to the head of this response. /// Returns a reference to the head of this response.
#[inline] #[inline]
pub fn head(&self) -> &ResponseHead { pub fn head(&self) -> &ResponseHead {
&*self.head &self.head
} }
/// Returns a mutable reference to the head of this response. /// Returns a mutable reference to the head of this response.
#[inline] #[inline]
pub fn head_mut(&mut self) -> &mut ResponseHead { pub fn head_mut(&mut self) -> &mut ResponseHead {
&mut *self.head &mut self.head
} }
/// Returns the status code of this response. /// Returns the status code of this response.

View File

@ -313,7 +313,7 @@ mod tests {
#[test] #[test]
fn test_parse_frame_no_mask() { fn test_parse_frame_no_mask() {
let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]); let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]);
buf.extend(&[1u8]); buf.extend([1u8]);
assert!(Parser::parse(&mut buf, true, 1024).is_err()); assert!(Parser::parse(&mut buf, true, 1024).is_err());
@ -326,7 +326,7 @@ mod tests {
#[test] #[test]
fn test_parse_frame_max_size() { fn test_parse_frame_max_size() {
let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0010u8][..]); let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0010u8][..]);
buf.extend(&[1u8, 1u8]); buf.extend([1u8, 1u8]);
assert!(Parser::parse(&mut buf, true, 1).is_err()); assert!(Parser::parse(&mut buf, true, 1).is_err());
@ -340,9 +340,9 @@ mod tests {
fn test_parse_frame_max_size_recoverability() { fn test_parse_frame_max_size_recoverability() {
let mut buf = BytesMut::new(); let mut buf = BytesMut::new();
// The first text frame with length == 2, payload doesn't matter. // The first text frame with length == 2, payload doesn't matter.
buf.extend(&[0b0000_0001u8, 0b0000_0010u8, 0b0000_0000u8, 0b0000_0000u8]); buf.extend([0b0000_0001u8, 0b0000_0010u8, 0b0000_0000u8, 0b0000_0000u8]);
// Next binary frame with length == 2 and payload == `[0x1111_1111u8, 0x1111_1111u8]`. // Next binary frame with length == 2 and payload == `[0x1111_1111u8, 0x1111_1111u8]`.
buf.extend(&[0b0000_0010u8, 0b0000_0010u8, 0b1111_1111u8, 0b1111_1111u8]); buf.extend([0b0000_0010u8, 0b0000_0010u8, 0b1111_1111u8, 0b1111_1111u8]);
assert_eq!(buf.len(), 8); assert_eq!(buf.len(), 8);
assert!(matches!( assert!(matches!(

View File

@ -244,7 +244,7 @@ pub fn hash_key(key: &[u8]) -> [u8; 28] {
}; };
let mut hash_b64 = [0; 28]; let mut hash_b64 = [0; 28];
let n = base64::encode_config_slice(&hash, base64::STANDARD, &mut hash_b64); let n = base64::encode_config_slice(hash, base64::STANDARD, &mut hash_b64);
assert_eq!(n, 28); assert_eq!(n, 28);
hash_b64 hash_b64

View File

@ -41,7 +41,7 @@ where
let body = stream.as_mut(); let body = stream.as_mut();
match ready!(body.poll_next(cx)) { match ready!(body.poll_next(cx)) {
Some(Ok(bytes)) => buf.extend_from_slice(&*bytes), Some(Ok(bytes)) => buf.extend_from_slice(&bytes),
None => return Poll::Ready(Ok(())), None => return Poll::Ready(Ok(())),
Some(Err(err)) => return Poll::Ready(Err(err)), Some(Err(err)) => return Poll::Ready(Err(err)),
} }

View File

@ -289,10 +289,8 @@ impl InnerMultipart {
match self.state { match self.state {
// read until first boundary // read until first boundary
InnerState::FirstBoundary => { InnerState::FirstBoundary => {
match InnerMultipart::skip_until_boundary( match InnerMultipart::skip_until_boundary(&mut payload, &self.boundary)?
&mut *payload, {
&self.boundary,
)? {
Some(eof) => { Some(eof) => {
if eof { if eof {
self.state = InnerState::Eof; self.state = InnerState::Eof;
@ -306,7 +304,7 @@ impl InnerMultipart {
} }
// read boundary // read boundary
InnerState::Boundary => { InnerState::Boundary => {
match InnerMultipart::read_boundary(&mut *payload, &self.boundary)? { match InnerMultipart::read_boundary(&mut payload, &self.boundary)? {
None => return Poll::Pending, None => return Poll::Pending,
Some(eof) => { Some(eof) => {
if eof { if eof {
@ -323,7 +321,7 @@ impl InnerMultipart {
// read field headers for next field // read field headers for next field
if self.state == InnerState::Headers { if self.state == InnerState::Headers {
if let Some(headers) = InnerMultipart::read_headers(&mut *payload)? { if let Some(headers) = InnerMultipart::read_headers(&mut payload)? {
self.state = InnerState::Boundary; self.state = InnerState::Boundary;
headers headers
} else { } else {
@ -652,9 +650,9 @@ impl InnerField {
let result = if let Some(mut payload) = self.payload.as_ref().unwrap().get_mut(s) { let result = if let Some(mut payload) = self.payload.as_ref().unwrap().get_mut(s) {
if !self.eof { if !self.eof {
let res = if let Some(ref mut len) = self.length { let res = if let Some(ref mut len) = self.length {
InnerField::read_len(&mut *payload, len) InnerField::read_len(&mut payload, len)
} else { } else {
InnerField::read_stream(&mut *payload, &self.boundary) InnerField::read_stream(&mut payload, &self.boundary)
}; };
match res { match res {

View File

@ -242,6 +242,7 @@ mod tests {
use super::*; use super::*;
#[allow(clippy::needless_borrow)]
#[test] #[test]
fn deref_impls() { fn deref_impls() {
let mut foo = Path::new("/foo"); let mut foo = Path::new("/foo");

View File

@ -1503,31 +1503,31 @@ mod tests {
fn build_path_list() { fn build_path_list() {
let mut s = String::new(); let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/test"); let resource = ResourceDef::new("/user/{item1}/test");
assert!(resource.resource_path_from_iter(&mut s, &mut (&["user1"]).iter())); assert!(resource.resource_path_from_iter(&mut s, &mut ["user1"].iter()));
assert_eq!(s, "/user/user1/test"); assert_eq!(s, "/user/user1/test");
let mut s = String::new(); let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}/test"); let resource = ResourceDef::new("/user/{item1}/{item2}/test");
assert!(resource.resource_path_from_iter(&mut s, &mut (&["item", "item2"]).iter())); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter()));
assert_eq!(s, "/user/item/item2/test"); assert_eq!(s, "/user/item/item2/test");
let mut s = String::new(); let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}"); let resource = ResourceDef::new("/user/{item1}/{item2}");
assert!(resource.resource_path_from_iter(&mut s, &mut (&["item", "item2"]).iter())); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter()));
assert_eq!(s, "/user/item/item2"); assert_eq!(s, "/user/item/item2");
let mut s = String::new(); let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}/"); let resource = ResourceDef::new("/user/{item1}/{item2}/");
assert!(resource.resource_path_from_iter(&mut s, &mut (&["item", "item2"]).iter())); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter()));
assert_eq!(s, "/user/item/item2/"); assert_eq!(s, "/user/item/item2/");
let mut s = String::new(); let mut s = String::new();
assert!(!resource.resource_path_from_iter(&mut s, &mut (&["item"]).iter())); assert!(!resource.resource_path_from_iter(&mut s, &mut ["item"].iter()));
let mut s = String::new(); let mut s = String::new();
assert!(resource.resource_path_from_iter(&mut s, &mut (&["item", "item2"]).iter())); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter()));
assert_eq!(s, "/user/item/item2/"); assert_eq!(s, "/user/item/item2/");
assert!(!resource.resource_path_from_iter(&mut s, &mut (&["item"]).iter())); assert!(!resource.resource_path_from_iter(&mut s, &mut ["item"].iter()));
let mut s = String::new(); let mut s = String::new();
assert!(resource.resource_path_from_iter(&mut s, &mut vec!["item", "item2"].iter())); assert!(resource.resource_path_from_iter(&mut s, &mut vec!["item", "item2"].iter()));
@ -1604,10 +1604,10 @@ mod tests {
let resource = ResourceDef::new("/user/{item1}*"); let resource = ResourceDef::new("/user/{item1}*");
let mut s = String::new(); let mut s = String::new();
assert!(!resource.resource_path_from_iter(&mut s, &mut (&[""; 0]).iter())); assert!(!resource.resource_path_from_iter(&mut s, &mut [""; 0].iter()));
let mut s = String::new(); let mut s = String::new();
assert!(resource.resource_path_from_iter(&mut s, &mut (&["user1"]).iter())); assert!(resource.resource_path_from_iter(&mut s, &mut ["user1"].iter()));
assert_eq!(s, "/user/user1"); assert_eq!(s, "/user/user1");
let mut s = String::new(); let mut s = String::new();

View File

@ -682,7 +682,7 @@ mod tests {
"/test", "/test",
web::get().to(|req: HttpRequest| { web::get().to(|req: HttpRequest| {
HttpResponse::Ok() HttpResponse::Ok()
.body(req.url_for("youtube", &["12345"]).unwrap().to_string()) .body(req.url_for("youtube", ["12345"]).unwrap().to_string())
}), }),
), ),
) )

View File

@ -173,7 +173,7 @@ impl AppInitServiceState {
#[inline] #[inline]
pub(crate) fn rmap(&self) -> &ResourceMap { pub(crate) fn rmap(&self) -> &ResourceMap {
&*self.rmap &self.rmap
} }
#[inline] #[inline]

View File

@ -344,7 +344,7 @@ mod tests {
"/test", "/test",
web::get().to(|req: HttpRequest| { web::get().to(|req: HttpRequest| {
HttpResponse::Ok() HttpResponse::Ok()
.body(req.url_for("youtube", &["12345"]).unwrap().to_string()) .body(req.url_for("youtube", ["12345"]).unwrap().to_string())
}), }),
), ),
) )

View File

@ -176,7 +176,7 @@ impl str::FromStr for CacheDirective {
_ => match s.find('=') { _ => match s.find('=') {
Some(idx) if idx + 1 < s.len() => { Some(idx) if idx + 1 < s.len() => {
match (&s[..idx], (&s[idx + 1..]).trim_matches('"')) { match (&s[..idx], s[idx + 1..].trim_matches('"')) {
("max-age", secs) => secs.parse().map(MaxAge).map_err(Some), ("max-age", secs) => secs.parse().map(MaxAge).map_err(Some),
("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some), ("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some), ("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),

View File

@ -219,7 +219,7 @@ impl HttpRequest {
/// for urls that do not contain variable parts. /// for urls that do not contain variable parts.
pub fn url_for_static(&self, name: &str) -> Result<url::Url, UrlGenerationError> { pub fn url_for_static(&self, name: &str) -> Result<url::Url, UrlGenerationError> {
const NO_PARAMS: [&str; 0] = []; const NO_PARAMS: [&str; 0] = [];
self.url_for(name, &NO_PARAMS) self.url_for(name, NO_PARAMS)
} }
/// Get a reference to a `ResourceMap` of current application. /// Get a reference to a `ResourceMap` of current application.
@ -306,7 +306,7 @@ impl HttpRequest {
#[inline] #[inline]
fn app_state(&self) -> &AppInitServiceState { fn app_state(&self) -> &AppInitServiceState {
&*self.inner.app_state &self.inner.app_state
} }
/// Load request cookies. /// Load request cookies.
@ -583,14 +583,14 @@ mod tests {
.to_http_request(); .to_http_request();
assert_eq!( assert_eq!(
req.url_for("unknown", &["test"]), req.url_for("unknown", ["test"]),
Err(UrlGenerationError::ResourceNotFound) Err(UrlGenerationError::ResourceNotFound)
); );
assert_eq!( assert_eq!(
req.url_for("index", &["test"]), req.url_for("index", ["test"]),
Err(UrlGenerationError::NotEnoughElements) Err(UrlGenerationError::NotEnoughElements)
); );
let url = req.url_for("index", &["test", "html"]); let url = req.url_for("index", ["test", "html"]);
assert_eq!( assert_eq!(
url.ok().unwrap().as_str(), url.ok().unwrap().as_str(),
"http://www.rust-lang.org/user/test.html" "http://www.rust-lang.org/user/test.html"
@ -646,7 +646,7 @@ mod tests {
rmap.add(&mut rdef, None); rmap.add(&mut rdef, None);
let req = TestRequest::default().rmap(rmap).to_http_request(); let req = TestRequest::default().rmap(rmap).to_http_request();
let url = req.url_for("youtube", &["oHg5SJYRHA0"]); let url = req.url_for("youtube", ["oHg5SJYRHA0"]);
assert_eq!( assert_eq!(
url.ok().unwrap().as_str(), url.ok().unwrap().as_str(),
"https://youtube.com/watch/oHg5SJYRHA0" "https://youtube.com/watch/oHg5SJYRHA0"

View File

@ -457,7 +457,7 @@ mod tests {
assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_body_eq!(res, br#"["v1","v2","v3"]"#); assert_body_eq!(res, br#"["v1","v2","v3"]"#);
let res = HttpResponse::Ok().json(&["v1", "v2", "v3"]); let res = HttpResponse::Ok().json(["v1", "v2", "v3"]);
let ct = res.headers().get(CONTENT_TYPE).unwrap(); let ct = res.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_body_eq!(res, br#"["v1","v2","v3"]"#); assert_body_eq!(res, br#"["v1","v2","v3"]"#);

View File

@ -449,12 +449,12 @@ mod tests {
let req = req.to_http_request(); let req = req.to_http_request();
let url = rmap let url = rmap
.url_for(&req, "post", &["u123", "foobar"]) .url_for(&req, "post", ["u123", "foobar"])
.unwrap() .unwrap()
.to_string(); .to_string();
assert_eq!(url, "http://localhost:8888/user/u123/post/foobar"); assert_eq!(url, "http://localhost:8888/user/u123/post/foobar");
assert!(rmap.url_for(&req, "missing", &["u123"]).is_err()); assert!(rmap.url_for(&req, "missing", ["u123"]).is_err());
} }
#[test] #[test]
@ -490,7 +490,7 @@ mod tests {
assert_eq!(url.path(), OUTPUT); assert_eq!(url.path(), OUTPUT);
assert!(rmap.url_for(&req, "external.2", INPUT).is_err()); assert!(rmap.url_for(&req, "external.2", INPUT).is_err());
assert!(rmap.url_for(&req, "external.2", &[""]).is_err()); assert!(rmap.url_for(&req, "external.2", [""]).is_err());
} }
#[test] #[test]
@ -524,7 +524,7 @@ mod tests {
let req = req.to_http_request(); let req = req.to_http_request();
assert_eq!( assert_eq!(
rmap.url_for(&req, "duck", &["abcd"]).unwrap().to_string(), rmap.url_for(&req, "duck", ["abcd"]).unwrap().to_string(),
"https://duck.com/abcd" "https://duck.com/abcd"
); );
} }
@ -552,9 +552,9 @@ mod tests {
let req = crate::test::TestRequest::default().to_http_request(); let req = crate::test::TestRequest::default().to_http_request();
let url = rmap.url_for(&req, "nested", &[""; 0]).unwrap().to_string(); let url = rmap.url_for(&req, "nested", [""; 0]).unwrap().to_string();
assert_eq!(url, "http://localhost:8080/bar/nested"); assert_eq!(url, "http://localhost:8080/bar/nested");
assert!(rmap.url_for(&req, "missing", &["u123"]).is_err()); assert!(rmap.url_for(&req, "missing", ["u123"]).is_err());
} }
} }

View File

@ -1133,7 +1133,7 @@ mod tests {
"/", "/",
web::get().to(|req: HttpRequest| { web::get().to(|req: HttpRequest| {
HttpResponse::Ok() HttpResponse::Ok()
.body(req.url_for("youtube", &["xxxxxx"]).unwrap().to_string()) .body(req.url_for("youtube", ["xxxxxx"]).unwrap().to_string())
}), }),
); );
})); }));
@ -1152,8 +1152,7 @@ mod tests {
let srv = init_service(App::new().service(web::scope("/a").service( let srv = init_service(App::new().service(web::scope("/a").service(
web::scope("/b").service(web::resource("/c/{stuff}").name("c").route( web::scope("/b").service(web::resource("/c/{stuff}").name("c").route(
web::get().to(|req: HttpRequest| { web::get().to(|req: HttpRequest| {
HttpResponse::Ok() HttpResponse::Ok().body(format!("{}", req.url_for("c", ["12345"]).unwrap()))
.body(format!("{}", req.url_for("c", &["12345"]).unwrap()))
}), }),
)), )),
))) )))

View File

@ -97,7 +97,7 @@ where
type Target = ConnectionPoolInnerPriv<Io>; type Target = ConnectionPoolInnerPriv<Io>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&*self.0 &self.0
} }
} }

View File

@ -321,7 +321,7 @@ impl WebsocketsRequest {
// Generate a random key for the `Sec-WebSocket-Key` header which is a base64-encoded // Generate a random key for the `Sec-WebSocket-Key` header which is a base64-encoded
// (see RFC 4648 §4) value that, when decoded, is 16 bytes in length (RFC 6455 §1.3). // (see RFC 4648 §4) value that, when decoded, is 16 bytes in length (RFC 6455 §1.3).
let sec_key: [u8; 16] = rand::random(); let sec_key: [u8; 16] = rand::random();
let key = base64::encode(&sec_key); let key = base64::encode(sec_key);
self.head.headers.insert( self.head.headers.insert(
header::SEC_WEBSOCKET_KEY, header::SEC_WEBSOCKET_KEY,
@ -513,7 +513,7 @@ mod tests {
.origin("test-origin") .origin("test-origin")
.max_frame_size(100) .max_frame_size(100)
.server_mode() .server_mode()
.protocols(&["v1", "v2"]) .protocols(["v1", "v2"])
.set_header_if_none(header::CONTENT_TYPE, "json") .set_header_if_none(header::CONTENT_TYPE, "json")
.set_header_if_none(header::CONTENT_TYPE, "text") .set_header_if_none(header::CONTENT_TYPE, "text")
.cookie(Cookie::build("cookie1", "value1").finish()); .cookie(Cookie::build("cookie1", "value1").finish());

View File

@ -707,8 +707,7 @@ async fn client_cookie_handling() {
async move { async move {
// Check cookies were sent correctly // Check cookies were sent correctly
let res: Result<(), Error> = req req.cookie("cookie1")
.cookie("cookie1")
.ok_or(()) .ok_or(())
.and_then(|c1| { .and_then(|c1| {
if c1.value() == "value1" { if c1.value() == "value1" {
@ -725,16 +724,10 @@ async fn client_cookie_handling() {
Err(()) Err(())
} }
}) })
.map_err(|_| Error::from(IoError::from(ErrorKind::NotFound))); .map_err(|_| Error::from(IoError::from(ErrorKind::NotFound)))?;
if let Err(e) = res {
Err(e)
} else {
// Send some cookies back // Send some cookies back
Ok::<_, Error>( Ok::<_, Error>(HttpResponse::Ok().cookie(cookie1).cookie(cookie2).finish())
HttpResponse::Ok().cookie(cookie1).cookie(cookie2).finish(),
)
}
} }
}), }),
) )