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
+2 -2
View File
@@ -105,8 +105,8 @@ const _: () = {
}
};
impl Connected<SocketAddr> for SocketAddr {
fn connect_info(remote_addr: SocketAddr) -> Self {
impl Connected<Self> for SocketAddr {
fn connect_info(remote_addr: Self) -> Self {
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> {
let uri = Extension::<Self>::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)
}
+10 -10
View File
@@ -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()))
}
}
+1 -1
View File
@@ -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))
}
}
+9 -9
View File
@@ -832,49 +832,49 @@ impl Message {
}
/// Create a new text WebSocket message from a stringable.
pub fn text<S>(string: S) -> Message
pub fn text<S>(string: S) -> Self
where
S: Into<Utf8Bytes>,
{
Message::Text(string.into())
Self::Text(string.into())
}
/// 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
B: Into<Bytes>,
{
Message::Binary(bin.into())
Self::Binary(bin.into())
}
}
impl From<String> 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<Bytes> for Message {
fn from(data: Bytes) -> Self {
Message::Binary(data)
Self::Binary(data)
}
}
impl From<Vec<u8>> for Message {
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::InvalidFormContentType(r)) => {
+2 -4
View File
@@ -60,7 +60,7 @@ impl<H, T, S> HandlerService<H, T, S> {
/// ```
///
/// [`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)
}
@@ -101,9 +101,7 @@ impl<H, T, S> HandlerService<H, T, S> {
/// [`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<C>(
self,
) -> IntoMakeServiceWithConnectInfo<HandlerService<H, T, S>, C> {
pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
IntoMakeServiceWithConnectInfo::new(self)
}
}
+1 -1
View File
@@ -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)),
}
}
+1 -1
View File
@@ -380,7 +380,7 @@ where
}
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)
}
}
+12 -12
View File
@@ -63,7 +63,7 @@ impl<S> Sse<S> {
S: TryStream<Ok = Event> + Send + 'static,
S::Error: Into<BoxError>,
{
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<T>(mut self, data: T) -> Event
pub fn data<T>(mut self, data: T) -> Self
where
T: AsRef<str>,
{
@@ -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<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
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<T>(mut self, comment: T) -> Event
pub fn comment<T>(mut self, comment: T) -> Self
where
T: AsRef<str>,
{
@@ -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<T>(mut self, event: T) -> Event
pub fn event<T>(mut self, event: T) -> Self
where
T: AsRef<str>,
{
@@ -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<T>(mut self, id: T) -> Event
pub fn id<T>(mut self, id: T) -> Self
where
T: AsRef<str>,
{
+9 -9
View File
@@ -89,15 +89,15 @@ impl TryFrom<Method> for MethodFilter {
fn try_from(m: Method) -> Result<Self, NoMatchingMethodFilter> {
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 }),
}
}
+12 -14
View File
@@ -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<L>(mut self, layer: L) -> MethodRouter<S, E>
pub fn route_layer<L>(mut self, layer: L) -> Self
where
L: Layer<Route<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(
mut self,
path: Option<&str>,
other: MethodRouter<S, E>,
other: Self,
) -> Result<Self, Cow<'static, str>> {
// written using inner functions to generate less IR
fn merge_inner<S, E>(
@@ -1086,7 +1086,7 @@ where
#[doc = include_str!("../docs/method_routing/merge.md")]
#[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) {
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<S2>(self, state: &S) -> MethodEndpoint<S2, E> {
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())),
}
}
}
+13 -15
View File
@@ -187,7 +187,7 @@ where
T::Response: IntoResponse,
T::Future: Send + 'static,
{
let service = match try_downcast::<Router<S>, _>(service) {
let service = match try_downcast::<Self, _>(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<S>) -> 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<R>(self, other: R) -> Self
where
R: Into<Router<S>>,
R: Into<Self>,
{
let other: Router<S> = 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<L>(self, layer: L) -> Router<S>
pub fn layer<L>(self, layer: L) -> Self
where
L: Layer<Route> + 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> {
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<E> {
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<S> Endpoint<S>
where
S: Clone + Send + Sync + 'static,
{
fn layer<L>(self, layer: L) -> Endpoint<S>
fn layer<L>(self, layer: L) -> Self
where
L: Layer<Route> + 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,
{
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)),
}
}
}
+7 -7
View File
@@ -143,8 +143,8 @@ where
.map_err(|err| format!("Invalid route {path:?}: {err}"))
}
pub(super) fn merge(&mut self, other: PathRouter<S>) -> 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<S>,
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<L>(self, layer: L) -> PathRouter<S>
pub(super) fn layer<L>(self, layer: L) -> Self
where
L: Layer<Route> + Clone + Send + Sync + 'static,
L::Service: Service<Request> + 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,
+1 -1
View File
@@ -59,7 +59,7 @@ impl<E> Route<E> {
pub(crate) fn layer<L, NewError>(self, layer: L) -> Route<NewError>
where
L: Layer<Route<E>> + Clone + Send + 'static,
L: Layer<Self> + Clone + Send + 'static,
L::Service: Service<Request> + Clone + Send + Sync + 'static,
<L::Service as Service<Request>>::Response: IntoResponse + 'static,
<L::Service as Service<Request>>::Error: Into<NewError> + 'static,
@@ -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 }
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl TestClient {
.build()
.unwrap();
TestClient { client, addr }
Self { client, addr }
}
pub fn get(&self, url: &str) -> RequestBuilder {