style: use Self to avoid unnecessary repetition (#3396)

This commit is contained in:
Theodore Bjernhed
2025-07-04 21:10:01 +00:00
committed by GitHub
parent b8d9a3e764
commit 0f255c3c4c
33 changed files with 137 additions and 138 deletions
+1
View File
@@ -45,6 +45,7 @@ todo = "warn"
uninlined_format_args = "warn" uninlined_format_args = "warn"
unnested_or_patterns = "warn" unnested_or_patterns = "warn"
unused_self = "warn" unused_self = "warn"
use_self = "warn"
verbose_file_reads = "warn" verbose_file_reads = "warn"
# configuration for https://github.com/crate-ci/typos # configuration for https://github.com/crate-ci/typos
+2
View File
@@ -42,6 +42,7 @@ where
{ {
type Rejection = T::Rejection; type Rejection = T::Rejection;
#[allow(clippy::use_self)]
fn from_request_parts( fn from_request_parts(
parts: &mut Parts, parts: &mut Parts,
state: &S, state: &S,
@@ -57,6 +58,7 @@ where
{ {
type Rejection = T::Rejection; type Rejection = T::Rejection;
#[allow(clippy::use_self)]
async fn from_request(req: Request, state: &S) -> Result<Option<T>, Self::Rejection> { async fn from_request(req: Request, state: &S) -> Result<Option<T>, Self::Rejection> {
T::from_request(req, state).await T::from_request(req, state).await
} }
+2
View File
@@ -73,6 +73,7 @@ where
async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> { async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> {
let mut body = req.into_limited_body(); let mut body = req.into_limited_body();
#[allow(clippy::use_self)]
let mut bytes = BytesMut::new(); let mut bytes = BytesMut::new();
body_to_bytes_mut(&mut body, &mut bytes).await?; body_to_bytes_mut(&mut body, &mut bytes).await?;
Ok(bytes) Ok(bytes)
@@ -128,6 +129,7 @@ where
} }
})?; })?;
#[allow(clippy::use_self)]
let string = String::from_utf8(bytes.into()).map_err(InvalidUtf8::from_err)?; let string = String::from_utf8(bytes.into()).map_err(InvalidUtf8::from_err)?;
Ok(string) Ok(string)
+6 -6
View File
@@ -283,8 +283,8 @@ where
fn layer(&self, inner: S) -> Self::Service { fn layer(&self, inner: S) -> Self::Service {
match self { match self {
Either::E1(layer) => Either::E1(layer.layer(inner)), Self::E1(layer) => Either::E1(layer.layer(inner)),
Either::E2(layer) => Either::E2(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<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self { match self {
Either::E1(inner) => inner.poll_ready(cx), Self::E1(inner) => inner.poll_ready(cx),
Either::E2(inner) => inner.poll_ready(cx), Self::E2(inner) => inner.poll_ready(cx),
} }
} }
fn call(&mut self, req: R) -> Self::Future { fn call(&mut self, req: R) -> Self::Future {
match self { match self {
Either::E1(inner) => futures_util::future::Either::Left(inner.call(req)), Self::E1(inner) => futures_util::future::Either::Left(inner.call(req)),
Either::E2(inner) => futures_util::future::Either::Right(inner.call(req)), Self::E2(inner) => futures_util::future::Either::Right(inner.call(req)),
} }
} }
} }
+2 -2
View File
@@ -321,13 +321,13 @@ mod tests {
} }
impl FromRef<AppState> for Key { impl FromRef<AppState> for Key {
fn from_ref(state: &AppState) -> Key { fn from_ref(state: &AppState) -> Self {
state.key.clone() state.key.clone()
} }
} }
impl FromRef<AppState> for CustomKey { impl FromRef<AppState> for CustomKey {
fn from_ref(state: &AppState) -> CustomKey { fn from_ref(state: &AppState) -> Self {
state.custom_key.clone() state.custom_key.clone()
} }
} }
+1 -1
View File
@@ -136,7 +136,7 @@ where
key, key,
_marker: _, _marker: _,
} = PrivateCookieJar::from_headers(&parts.headers, key); } = PrivateCookieJar::from_headers(&parts.headers, key);
Ok(PrivateCookieJar { Ok(Self {
jar, jar,
key, key,
_marker: PhantomData, _marker: PhantomData,
+1 -1
View File
@@ -153,7 +153,7 @@ where
key, key,
_marker: _, _marker: _,
} = SignedCookieJar::from_headers(&parts.headers, key); } = SignedCookieJar::from_headers(&parts.headers, key);
Ok(SignedCookieJar { Ok(Self {
jar, jar,
key, key,
_marker: PhantomData, _marker: PhantomData,
+5 -5
View File
@@ -36,7 +36,7 @@ where
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
parts parts
.extract::<Option<Host>>() .extract::<Option<Self>>()
.await .await
.ok() .ok()
.flatten() .flatten()
@@ -55,7 +55,7 @@ where
_state: &S, _state: &S,
) -> Result<Option<Self>, Self::Rejection> { ) -> Result<Option<Self>, Self::Rejection> {
if let Some(host) = parse_forwarded(&parts.headers) { 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 if let Some(host) = parts
@@ -63,7 +63,7 @@ where
.get(X_FORWARDED_HOST_HEADER_KEY) .get(X_FORWARDED_HOST_HEADER_KEY)
.and_then(|host| host.to_str().ok()) .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 if let Some(host) = parts
@@ -71,11 +71,11 @@ where
.get(http::header::HOST) .get(http::header::HOST)
.and_then(|host| host.to_str().ok()) .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() { 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) Ok(None)
+3 -3
View File
@@ -91,7 +91,7 @@ where
serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes())); serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes()));
let value = serde_path_to_error::deserialize(deserializer) let value = serde_path_to_error::deserialize(deserializer)
.map_err(FailedToDeserializeQueryString::from_err)?; .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())); serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes()));
let value = serde_path_to_error::deserialize(deserializer) let value = serde_path_to_error::deserialize(deserializer)
.map_err(FailedToDeserializeQueryString::from_err)?; .map_err(FailedToDeserializeQueryString::from_err)?;
Ok(OptionalQuery(Some(value))) Ok(Self(Some(value)))
} else { } else {
Ok(OptionalQuery(None)) Ok(Self(None))
} }
} }
} }
+3 -3
View File
@@ -38,7 +38,7 @@ where
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
// Within Forwarded header // Within Forwarded header
if let Some(scheme) = parse_forwarded(&parts.headers) { if let Some(scheme) = parse_forwarded(&parts.headers) {
return Ok(Scheme(scheme.to_owned())); return Ok(Self(scheme.to_owned()));
} }
// X-Forwarded-Proto // X-Forwarded-Proto
@@ -47,12 +47,12 @@ where
.get(X_FORWARDED_PROTO_HEADER_KEY) .get(X_FORWARDED_PROTO_HEADER_KEY)
.and_then(|scheme| scheme.to_str().ok()) .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 // From parts of an HTTP/2 request
if let Some(scheme) = parts.uri.scheme_str() { if let Some(scheme) = parts.uri.scheme_str() {
return Ok(Scheme(scheme.to_owned())); return Ok(Self(scheme.to_owned()));
} }
Err(SchemeMissing) Err(SchemeMissing)
+3 -3
View File
@@ -119,7 +119,7 @@ where
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let extractor = E::from_request(req, state).await?; 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<Self, Self::Rejection> { async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let extractor = E::from_request_parts(parts, state).await?; 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 { impl From<()> for TestRejection {
fn from(_: ()) -> Self { fn from(_: ()) -> Self {
TestRejection Self
} }
} }
+1 -1
View File
@@ -109,7 +109,7 @@ where
.aggregate(); .aggregate();
match T::decode(&mut buf) { match T::decode(&mut buf) {
Ok(value) => Ok(Protobuf(value)), Ok(value) => Ok(Self(value)),
Err(err) => Err(ProtobufDecodeError::from_err(err).into()), Err(err) => Err(ProtobufDecodeError::from_err(err).into()),
} }
} }
+1 -1
View File
@@ -25,7 +25,7 @@ impl MultipartForm {
/// let form = MultipartForm::with_parts(parts); /// let form = MultipartForm::with_parts(parts);
/// ``` /// ```
pub fn with_parts(parts: Vec<Part>) -> Self { pub fn with_parts(parts: Vec<Part>) -> Self {
MultipartForm { parts } Self { parts }
} }
} }
+4 -4
View File
@@ -97,8 +97,8 @@ pub(crate) enum FunctionKind {
impl fmt::Display for FunctionKind { impl fmt::Display for FunctionKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
FunctionKind::Handler => f.write_str("handler"), Self::Handler => f.write_str("handler"),
FunctionKind::Middleware => f.write_str("middleware"), Self::Middleware => f.write_str("middleware"),
} }
} }
} }
@@ -106,8 +106,8 @@ impl fmt::Display for FunctionKind {
impl FunctionKind { impl FunctionKind {
fn name_uppercase_plural(&self) -> &'static str { fn name_uppercase_plural(&self) -> &'static str {
match self { match self {
FunctionKind::Handler => "Handlers", Self::Handler => "Handlers",
FunctionKind::Middleware => "Middleware", Self::Middleware => "Middleware",
} }
} }
} }
+14 -14
View File
@@ -21,8 +21,8 @@ pub(crate) enum Trait {
impl Trait { impl Trait {
fn via_marker_type(&self) -> Option<Type> { fn via_marker_type(&self) -> Option<Type> {
match self { match self {
Trait::FromRequest => Some(parse_quote!(M)), Self::FromRequest => Some(parse_quote!(M)),
Trait::FromRequestParts => None, Self::FromRequestParts => None,
} }
} }
} }
@@ -30,8 +30,8 @@ impl Trait {
impl fmt::Display for Trait { impl fmt::Display for Trait {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Trait::FromRequest => f.write_str("FromRequest"), Self::FromRequest => f.write_str("FromRequest"),
Trait::FromRequestParts => f.write_str("FromRequestParts"), Self::FromRequestParts => f.write_str("FromRequestParts"),
} }
} }
} }
@@ -50,9 +50,9 @@ impl State {
/// ``` /// ```
fn impl_generics(&self) -> impl Iterator<Item = Type> { fn impl_generics(&self) -> impl Iterator<Item = Type> {
match self { match self {
State::Default(inner) => Some(inner.clone()), Self::Default(inner) => Some(inner.clone()),
State::Custom(_) => None, Self::Custom(_) => None,
State::CannotInfer => Some(parse_quote!(S)), Self::CannotInfer => Some(parse_quote!(S)),
} }
.into_iter() .into_iter()
} }
@@ -63,18 +63,18 @@ impl State {
/// ``` /// ```
fn trait_generics(&self) -> impl Iterator<Item = Type> { fn trait_generics(&self) -> impl Iterator<Item = Type> {
match self { match self {
State::Default(inner) | State::Custom(inner) => iter::once(inner.clone()), Self::Default(inner) | Self::Custom(inner) => iter::once(inner.clone()),
State::CannotInfer => iter::once(parse_quote!(S)), Self::CannotInfer => iter::once(parse_quote!(S)),
} }
} }
fn bounds(&self) -> TokenStream { fn bounds(&self) -> TokenStream {
match self { match self {
State::Custom(_) => quote! {}, Self::Custom(_) => quote! {},
State::Default(inner) => quote! { Self::Default(inner) => quote! {
#inner: ::std::marker::Send + ::std::marker::Sync, #inner: ::std::marker::Send + ::std::marker::Sync,
}, },
State::CannotInfer => quote! { Self::CannotInfer => quote! {
S: ::std::marker::Send + ::std::marker::Sync, S: ::std::marker::Send + ::std::marker::Sync,
}, },
} }
@@ -84,8 +84,8 @@ impl State {
impl ToTokens for State { impl ToTokens for State {
fn to_tokens(&self, tokens: &mut TokenStream) { fn to_tokens(&self, tokens: &mut TokenStream) {
match self { match self {
State::Custom(inner) | State::Default(inner) => inner.to_tokens(tokens), Self::Custom(inner) | Self::Default(inner) => inner.to_tokens(tokens),
State::CannotInfer => quote! { S }.to_tokens(tokens), Self::CannotInfer => quote! { S }.to_tokens(tokens),
} }
} }
} }
+3 -3
View File
@@ -40,8 +40,8 @@ impl<I> WithPosition<I>
where where
I: Iterator, I: Iterator,
{ {
pub(crate) fn new(iter: impl IntoIterator<IntoIter = I>) -> WithPosition<I> { pub(crate) fn new(iter: impl IntoIterator<IntoIter = I>) -> Self {
WithPosition { Self {
handled_first: false, handled_first: false,
peekable: iter.into_iter().fuse().peekable(), peekable: iter.into_iter().fuse().peekable(),
} }
@@ -72,7 +72,7 @@ pub(crate) enum Position<T> {
impl<T> Position<T> { impl<T> Position<T> {
pub(crate) fn into_inner(self) -> T { pub(crate) fn into_inner(self) -> T {
match self { 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,
} }
} }
} }
+2 -2
View File
@@ -105,8 +105,8 @@ const _: () = {
} }
}; };
impl Connected<SocketAddr> for SocketAddr { impl Connected<Self> for SocketAddr {
fn connect_info(remote_addr: SocketAddr) -> Self { fn connect_info(remote_addr: Self) -> Self {
remote_addr remote_addr
} }
} }
+1 -1
View File
@@ -76,7 +76,7 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let uri = Extension::<Self>::from_request_parts(parts, state) let uri = Extension::<Self>::from_request_parts(parts, state)
.await .await
.unwrap_or_else(|_| Extension(OriginalUri(parts.uri.clone()))) .unwrap_or_else(|_| Extension(Self(parts.uri.clone())))
.0; .0;
Ok(uri) Ok(uri)
} }
+10 -10
View File
@@ -183,7 +183,7 @@ where
} }
match T::deserialize(de::PathDeserializer::new(get_params(parts)?)) { 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)), Err(e) => Err(failed_to_deserialize_path_params(e)),
} }
} }
@@ -356,9 +356,9 @@ pub enum ErrorKind {
impl fmt::Display for ErrorKind { impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
ErrorKind::Message(error) => error.fmt(f), Self::Message(error) => error.fmt(f),
ErrorKind::InvalidUtf8InPathParam { key } => write!(f, "Invalid UTF-8 in `{key}`"), Self::InvalidUtf8InPathParam { key } => write!(f, "Invalid UTF-8 in `{key}`"),
ErrorKind::WrongNumberOfParameters { got, expected } => { Self::WrongNumberOfParameters { got, expected } => {
write!( write!(
f, f,
"Wrong number of path arguments for `Path`. Expected {expected} but got {got}" "Wrong number of path arguments for `Path`. Expected {expected} but got {got}"
@@ -370,8 +370,8 @@ impl fmt::Display for ErrorKind {
Ok(()) Ok(())
} }
ErrorKind::UnsupportedType { name } => write!(f, "Unsupported type `{name}`"), Self::UnsupportedType { name } => write!(f, "Unsupported type `{name}`"),
ErrorKind::ParseErrorAtKey { Self::ParseErrorAtKey {
key, key,
value, value,
expected_type, expected_type,
@@ -379,11 +379,11 @@ impl fmt::Display for ErrorKind {
f, f,
"Cannot parse `{key}` with value `{value}` to a `{expected_type}`" "Cannot parse `{key}` with value `{value}` to a `{expected_type}`"
), ),
ErrorKind::ParseError { Self::ParseError {
value, value,
expected_type, expected_type,
} => write!(f, "Cannot parse `{value}` to a `{expected_type}`"), } => write!(f, "Cannot parse `{value}` to a `{expected_type}`"),
ErrorKind::ParseErrorAtIndex { Self::ParseErrorAtIndex {
index, index,
value, value,
expected_type, expected_type,
@@ -391,7 +391,7 @@ impl fmt::Display for ErrorKind {
f, f,
"Cannot parse value at index {index} with value `{value}` to a `{expected_type}`" "Cannot parse value at index {index} with value `{value}` to a `{expected_type}`"
), ),
ErrorKind::DeserializeError { Self::DeserializeError {
key, key,
value, value,
message, message,
@@ -766,7 +766,7 @@ mod tests {
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
{ {
let s = <&str as serde::Deserialize>::deserialize(deserializer)?; let s = <&str as serde::Deserialize>::deserialize(deserializer)?;
Ok(Param(s.to_owned())) Ok(Self(s.to_owned()))
} }
} }
+1 -1
View File
@@ -91,7 +91,7 @@ where
serde_urlencoded::Deserializer::new(form_urlencoded::parse(query.as_bytes())); serde_urlencoded::Deserializer::new(form_urlencoded::parse(query.as_bytes()));
let params = serde_path_to_error::deserialize(deserializer) let params = serde_path_to_error::deserialize(deserializer)
.map_err(FailedToDeserializeQueryString::from_err)?; .map_err(FailedToDeserializeQueryString::from_err)?;
Ok(Query(params)) Ok(Self(params))
} }
} }
+9 -9
View File
@@ -832,49 +832,49 @@ impl Message {
} }
/// Create a new text WebSocket message from a stringable. /// Create a new text WebSocket message from a stringable.
pub fn text<S>(string: S) -> Message pub fn text<S>(string: S) -> Self
where where
S: Into<Utf8Bytes>, S: Into<Utf8Bytes>,
{ {
Message::Text(string.into()) Self::Text(string.into())
} }
/// Create a new binary WebSocket message by converting to `Bytes`. /// Create a new binary WebSocket message by converting to `Bytes`.
pub fn binary<B>(bin: B) -> Message pub fn binary<B>(bin: B) -> Self
where where
B: Into<Bytes>, B: Into<Bytes>,
{ {
Message::Binary(bin.into()) Self::Binary(bin.into())
} }
} }
impl From<String> for Message { impl From<String> for Message {
fn from(string: String) -> Self { fn from(string: String) -> Self {
Message::Text(string.into()) Self::Text(string.into())
} }
} }
impl<'s> From<&'s str> for Message { impl<'s> From<&'s str> for Message {
fn from(string: &'s str) -> Self { fn from(string: &'s str) -> Self {
Message::Text(string.into()) Self::Text(string.into())
} }
} }
impl<'b> From<&'b [u8]> for Message { impl<'b> From<&'b [u8]> for Message {
fn from(data: &'b [u8]) -> Self { fn from(data: &'b [u8]) -> Self {
Message::Binary(Bytes::copy_from_slice(data)) Self::Binary(Bytes::copy_from_slice(data))
} }
} }
impl From<Bytes> for Message { impl From<Bytes> for Message {
fn from(data: Bytes) -> Self { fn from(data: Bytes) -> Self {
Message::Binary(data) Self::Binary(data)
} }
} }
impl From<Vec<u8>> for Message { impl From<Vec<u8>> for Message {
fn from(data: Vec<u8>) -> Self { fn from(data: Vec<u8>) -> Self {
Message::Binary(data.into()) Self::Binary(data.into())
} }
} }
+1 -1
View File
@@ -95,7 +95,7 @@ where
} }
}, },
)?; )?;
Ok(Form(value)) Ok(Self(value))
} }
Err(RawFormRejection::BytesRejection(r)) => Err(FormRejection::BytesRejection(r)), Err(RawFormRejection::BytesRejection(r)) => Err(FormRejection::BytesRejection(r)),
Err(RawFormRejection::InvalidFormContentType(r)) => { Err(RawFormRejection::InvalidFormContentType(r)) => {
+2 -4
View File
@@ -60,7 +60,7 @@ impl<H, T, S> HandlerService<H, T, S> {
/// ``` /// ```
/// ///
/// [`MakeService`]: tower::make::MakeService /// [`MakeService`]: tower::make::MakeService
pub fn into_make_service(self) -> IntoMakeService<HandlerService<H, T, S>> { pub fn into_make_service(self) -> IntoMakeService<Self> {
IntoMakeService::new(self) IntoMakeService::new(self)
} }
@@ -101,9 +101,7 @@ impl<H, T, S> HandlerService<H, T, S> {
/// [`MakeService`]: tower::make::MakeService /// [`MakeService`]: tower::make::MakeService
/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info /// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
#[cfg(feature = "tokio")] #[cfg(feature = "tokio")]
pub fn into_make_service_with_connect_info<C>( pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
self,
) -> IntoMakeServiceWithConnectInfo<HandlerService<H, T, S>, C> {
IntoMakeServiceWithConnectInfo::new(self) IntoMakeServiceWithConnectInfo::new(self)
} }
} }
+1 -1
View File
@@ -184,7 +184,7 @@ where
let deserializer = &mut serde_json::Deserializer::from_slice(bytes); let deserializer = &mut serde_json::Deserializer::from_slice(bytes);
match serde_path_to_error::deserialize(deserializer) { match serde_path_to_error::deserialize(deserializer) {
Ok(value) => Ok(Json(value)), Ok(value) => Ok(Self(value)),
Err(err) => Err(make_rejection(err)), Err(err) => Err(make_rejection(err)),
} }
} }
+1 -1
View File
@@ -380,7 +380,7 @@ where
} }
impl<B> IntoMapRequestResult<B> for Request<B> { impl<B> IntoMapRequestResult<B> for Request<B> {
fn into_map_request_result(self) -> Result<Request<B>, Response> { fn into_map_request_result(self) -> Result<Self, Response> {
Ok(self) Ok(self)
} }
} }
+12 -12
View File
@@ -63,7 +63,7 @@ impl<S> Sse<S> {
S: TryStream<Ok = Event> + Send + 'static, S: TryStream<Ok = Event> + Send + 'static,
S::Error: Into<BoxError>, S::Error: Into<BoxError>,
{ {
Sse { stream } Self { stream }
} }
/// Configure the interval between keep-alive messages. /// Configure the interval between keep-alive messages.
@@ -154,12 +154,12 @@ impl Buffer {
/// a new active buffer with the previous contents. /// a new active buffer with the previous contents.
fn as_mut(&mut self) -> &mut BytesMut { fn as_mut(&mut self) -> &mut BytesMut {
match self { match self {
Buffer::Active(bytes_mut) => bytes_mut, Self::Active(bytes_mut) => bytes_mut,
Buffer::Finalized(bytes) => { Self::Finalized(bytes) => {
*self = Buffer::Active(BytesMut::from(mem::take(bytes))); *self = Self::Active(BytesMut::from(mem::take(bytes)));
match self { match self {
Buffer::Active(bytes_mut) => bytes_mut, Self::Active(bytes_mut) => bytes_mut,
Buffer::Finalized(_) => unreachable!(), Self::Finalized(_) => unreachable!(),
} }
} }
} }
@@ -199,7 +199,7 @@ impl Event {
/// - Panics if `data` or `json_data` have already been called. /// - 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 /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data
pub fn data<T>(mut self, data: T) -> Event pub fn data<T>(mut self, data: T) -> Self
where where
T: AsRef<str>, T: AsRef<str>,
{ {
@@ -226,7 +226,7 @@ impl Event {
/// ///
/// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data
#[cfg(feature = "json")] #[cfg(feature = "json")]
pub fn json_data<T>(mut self, data: T) -> Result<Event, axum_core::Error> pub fn json_data<T>(mut self, data: T) -> Result<Self, axum_core::Error>
where where
T: serde::Serialize, T: serde::Serialize,
{ {
@@ -271,7 +271,7 @@ impl Event {
/// ///
/// Panics if `comment` contains any newlines or carriage returns, as they are not allowed in /// Panics if `comment` contains any newlines or carriage returns, as they are not allowed in
/// comments. /// comments.
pub fn comment<T>(mut self, comment: T) -> Event pub fn comment<T>(mut self, comment: T) -> Self
where where
T: AsRef<str>, T: AsRef<str>,
{ {
@@ -293,7 +293,7 @@ impl Event {
/// ///
/// - Panics if `event` contains any newlines or carriage returns. /// - Panics if `event` contains any newlines or carriage returns.
/// - Panics if this function has already been called on this event. /// - Panics if this function has already been called on this event.
pub fn event<T>(mut self, event: T) -> Event pub fn event<T>(mut self, event: T) -> Self
where where
T: AsRef<str>, T: AsRef<str>,
{ {
@@ -316,7 +316,7 @@ impl Event {
/// # Panics /// # Panics
/// ///
/// Panics if this function has already been called on this event. /// 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) { if self.flags.contains(EventFlags::HAS_RETRY) {
panic!("Called `Event::retry` multiple times"); 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 `id` contains any newlines, carriage returns or null characters.
/// - Panics if this function has already been called on this event. /// - Panics if this function has already been called on this event.
pub fn id<T>(mut self, id: T) -> Event pub fn id<T>(mut self, id: T) -> Self
where where
T: AsRef<str>, T: AsRef<str>,
{ {
+9 -9
View File
@@ -89,15 +89,15 @@ impl TryFrom<Method> for MethodFilter {
fn try_from(m: Method) -> Result<Self, NoMatchingMethodFilter> { fn try_from(m: Method) -> Result<Self, NoMatchingMethodFilter> {
match m { match m {
Method::CONNECT => Ok(MethodFilter::CONNECT), Method::CONNECT => Ok(Self::CONNECT),
Method::DELETE => Ok(MethodFilter::DELETE), Method::DELETE => Ok(Self::DELETE),
Method::GET => Ok(MethodFilter::GET), Method::GET => Ok(Self::GET),
Method::HEAD => Ok(MethodFilter::HEAD), Method::HEAD => Ok(Self::HEAD),
Method::OPTIONS => Ok(MethodFilter::OPTIONS), Method::OPTIONS => Ok(Self::OPTIONS),
Method::PATCH => Ok(MethodFilter::PATCH), Method::PATCH => Ok(Self::PATCH),
Method::POST => Ok(MethodFilter::POST), Method::POST => Ok(Self::POST),
Method::PUT => Ok(MethodFilter::PUT), Method::PUT => Ok(Self::PUT),
Method::TRACE => Ok(MethodFilter::TRACE), Method::TRACE => Ok(Self::TRACE),
other => Err(NoMatchingMethodFilter { method: other }), other => Err(NoMatchingMethodFilter { method: other }),
} }
} }
+12 -14
View File
@@ -571,14 +571,14 @@ enum AllowHeader {
impl AllowHeader { impl AllowHeader {
fn merge(self, other: Self) -> Self { fn merge(self, other: Self) -> Self {
match (self, other) { match (self, other) {
(AllowHeader::Skip, _) | (_, AllowHeader::Skip) => AllowHeader::Skip, (Self::Skip, _) | (_, Self::Skip) => Self::Skip,
(AllowHeader::None, AllowHeader::None) => AllowHeader::None, (Self::None, Self::None) => Self::None,
(AllowHeader::None, AllowHeader::Bytes(pick)) => AllowHeader::Bytes(pick), (Self::None, Self::Bytes(pick)) => Self::Bytes(pick),
(AllowHeader::Bytes(pick), AllowHeader::None) => AllowHeader::Bytes(pick), (Self::Bytes(pick), Self::None) => Self::Bytes(pick),
(AllowHeader::Bytes(mut a), AllowHeader::Bytes(b)) => { (Self::Bytes(mut a), Self::Bytes(b)) => {
a.extend_from_slice(b","); a.extend_from_slice(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")] #[doc = include_str!("../docs/method_routing/route_layer.md")]
#[track_caller] #[track_caller]
pub fn route_layer<L>(mut self, layer: L) -> MethodRouter<S, E> pub fn route_layer<L>(mut self, layer: L) -> Self
where where
L: Layer<Route<E>> + Clone + Send + Sync + 'static, L: Layer<Route<E>> + Clone + Send + Sync + 'static,
L::Service: Service<Request, Error = E> + Clone + Send + Sync + 'static, L::Service: Service<Request, Error = E> + Clone + Send + Sync + 'static,
@@ -1035,7 +1035,7 @@ where
pub(crate) fn merge_for_path( pub(crate) fn merge_for_path(
mut self, mut self,
path: Option<&str>, path: Option<&str>,
other: MethodRouter<S, E>, other: Self,
) -> Result<Self, Cow<'static, str>> { ) -> Result<Self, Cow<'static, str>> {
// written using inner functions to generate less IR // written using inner functions to generate less IR
fn merge_inner<S, E>( fn merge_inner<S, E>(
@@ -1086,7 +1086,7 @@ where
#[doc = include_str!("../docs/method_routing/merge.md")] #[doc = include_str!("../docs/method_routing/merge.md")]
#[track_caller] #[track_caller]
pub fn merge(self, other: MethodRouter<S, E>) -> Self { pub fn merge(self, other: Self) -> Self {
match self.merge_for_path(None, other) { match self.merge_for_path(None, other) {
Ok(t) => t, Ok(t) => t,
// not using unwrap or unwrap_or_else to get a clean panic message + the right location // not using unwrap or unwrap_or_else to get a clean panic message + the right location
@@ -1254,11 +1254,9 @@ where
fn with_state<S2>(self, state: &S) -> MethodEndpoint<S2, E> { fn with_state<S2>(self, state: &S) -> MethodEndpoint<S2, E> {
match self { match self {
MethodEndpoint::None => MethodEndpoint::None, Self::None => MethodEndpoint::None,
MethodEndpoint::Route(route) => MethodEndpoint::Route(route), Self::Route(route) => MethodEndpoint::Route(route),
MethodEndpoint::BoxedHandler(handler) => { Self::BoxedHandler(handler) => MethodEndpoint::Route(handler.into_route(state.clone())),
MethodEndpoint::Route(handler.into_route(state.clone()))
}
} }
} }
} }
+13 -15
View File
@@ -187,7 +187,7 @@ where
T::Response: IntoResponse, T::Response: IntoResponse,
T::Future: Send + 'static, T::Future: Send + 'static,
{ {
let service = match try_downcast::<Router<S>, _>(service) { let service = match try_downcast::<Self, _>(service) {
Ok(_) => { Ok(_) => {
panic!( panic!(
"Invalid route: `Router::route_service` cannot be used with `Router`s. \ "Invalid route: `Router::route_service` cannot be used with `Router`s. \
@@ -205,7 +205,7 @@ where
#[doc = include_str!("../docs/routing/nest.md")] #[doc = include_str!("../docs/routing/nest.md")]
#[doc(alias = "scope")] // Some web frameworks like actix-web use this term #[doc(alias = "scope")] // Some web frameworks like actix-web use this term
#[track_caller] #[track_caller]
pub fn nest(self, path: &str, router: Router<S>) -> Self { pub fn nest(self, path: &str, router: Self) -> Self {
if path.is_empty() || path == "/" { if path.is_empty() || path == "/" {
panic!("Nesting at the root is no longer supported. Use merge instead."); panic!("Nesting at the root is no longer supported. Use merge instead.");
} }
@@ -245,9 +245,9 @@ where
#[track_caller] #[track_caller]
pub fn merge<R>(self, other: R) -> Self pub fn merge<R>(self, other: R) -> Self
where where
R: Into<Router<S>>, R: Into<Self>,
{ {
let other: Router<S> = other.into(); let other: Self = other.into();
let RouterInner { let RouterInner {
path_router, path_router,
default_fallback, default_fallback,
@@ -284,7 +284,7 @@ where
} }
#[doc = include_str!("../docs/routing/layer.md")] #[doc = include_str!("../docs/routing/layer.md")]
pub fn layer<L>(self, layer: L) -> Router<S> pub fn layer<L>(self, layer: L) -> Self
where where
L: Layer<Route> + Clone + Send + Sync + 'static, L: Layer<Route> + Clone + Send + Sync + 'static,
L::Service: Service<Request> + Clone + Send + Sync + 'static, L::Service: Service<Request> + Clone + Send + Sync + 'static,
@@ -725,16 +725,16 @@ where
fn with_state<S2>(self, state: S) -> Fallback<S2, E> { fn with_state<S2>(self, state: S) -> Fallback<S2, E> {
match self { match self {
Fallback::Default(route) => Fallback::Default(route), Self::Default(route) => Fallback::Default(route),
Fallback::Service(route) => Fallback::Service(route), Self::Service(route) => Fallback::Service(route),
Fallback::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)), Self::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)),
} }
} }
fn call_with_state(self, req: Request, state: S) -> RouteFuture<E> { fn call_with_state(self, req: Request, state: S) -> RouteFuture<E> {
match self { match self {
Fallback::Default(route) | Fallback::Service(route) => route.oneshot_inner_owned(req), Self::Default(route) | Self::Service(route) => route.oneshot_inner_owned(req),
Fallback::BoxedHandler(handler) => { Self::BoxedHandler(handler) => {
let route = handler.clone().into_route(state); let route = handler.clone().into_route(state);
route.oneshot_inner_owned(req) route.oneshot_inner_owned(req)
} }
@@ -772,7 +772,7 @@ impl<S> Endpoint<S>
where where
S: Clone + Send + Sync + 'static, S: Clone + Send + Sync + 'static,
{ {
fn layer<L>(self, layer: L) -> Endpoint<S> fn layer<L>(self, layer: L) -> Self
where where
L: Layer<Route> + Clone + Send + Sync + 'static, L: Layer<Route> + Clone + Send + Sync + 'static,
L::Service: Service<Request> + Clone + Send + Sync + 'static, L::Service: Service<Request> + Clone + Send + Sync + 'static,
@@ -781,10 +781,8 @@ where
<L::Service as Service<Request>>::Future: Send + 'static, <L::Service as Service<Request>>::Future: Send + 'static,
{ {
match self { match self {
Endpoint::MethodRouter(method_router) => { Self::MethodRouter(method_router) => Self::MethodRouter(method_router.layer(layer)),
Endpoint::MethodRouter(method_router.layer(layer)) Self::Route(route) => Self::Route(route.layer(layer)),
}
Endpoint::Route(route) => Endpoint::Route(route.layer(layer)),
} }
} }
} }
+7 -7
View File
@@ -143,8 +143,8 @@ where
.map_err(|err| format!("Invalid route {path:?}: {err}")) .map_err(|err| format!("Invalid route {path:?}: {err}"))
} }
pub(super) fn merge(&mut self, other: PathRouter<S>) -> Result<(), Cow<'static, str>> { pub(super) fn merge(&mut self, other: Self) -> Result<(), Cow<'static, str>> {
let PathRouter { let Self {
routes, routes,
node, node,
prev_route_id: _, prev_route_id: _,
@@ -172,11 +172,11 @@ where
pub(super) fn nest( pub(super) fn nest(
&mut self, &mut self,
path_to_nest_at: &str, path_to_nest_at: &str,
router: PathRouter<S>, router: Self,
) -> Result<(), Cow<'static, str>> { ) -> Result<(), Cow<'static, str>> {
let prefix = validate_nest_path(self.v7_checks, path_to_nest_at); let prefix = validate_nest_path(self.v7_checks, path_to_nest_at);
let PathRouter { let Self {
routes, routes,
node, node,
prev_route_id: _, prev_route_id: _,
@@ -248,7 +248,7 @@ where
Ok(()) Ok(())
} }
pub(super) fn layer<L>(self, layer: L) -> PathRouter<S> pub(super) fn layer<L>(self, layer: L) -> Self
where where
L: Layer<Route> + Clone + Send + Sync + 'static, L: Layer<Route> + Clone + Send + Sync + 'static,
L::Service: Service<Request> + Clone + Send + Sync + 'static, L::Service: Service<Request> + Clone + Send + Sync + 'static,
@@ -265,7 +265,7 @@ where
}) })
.collect(); .collect();
PathRouter { Self {
routes, routes,
node: self.node, node: self.node,
prev_route_id: self.prev_route_id, prev_route_id: self.prev_route_id,
@@ -298,7 +298,7 @@ where
}) })
.collect(); .collect();
PathRouter { Self {
routes, routes,
node: self.node, node: self.node,
prev_route_id: self.prev_route_id, prev_route_id: self.prev_route_id,
+1 -1
View File
@@ -59,7 +59,7 @@ impl<E> Route<E> {
pub(crate) fn layer<L, NewError>(self, layer: L) -> Route<NewError> pub(crate) fn layer<L, NewError>(self, layer: L) -> Route<NewError>
where where
L: Layer<Route<E>> + Clone + Send + 'static, L: Layer<Self> + Clone + Send + 'static,
L::Service: Service<Request> + Clone + Send + Sync + 'static, L::Service: Service<Request> + Clone + Send + Sync + 'static,
<L::Service as Service<Request>>::Response: IntoResponse + 'static, <L::Service as Service<Request>>::Response: IntoResponse + 'static,
<L::Service as Service<Request>>::Error: Into<NewError> + 'static, <L::Service as Service<Request>>::Error: Into<NewError> + 'static,
@@ -18,7 +18,7 @@ impl CountingCloneableState {
setup_done: AtomicBool::new(false), setup_done: AtomicBool::new(false),
count: AtomicUsize::new(0), count: AtomicUsize::new(0),
}; };
CountingCloneableState { Self {
state: Arc::new(inner_state), state: Arc::new(inner_state),
} }
} }
@@ -47,6 +47,6 @@ impl Clone for CountingCloneableState {
state.count.fetch_add(1, Ordering::SeqCst); state.count.fetch_add(1, Ordering::SeqCst);
} }
CountingCloneableState { state } Self { state }
} }
} }
+1 -1
View File
@@ -47,7 +47,7 @@ impl TestClient {
.build() .build()
.unwrap(); .unwrap();
TestClient { client, addr } Self { client, addr }
} }
pub fn get(&self, url: &str) -> RequestBuilder { pub fn get(&self, url: &str) -> RequestBuilder {