diff --git a/Cargo.toml b/Cargo.toml index a9eeafcfd3..61d7e3d234 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,7 @@ todo = "warn" uninlined_format_args = "warn" unnested_or_patterns = "warn" unused_self = "warn" +use_self = "warn" verbose_file_reads = "warn" # configuration for https://github.com/crate-ci/typos diff --git a/axum-core/src/extract/option.rs b/axum-core/src/extract/option.rs index c537e72187..fcedbe9808 100644 --- a/axum-core/src/extract/option.rs +++ b/axum-core/src/extract/option.rs @@ -42,6 +42,7 @@ where { type Rejection = T::Rejection; + #[allow(clippy::use_self)] fn from_request_parts( parts: &mut Parts, state: &S, @@ -57,6 +58,7 @@ where { type Rejection = T::Rejection; + #[allow(clippy::use_self)] async fn from_request(req: Request, state: &S) -> Result, Self::Rejection> { T::from_request(req, state).await } diff --git a/axum-core/src/extract/request_parts.rs b/axum-core/src/extract/request_parts.rs index b2a5c14aa8..498b1edfcb 100644 --- a/axum-core/src/extract/request_parts.rs +++ b/axum-core/src/extract/request_parts.rs @@ -73,6 +73,7 @@ where async fn from_request(req: Request, _: &S) -> Result { let mut body = req.into_limited_body(); + #[allow(clippy::use_self)] let mut bytes = BytesMut::new(); body_to_bytes_mut(&mut body, &mut bytes).await?; Ok(bytes) @@ -128,6 +129,7 @@ where } })?; + #[allow(clippy::use_self)] let string = String::from_utf8(bytes.into()).map_err(InvalidUtf8::from_err)?; Ok(string) diff --git a/axum-extra/src/either.rs b/axum-extra/src/either.rs index 5d0e33eb7c..9f426c951d 100755 --- a/axum-extra/src/either.rs +++ b/axum-extra/src/either.rs @@ -283,8 +283,8 @@ where fn layer(&self, inner: S) -> Self::Service { match self { - Either::E1(layer) => Either::E1(layer.layer(inner)), - Either::E2(layer) => Either::E2(layer.layer(inner)), + Self::E1(layer) => Either::E1(layer.layer(inner)), + Self::E2(layer) => Either::E2(layer.layer(inner)), } } } @@ -300,15 +300,15 @@ where fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { match self { - Either::E1(inner) => inner.poll_ready(cx), - Either::E2(inner) => inner.poll_ready(cx), + Self::E1(inner) => inner.poll_ready(cx), + Self::E2(inner) => inner.poll_ready(cx), } } fn call(&mut self, req: R) -> Self::Future { match self { - Either::E1(inner) => futures_util::future::Either::Left(inner.call(req)), - Either::E2(inner) => futures_util::future::Either::Right(inner.call(req)), + Self::E1(inner) => futures_util::future::Either::Left(inner.call(req)), + Self::E2(inner) => futures_util::future::Either::Right(inner.call(req)), } } } diff --git a/axum-extra/src/extract/cookie/mod.rs b/axum-extra/src/extract/cookie/mod.rs index 50fa6031ac..a8734335e8 100644 --- a/axum-extra/src/extract/cookie/mod.rs +++ b/axum-extra/src/extract/cookie/mod.rs @@ -321,13 +321,13 @@ mod tests { } impl FromRef for Key { - fn from_ref(state: &AppState) -> Key { + fn from_ref(state: &AppState) -> Self { state.key.clone() } } impl FromRef for CustomKey { - fn from_ref(state: &AppState) -> CustomKey { + fn from_ref(state: &AppState) -> Self { state.custom_key.clone() } } diff --git a/axum-extra/src/extract/cookie/private.rs b/axum-extra/src/extract/cookie/private.rs index f852b8c4ba..841acb7484 100644 --- a/axum-extra/src/extract/cookie/private.rs +++ b/axum-extra/src/extract/cookie/private.rs @@ -136,7 +136,7 @@ where key, _marker: _, } = PrivateCookieJar::from_headers(&parts.headers, key); - Ok(PrivateCookieJar { + Ok(Self { jar, key, _marker: PhantomData, diff --git a/axum-extra/src/extract/cookie/signed.rs b/axum-extra/src/extract/cookie/signed.rs index 92bf917145..3120674417 100644 --- a/axum-extra/src/extract/cookie/signed.rs +++ b/axum-extra/src/extract/cookie/signed.rs @@ -153,7 +153,7 @@ where key, _marker: _, } = SignedCookieJar::from_headers(&parts.headers, key); - Ok(SignedCookieJar { + Ok(Self { jar, key, _marker: PhantomData, diff --git a/axum-extra/src/extract/host.rs b/axum-extra/src/extract/host.rs index e9eb91c5be..0f33a4ab02 100644 --- a/axum-extra/src/extract/host.rs +++ b/axum-extra/src/extract/host.rs @@ -36,7 +36,7 @@ where async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { parts - .extract::>() + .extract::>() .await .ok() .flatten() @@ -55,7 +55,7 @@ where _state: &S, ) -> Result, Self::Rejection> { if let Some(host) = parse_forwarded(&parts.headers) { - return Ok(Some(Host(host.to_owned()))); + return Ok(Some(Self(host.to_owned()))); } if let Some(host) = parts @@ -63,7 +63,7 @@ where .get(X_FORWARDED_HOST_HEADER_KEY) .and_then(|host| host.to_str().ok()) { - return Ok(Some(Host(host.to_owned()))); + return Ok(Some(Self(host.to_owned()))); } if let Some(host) = parts @@ -71,11 +71,11 @@ where .get(http::header::HOST) .and_then(|host| host.to_str().ok()) { - return Ok(Some(Host(host.to_owned()))); + return Ok(Some(Self(host.to_owned()))); } if let Some(authority) = parts.uri.authority() { - return Ok(Some(Host(parse_authority(authority).to_owned()))); + return Ok(Some(Self(parse_authority(authority).to_owned()))); } Ok(None) diff --git a/axum-extra/src/extract/query.rs b/axum-extra/src/extract/query.rs index 72bf2f4703..3b0330acfb 100644 --- a/axum-extra/src/extract/query.rs +++ b/axum-extra/src/extract/query.rs @@ -91,7 +91,7 @@ where serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes())); let value = serde_path_to_error::deserialize(deserializer) .map_err(FailedToDeserializeQueryString::from_err)?; - Ok(Query(value)) + Ok(Self(value)) } } @@ -170,9 +170,9 @@ where serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes())); let value = serde_path_to_error::deserialize(deserializer) .map_err(FailedToDeserializeQueryString::from_err)?; - Ok(OptionalQuery(Some(value))) + Ok(Self(Some(value))) } else { - Ok(OptionalQuery(None)) + Ok(Self(None)) } } } diff --git a/axum-extra/src/extract/scheme.rs b/axum-extra/src/extract/scheme.rs index b20e9cf205..3634bb262f 100644 --- a/axum-extra/src/extract/scheme.rs +++ b/axum-extra/src/extract/scheme.rs @@ -38,7 +38,7 @@ where async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { // Within Forwarded header if let Some(scheme) = parse_forwarded(&parts.headers) { - return Ok(Scheme(scheme.to_owned())); + return Ok(Self(scheme.to_owned())); } // X-Forwarded-Proto @@ -47,12 +47,12 @@ where .get(X_FORWARDED_PROTO_HEADER_KEY) .and_then(|scheme| scheme.to_str().ok()) { - return Ok(Scheme(scheme.to_owned())); + return Ok(Self(scheme.to_owned())); } // From parts of an HTTP/2 request if let Some(scheme) = parts.uri.scheme_str() { - return Ok(Scheme(scheme.to_owned())); + return Ok(Self(scheme.to_owned())); } Err(SchemeMissing) diff --git a/axum-extra/src/extract/with_rejection.rs b/axum-extra/src/extract/with_rejection.rs index c093f6fa47..ee9906682a 100644 --- a/axum-extra/src/extract/with_rejection.rs +++ b/axum-extra/src/extract/with_rejection.rs @@ -119,7 +119,7 @@ where async fn from_request(req: Request, state: &S) -> Result { let extractor = E::from_request(req, state).await?; - Ok(WithRejection(extractor, PhantomData)) + Ok(Self(extractor, PhantomData)) } } @@ -133,7 +133,7 @@ where async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { let extractor = E::from_request_parts(parts, state).await?; - Ok(WithRejection(extractor, PhantomData)) + Ok(Self(extractor, PhantomData)) } } @@ -188,7 +188,7 @@ mod tests { impl From<()> for TestRejection { fn from(_: ()) -> Self { - TestRejection + Self } } diff --git a/axum-extra/src/protobuf.rs b/axum-extra/src/protobuf.rs index fb63c7a41c..260de04114 100644 --- a/axum-extra/src/protobuf.rs +++ b/axum-extra/src/protobuf.rs @@ -109,7 +109,7 @@ where .aggregate(); match T::decode(&mut buf) { - Ok(value) => Ok(Protobuf(value)), + Ok(value) => Ok(Self(value)), Err(err) => Err(ProtobufDecodeError::from_err(err).into()), } } diff --git a/axum-extra/src/response/multiple.rs b/axum-extra/src/response/multiple.rs index 390ef3e726..ddc6293beb 100644 --- a/axum-extra/src/response/multiple.rs +++ b/axum-extra/src/response/multiple.rs @@ -25,7 +25,7 @@ impl MultipartForm { /// let form = MultipartForm::with_parts(parts); /// ``` pub fn with_parts(parts: Vec) -> Self { - MultipartForm { parts } + Self { parts } } } diff --git a/axum-macros/src/debug_handler.rs b/axum-macros/src/debug_handler.rs index 73dd9f23d9..63151575e3 100644 --- a/axum-macros/src/debug_handler.rs +++ b/axum-macros/src/debug_handler.rs @@ -97,8 +97,8 @@ pub(crate) enum FunctionKind { impl fmt::Display for FunctionKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - FunctionKind::Handler => f.write_str("handler"), - FunctionKind::Middleware => f.write_str("middleware"), + Self::Handler => f.write_str("handler"), + Self::Middleware => f.write_str("middleware"), } } } @@ -106,8 +106,8 @@ impl fmt::Display for FunctionKind { impl FunctionKind { fn name_uppercase_plural(&self) -> &'static str { match self { - FunctionKind::Handler => "Handlers", - FunctionKind::Middleware => "Middleware", + Self::Handler => "Handlers", + Self::Middleware => "Middleware", } } } diff --git a/axum-macros/src/from_request/mod.rs b/axum-macros/src/from_request/mod.rs index 3838636597..451ba9bfb1 100644 --- a/axum-macros/src/from_request/mod.rs +++ b/axum-macros/src/from_request/mod.rs @@ -21,8 +21,8 @@ pub(crate) enum Trait { impl Trait { fn via_marker_type(&self) -> Option { match self { - Trait::FromRequest => Some(parse_quote!(M)), - Trait::FromRequestParts => None, + Self::FromRequest => Some(parse_quote!(M)), + Self::FromRequestParts => None, } } } @@ -30,8 +30,8 @@ impl Trait { impl fmt::Display for Trait { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Trait::FromRequest => f.write_str("FromRequest"), - Trait::FromRequestParts => f.write_str("FromRequestParts"), + Self::FromRequest => f.write_str("FromRequest"), + Self::FromRequestParts => f.write_str("FromRequestParts"), } } } @@ -50,9 +50,9 @@ impl State { /// ``` fn impl_generics(&self) -> impl Iterator { match self { - State::Default(inner) => Some(inner.clone()), - State::Custom(_) => None, - State::CannotInfer => Some(parse_quote!(S)), + Self::Default(inner) => Some(inner.clone()), + Self::Custom(_) => None, + Self::CannotInfer => Some(parse_quote!(S)), } .into_iter() } @@ -63,18 +63,18 @@ impl State { /// ``` fn trait_generics(&self) -> impl Iterator { match self { - State::Default(inner) | State::Custom(inner) => iter::once(inner.clone()), - State::CannotInfer => iter::once(parse_quote!(S)), + Self::Default(inner) | Self::Custom(inner) => iter::once(inner.clone()), + Self::CannotInfer => iter::once(parse_quote!(S)), } } fn bounds(&self) -> TokenStream { match self { - State::Custom(_) => quote! {}, - State::Default(inner) => quote! { + Self::Custom(_) => quote! {}, + Self::Default(inner) => quote! { #inner: ::std::marker::Send + ::std::marker::Sync, }, - State::CannotInfer => quote! { + Self::CannotInfer => quote! { S: ::std::marker::Send + ::std::marker::Sync, }, } @@ -84,8 +84,8 @@ impl State { impl ToTokens for State { fn to_tokens(&self, tokens: &mut TokenStream) { match self { - State::Custom(inner) | State::Default(inner) => inner.to_tokens(tokens), - State::CannotInfer => quote! { S }.to_tokens(tokens), + Self::Custom(inner) | Self::Default(inner) => inner.to_tokens(tokens), + Self::CannotInfer => quote! { S }.to_tokens(tokens), } } } diff --git a/axum-macros/src/with_position.rs b/axum-macros/src/with_position.rs index e064a3f01e..b5c1a60922 100644 --- a/axum-macros/src/with_position.rs +++ b/axum-macros/src/with_position.rs @@ -40,8 +40,8 @@ impl WithPosition where I: Iterator, { - pub(crate) fn new(iter: impl IntoIterator) -> WithPosition { - WithPosition { + pub(crate) fn new(iter: impl IntoIterator) -> Self { + Self { handled_first: false, peekable: iter.into_iter().fuse().peekable(), } @@ -72,7 +72,7 @@ pub(crate) enum Position { impl Position { pub(crate) fn into_inner(self) -> T { match self { - Position::First(x) | Position::Middle(x) | Position::Last(x) | Position::Only(x) => x, + Self::First(x) | Self::Middle(x) | Self::Last(x) | Self::Only(x) => x, } } } diff --git a/axum/src/extract/connect_info.rs b/axum/src/extract/connect_info.rs index 2c7866f9f6..c0d471d6f9 100644 --- a/axum/src/extract/connect_info.rs +++ b/axum/src/extract/connect_info.rs @@ -105,8 +105,8 @@ const _: () = { } }; -impl Connected for SocketAddr { - fn connect_info(remote_addr: SocketAddr) -> Self { +impl Connected for SocketAddr { + fn connect_info(remote_addr: Self) -> Self { remote_addr } } diff --git a/axum/src/extract/original_uri.rs b/axum/src/extract/original_uri.rs index 35364281ba..b5dbb58347 100644 --- a/axum/src/extract/original_uri.rs +++ b/axum/src/extract/original_uri.rs @@ -76,7 +76,7 @@ where async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { let uri = Extension::::from_request_parts(parts, state) .await - .unwrap_or_else(|_| Extension(OriginalUri(parts.uri.clone()))) + .unwrap_or_else(|_| Extension(Self(parts.uri.clone()))) .0; Ok(uri) } diff --git a/axum/src/extract/path/mod.rs b/axum/src/extract/path/mod.rs index f37fff4dfb..9fd0837eb6 100644 --- a/axum/src/extract/path/mod.rs +++ b/axum/src/extract/path/mod.rs @@ -183,7 +183,7 @@ where } match T::deserialize(de::PathDeserializer::new(get_params(parts)?)) { - Ok(val) => Ok(Path(val)), + Ok(val) => Ok(Self(val)), Err(e) => Err(failed_to_deserialize_path_params(e)), } } @@ -356,9 +356,9 @@ pub enum ErrorKind { impl fmt::Display for ErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ErrorKind::Message(error) => error.fmt(f), - ErrorKind::InvalidUtf8InPathParam { key } => write!(f, "Invalid UTF-8 in `{key}`"), - ErrorKind::WrongNumberOfParameters { got, expected } => { + Self::Message(error) => error.fmt(f), + Self::InvalidUtf8InPathParam { key } => write!(f, "Invalid UTF-8 in `{key}`"), + Self::WrongNumberOfParameters { got, expected } => { write!( f, "Wrong number of path arguments for `Path`. Expected {expected} but got {got}" @@ -370,8 +370,8 @@ impl fmt::Display for ErrorKind { Ok(()) } - ErrorKind::UnsupportedType { name } => write!(f, "Unsupported type `{name}`"), - ErrorKind::ParseErrorAtKey { + Self::UnsupportedType { name } => write!(f, "Unsupported type `{name}`"), + Self::ParseErrorAtKey { key, value, expected_type, @@ -379,11 +379,11 @@ impl fmt::Display for ErrorKind { f, "Cannot parse `{key}` with value `{value}` to a `{expected_type}`" ), - ErrorKind::ParseError { + Self::ParseError { value, expected_type, } => write!(f, "Cannot parse `{value}` to a `{expected_type}`"), - ErrorKind::ParseErrorAtIndex { + Self::ParseErrorAtIndex { index, value, expected_type, @@ -391,7 +391,7 @@ impl fmt::Display for ErrorKind { f, "Cannot parse value at index {index} with value `{value}` to a `{expected_type}`" ), - ErrorKind::DeserializeError { + Self::DeserializeError { key, value, message, @@ -766,7 +766,7 @@ mod tests { D: serde::Deserializer<'de>, { let s = <&str as serde::Deserialize>::deserialize(deserializer)?; - Ok(Param(s.to_owned())) + Ok(Self(s.to_owned())) } } diff --git a/axum/src/extract/query.rs b/axum/src/extract/query.rs index 58b7d366e8..b06c7f3e53 100644 --- a/axum/src/extract/query.rs +++ b/axum/src/extract/query.rs @@ -91,7 +91,7 @@ where serde_urlencoded::Deserializer::new(form_urlencoded::parse(query.as_bytes())); let params = serde_path_to_error::deserialize(deserializer) .map_err(FailedToDeserializeQueryString::from_err)?; - Ok(Query(params)) + Ok(Self(params)) } } diff --git a/axum/src/extract/ws.rs b/axum/src/extract/ws.rs index 94a6703903..a7834bd03f 100644 --- a/axum/src/extract/ws.rs +++ b/axum/src/extract/ws.rs @@ -832,49 +832,49 @@ impl Message { } /// Create a new text WebSocket message from a stringable. - pub fn text(string: S) -> Message + pub fn text(string: S) -> Self where S: Into, { - Message::Text(string.into()) + Self::Text(string.into()) } /// Create a new binary WebSocket message by converting to `Bytes`. - pub fn binary(bin: B) -> Message + pub fn binary(bin: B) -> Self where B: Into, { - Message::Binary(bin.into()) + Self::Binary(bin.into()) } } impl From for Message { fn from(string: String) -> Self { - Message::Text(string.into()) + Self::Text(string.into()) } } impl<'s> From<&'s str> for Message { fn from(string: &'s str) -> Self { - Message::Text(string.into()) + Self::Text(string.into()) } } impl<'b> From<&'b [u8]> for Message { fn from(data: &'b [u8]) -> Self { - Message::Binary(Bytes::copy_from_slice(data)) + Self::Binary(Bytes::copy_from_slice(data)) } } impl From for Message { fn from(data: Bytes) -> Self { - Message::Binary(data) + Self::Binary(data) } } impl From> for Message { fn from(data: Vec) -> Self { - Message::Binary(data.into()) + Self::Binary(data.into()) } } diff --git a/axum/src/form.rs b/axum/src/form.rs index dabfb65332..eb499def73 100644 --- a/axum/src/form.rs +++ b/axum/src/form.rs @@ -95,7 +95,7 @@ where } }, )?; - Ok(Form(value)) + Ok(Self(value)) } Err(RawFormRejection::BytesRejection(r)) => Err(FormRejection::BytesRejection(r)), Err(RawFormRejection::InvalidFormContentType(r)) => { diff --git a/axum/src/handler/service.rs b/axum/src/handler/service.rs index 2090051978..1bfdeb4ecb 100644 --- a/axum/src/handler/service.rs +++ b/axum/src/handler/service.rs @@ -60,7 +60,7 @@ impl HandlerService { /// ``` /// /// [`MakeService`]: tower::make::MakeService - pub fn into_make_service(self) -> IntoMakeService> { + pub fn into_make_service(self) -> IntoMakeService { IntoMakeService::new(self) } @@ -101,9 +101,7 @@ impl HandlerService { /// [`MakeService`]: tower::make::MakeService /// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info #[cfg(feature = "tokio")] - pub fn into_make_service_with_connect_info( - self, - ) -> IntoMakeServiceWithConnectInfo, C> { + pub fn into_make_service_with_connect_info(self) -> IntoMakeServiceWithConnectInfo { IntoMakeServiceWithConnectInfo::new(self) } } diff --git a/axum/src/json.rs b/axum/src/json.rs index 1e662cc6d1..00126f09b5 100644 --- a/axum/src/json.rs +++ b/axum/src/json.rs @@ -184,7 +184,7 @@ where let deserializer = &mut serde_json::Deserializer::from_slice(bytes); match serde_path_to_error::deserialize(deserializer) { - Ok(value) => Ok(Json(value)), + Ok(value) => Ok(Self(value)), Err(err) => Err(make_rejection(err)), } } diff --git a/axum/src/middleware/map_request.rs b/axum/src/middleware/map_request.rs index 56f250bc4d..3a90bc65ac 100644 --- a/axum/src/middleware/map_request.rs +++ b/axum/src/middleware/map_request.rs @@ -380,7 +380,7 @@ where } impl IntoMapRequestResult for Request { - fn into_map_request_result(self) -> Result, Response> { + fn into_map_request_result(self) -> Result { Ok(self) } } diff --git a/axum/src/response/sse.rs b/axum/src/response/sse.rs index 933f115e6f..d519b0d42f 100644 --- a/axum/src/response/sse.rs +++ b/axum/src/response/sse.rs @@ -63,7 +63,7 @@ impl Sse { S: TryStream + Send + 'static, S::Error: Into, { - Sse { stream } + Self { stream } } /// Configure the interval between keep-alive messages. @@ -154,12 +154,12 @@ impl Buffer { /// a new active buffer with the previous contents. fn as_mut(&mut self) -> &mut BytesMut { match self { - Buffer::Active(bytes_mut) => bytes_mut, - Buffer::Finalized(bytes) => { - *self = Buffer::Active(BytesMut::from(mem::take(bytes))); + Self::Active(bytes_mut) => bytes_mut, + Self::Finalized(bytes) => { + *self = Self::Active(BytesMut::from(mem::take(bytes))); match self { - Buffer::Active(bytes_mut) => bytes_mut, - Buffer::Finalized(_) => unreachable!(), + Self::Active(bytes_mut) => bytes_mut, + Self::Finalized(_) => unreachable!(), } } } @@ -199,7 +199,7 @@ impl Event { /// - Panics if `data` or `json_data` have already been called. /// /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data - pub fn data(mut self, data: T) -> Event + pub fn data(mut self, data: T) -> Self where T: AsRef, { @@ -226,7 +226,7 @@ impl Event { /// /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data #[cfg(feature = "json")] - pub fn json_data(mut self, data: T) -> Result + pub fn json_data(mut self, data: T) -> Result where T: serde::Serialize, { @@ -271,7 +271,7 @@ impl Event { /// /// Panics if `comment` contains any newlines or carriage returns, as they are not allowed in /// comments. - pub fn comment(mut self, comment: T) -> Event + pub fn comment(mut self, comment: T) -> Self where T: AsRef, { @@ -293,7 +293,7 @@ impl Event { /// /// - Panics if `event` contains any newlines or carriage returns. /// - Panics if this function has already been called on this event. - pub fn event(mut self, event: T) -> Event + pub fn event(mut self, event: T) -> Self where T: AsRef, { @@ -316,7 +316,7 @@ impl Event { /// # Panics /// /// Panics if this function has already been called on this event. - pub fn retry(mut self, duration: Duration) -> Event { + pub fn retry(mut self, duration: Duration) -> Self { if self.flags.contains(EventFlags::HAS_RETRY) { panic!("Called `Event::retry` multiple times"); } @@ -360,7 +360,7 @@ impl Event { /// /// - Panics if `id` contains any newlines, carriage returns or null characters. /// - Panics if this function has already been called on this event. - pub fn id(mut self, id: T) -> Event + pub fn id(mut self, id: T) -> Self where T: AsRef, { diff --git a/axum/src/routing/method_filter.rs b/axum/src/routing/method_filter.rs index 040783ec33..ddd7b21e00 100644 --- a/axum/src/routing/method_filter.rs +++ b/axum/src/routing/method_filter.rs @@ -89,15 +89,15 @@ impl TryFrom for MethodFilter { fn try_from(m: Method) -> Result { match m { - Method::CONNECT => Ok(MethodFilter::CONNECT), - Method::DELETE => Ok(MethodFilter::DELETE), - Method::GET => Ok(MethodFilter::GET), - Method::HEAD => Ok(MethodFilter::HEAD), - Method::OPTIONS => Ok(MethodFilter::OPTIONS), - Method::PATCH => Ok(MethodFilter::PATCH), - Method::POST => Ok(MethodFilter::POST), - Method::PUT => Ok(MethodFilter::PUT), - Method::TRACE => Ok(MethodFilter::TRACE), + Method::CONNECT => Ok(Self::CONNECT), + Method::DELETE => Ok(Self::DELETE), + Method::GET => Ok(Self::GET), + Method::HEAD => Ok(Self::HEAD), + Method::OPTIONS => Ok(Self::OPTIONS), + Method::PATCH => Ok(Self::PATCH), + Method::POST => Ok(Self::POST), + Method::PUT => Ok(Self::PUT), + Method::TRACE => Ok(Self::TRACE), other => Err(NoMatchingMethodFilter { method: other }), } } diff --git a/axum/src/routing/method_routing.rs b/axum/src/routing/method_routing.rs index 42e46612eb..b67f5798f3 100644 --- a/axum/src/routing/method_routing.rs +++ b/axum/src/routing/method_routing.rs @@ -571,14 +571,14 @@ enum AllowHeader { impl AllowHeader { fn merge(self, other: Self) -> Self { match (self, other) { - (AllowHeader::Skip, _) | (_, AllowHeader::Skip) => AllowHeader::Skip, - (AllowHeader::None, AllowHeader::None) => AllowHeader::None, - (AllowHeader::None, AllowHeader::Bytes(pick)) => AllowHeader::Bytes(pick), - (AllowHeader::Bytes(pick), AllowHeader::None) => AllowHeader::Bytes(pick), - (AllowHeader::Bytes(mut a), AllowHeader::Bytes(b)) => { + (Self::Skip, _) | (_, Self::Skip) => Self::Skip, + (Self::None, Self::None) => Self::None, + (Self::None, Self::Bytes(pick)) => Self::Bytes(pick), + (Self::Bytes(pick), Self::None) => Self::Bytes(pick), + (Self::Bytes(mut a), Self::Bytes(b)) => { a.extend_from_slice(b","); a.extend_from_slice(&b); - AllowHeader::Bytes(a) + Self::Bytes(a) } } } @@ -992,7 +992,7 @@ where #[doc = include_str!("../docs/method_routing/route_layer.md")] #[track_caller] - pub fn route_layer(mut self, layer: L) -> MethodRouter + pub fn route_layer(mut self, layer: L) -> Self where L: Layer> + Clone + Send + Sync + 'static, L::Service: Service + Clone + Send + Sync + 'static, @@ -1035,7 +1035,7 @@ where pub(crate) fn merge_for_path( mut self, path: Option<&str>, - other: MethodRouter, + other: Self, ) -> Result> { // written using inner functions to generate less IR fn merge_inner( @@ -1086,7 +1086,7 @@ where #[doc = include_str!("../docs/method_routing/merge.md")] #[track_caller] - pub fn merge(self, other: MethodRouter) -> Self { + pub fn merge(self, other: Self) -> Self { match self.merge_for_path(None, other) { Ok(t) => t, // not using unwrap or unwrap_or_else to get a clean panic message + the right location @@ -1254,11 +1254,9 @@ where fn with_state(self, state: &S) -> MethodEndpoint { match self { - MethodEndpoint::None => MethodEndpoint::None, - MethodEndpoint::Route(route) => MethodEndpoint::Route(route), - MethodEndpoint::BoxedHandler(handler) => { - MethodEndpoint::Route(handler.into_route(state.clone())) - } + Self::None => MethodEndpoint::None, + Self::Route(route) => MethodEndpoint::Route(route), + Self::BoxedHandler(handler) => MethodEndpoint::Route(handler.into_route(state.clone())), } } } diff --git a/axum/src/routing/mod.rs b/axum/src/routing/mod.rs index e54a00bb28..5130c62e16 100644 --- a/axum/src/routing/mod.rs +++ b/axum/src/routing/mod.rs @@ -187,7 +187,7 @@ where T::Response: IntoResponse, T::Future: Send + 'static, { - let service = match try_downcast::, _>(service) { + let service = match try_downcast::(service) { Ok(_) => { panic!( "Invalid route: `Router::route_service` cannot be used with `Router`s. \ @@ -205,7 +205,7 @@ where #[doc = include_str!("../docs/routing/nest.md")] #[doc(alias = "scope")] // Some web frameworks like actix-web use this term #[track_caller] - pub fn nest(self, path: &str, router: Router) -> Self { + pub fn nest(self, path: &str, router: Self) -> Self { if path.is_empty() || path == "/" { panic!("Nesting at the root is no longer supported. Use merge instead."); } @@ -245,9 +245,9 @@ where #[track_caller] pub fn merge(self, other: R) -> Self where - R: Into>, + R: Into, { - let other: Router = other.into(); + let other: Self = other.into(); let RouterInner { path_router, default_fallback, @@ -284,7 +284,7 @@ where } #[doc = include_str!("../docs/routing/layer.md")] - pub fn layer(self, layer: L) -> Router + pub fn layer(self, layer: L) -> Self where L: Layer + Clone + Send + Sync + 'static, L::Service: Service + Clone + Send + Sync + 'static, @@ -725,16 +725,16 @@ where fn with_state(self, state: S) -> Fallback { match self { - Fallback::Default(route) => Fallback::Default(route), - Fallback::Service(route) => Fallback::Service(route), - Fallback::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)), + Self::Default(route) => Fallback::Default(route), + Self::Service(route) => Fallback::Service(route), + Self::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)), } } fn call_with_state(self, req: Request, state: S) -> RouteFuture { match self { - Fallback::Default(route) | Fallback::Service(route) => route.oneshot_inner_owned(req), - Fallback::BoxedHandler(handler) => { + Self::Default(route) | Self::Service(route) => route.oneshot_inner_owned(req), + Self::BoxedHandler(handler) => { let route = handler.clone().into_route(state); route.oneshot_inner_owned(req) } @@ -772,7 +772,7 @@ impl Endpoint where S: Clone + Send + Sync + 'static, { - fn layer(self, layer: L) -> Endpoint + fn layer(self, layer: L) -> Self where L: Layer + Clone + Send + Sync + 'static, L::Service: Service + Clone + Send + Sync + 'static, @@ -781,10 +781,8 @@ where >::Future: Send + 'static, { match self { - Endpoint::MethodRouter(method_router) => { - Endpoint::MethodRouter(method_router.layer(layer)) - } - Endpoint::Route(route) => Endpoint::Route(route.layer(layer)), + Self::MethodRouter(method_router) => Self::MethodRouter(method_router.layer(layer)), + Self::Route(route) => Self::Route(route.layer(layer)), } } } diff --git a/axum/src/routing/path_router.rs b/axum/src/routing/path_router.rs index 263cc032f7..5999528193 100644 --- a/axum/src/routing/path_router.rs +++ b/axum/src/routing/path_router.rs @@ -143,8 +143,8 @@ where .map_err(|err| format!("Invalid route {path:?}: {err}")) } - pub(super) fn merge(&mut self, other: PathRouter) -> Result<(), Cow<'static, str>> { - let PathRouter { + pub(super) fn merge(&mut self, other: Self) -> Result<(), Cow<'static, str>> { + let Self { routes, node, prev_route_id: _, @@ -172,11 +172,11 @@ where pub(super) fn nest( &mut self, path_to_nest_at: &str, - router: PathRouter, + router: Self, ) -> Result<(), Cow<'static, str>> { let prefix = validate_nest_path(self.v7_checks, path_to_nest_at); - let PathRouter { + let Self { routes, node, prev_route_id: _, @@ -248,7 +248,7 @@ where Ok(()) } - pub(super) fn layer(self, layer: L) -> PathRouter + pub(super) fn layer(self, layer: L) -> Self where L: Layer + Clone + Send + Sync + 'static, L::Service: Service + Clone + Send + Sync + 'static, @@ -265,7 +265,7 @@ where }) .collect(); - PathRouter { + Self { routes, node: self.node, prev_route_id: self.prev_route_id, @@ -298,7 +298,7 @@ where }) .collect(); - PathRouter { + Self { routes, node: self.node, prev_route_id: self.prev_route_id, diff --git a/axum/src/routing/route.rs b/axum/src/routing/route.rs index 6cdc58a617..6730078787 100644 --- a/axum/src/routing/route.rs +++ b/axum/src/routing/route.rs @@ -59,7 +59,7 @@ impl Route { pub(crate) fn layer(self, layer: L) -> Route where - L: Layer> + Clone + Send + 'static, + L: Layer + Clone + Send + 'static, L::Service: Service + Clone + Send + Sync + 'static, >::Response: IntoResponse + 'static, >::Error: Into + 'static, diff --git a/axum/src/test_helpers/counting_cloneable_state.rs b/axum/src/test_helpers/counting_cloneable_state.rs index 762d5ce972..f428e737f6 100644 --- a/axum/src/test_helpers/counting_cloneable_state.rs +++ b/axum/src/test_helpers/counting_cloneable_state.rs @@ -18,7 +18,7 @@ impl CountingCloneableState { setup_done: AtomicBool::new(false), count: AtomicUsize::new(0), }; - CountingCloneableState { + Self { state: Arc::new(inner_state), } } @@ -47,6 +47,6 @@ impl Clone for CountingCloneableState { state.count.fetch_add(1, Ordering::SeqCst); } - CountingCloneableState { state } + Self { state } } } diff --git a/axum/src/test_helpers/test_client.rs b/axum/src/test_helpers/test_client.rs index e7ba36e95e..3891b60f0b 100644 --- a/axum/src/test_helpers/test_client.rs +++ b/axum/src/test_helpers/test_client.rs @@ -47,7 +47,7 @@ impl TestClient { .build() .unwrap(); - TestClient { client, addr } + Self { client, addr } } pub fn get(&self, url: &str) -> RequestBuilder {