Skip to content

Commit

Permalink
Use inline format args (#2232)
Browse files Browse the repository at this point in the history
  • Loading branch information
nyurik authored Sep 19, 2023
1 parent a9822ec commit 786329d
Show file tree
Hide file tree
Showing 35 changed files with 72 additions and 83 deletions.
2 changes: 1 addition & 1 deletion axum-core/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ macro_rules! __composite_rejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
$(
Self::$variant(inner) => write!(f, "{}", inner),
Self::$variant(inner) => write!(f, "{inner}"),
)+
}
}
Expand Down
2 changes: 1 addition & 1 deletion axum-extra/src/body/async_read_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pin_project! {
/// let file = File::open("Cargo.toml")
/// .await
/// .map_err(|err| {
/// (StatusCode::NOT_FOUND, format!("File not found: {}", err))
/// (StatusCode::NOT_FOUND, format!("File not found: {err}"))
/// })?;
///
/// let headers = [(CONTENT_TYPE, "text/x-toml")];
Expand Down
2 changes: 1 addition & 1 deletion axum-extra/src/extract/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl IntoResponse for FormRejection {
Self::RawFormRejection(inner) => inner.into_response(),
Self::FailedToDeserializeForm(inner) => (
StatusCode::BAD_REQUEST,
format!("Failed to deserialize form: {}", inner),
format!("Failed to deserialize form: {inner}"),
)
.into_response(),
}
Expand Down
2 changes: 1 addition & 1 deletion axum-extra/src/extract/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl IntoResponse for QueryRejection {
match self {
Self::FailedToDeserializeQueryString(inner) => (
StatusCode::BAD_REQUEST,
format!("Failed to deserialize query string: {}", inner),
format!("Failed to deserialize query string: {inner}"),
)
.into_response(),
}
Expand Down
6 changes: 3 additions & 3 deletions axum/src/docs/error_handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ let app = Router::new().route_service(
async fn handle_anyhow_error(err: anyhow::Error) -> (StatusCode, String) {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", err),
format!("Something went wrong: {err}"),
)
}
# let _: Router = app;
Expand Down Expand Up @@ -133,7 +133,7 @@ async fn handle_timeout_error(err: BoxError) -> (StatusCode, String) {
} else {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", err),
format!("Unhandled internal error: {err}"),
)
}
}
Expand Down Expand Up @@ -174,7 +174,7 @@ async fn handle_timeout_error(
) -> (StatusCode, String) {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("`{} {}` failed with {}", method, uri, err),
format!("`{method} {uri}` failed with {err}"),
)
}
# let _: Router = app;
Expand Down
2 changes: 1 addition & 1 deletion axum/src/docs/method_routing/fallback.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ let handler = get(|| async {}).fallback(fallback);
let app = Router::new().route("/", handler);

async fn fallback(method: Method, uri: Uri) -> (StatusCode, String) {
(StatusCode::NOT_FOUND, format!("`{}` not allowed for {}", method, uri))
(StatusCode::NOT_FOUND, format!("`{method}` not allowed for {uri}"))
}
# async {
# hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
Expand Down
2 changes: 1 addition & 1 deletion axum/src/docs/routing/fallback.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ let app = Router::new()
.fallback(fallback);

async fn fallback(uri: Uri) -> (StatusCode, String) {
(StatusCode::NOT_FOUND, format!("No route for {}", uri))
(StatusCode::NOT_FOUND, format!("No route for {uri}"))
}
# let _: Router = app;
```
Expand Down
4 changes: 2 additions & 2 deletions axum/src/docs/routing/into_make_service_with_connect_info.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use std::net::SocketAddr;
let app = Router::new().route("/", get(handler));

async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
format!("Hello {}", addr)
format!("Hello {addr}")
}

# async {
Expand All @@ -41,7 +41,7 @@ let app = Router::new().route("/", get(handler));
async fn handler(
ConnectInfo(my_connect_info): ConnectInfo<MyConnectInfo>,
) -> String {
format!("Hello {:?}", my_connect_info)
format!("Hello {my_connect_info:?}")
}

#[derive(Clone, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion axum/src/handler/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ impl<H, T, S> HandlerService<H, T, S> {
/// ConnectInfo(addr): ConnectInfo<SocketAddr>,
/// State(state): State<AppState>,
/// ) -> String {
/// format!("Hello {}", addr)
/// format!("Hello {addr}")
/// }
///
/// let app = handler.with_state(AppState {});
Expand Down
4 changes: 2 additions & 2 deletions axum/src/routing/method_routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ impl MethodRouter<(), Infallible> {
/// use std::net::SocketAddr;
///
/// async fn handler(method: Method, uri: Uri, body: String) -> String {
/// format!("received `{} {}` with body `{:?}`", method, uri, body)
/// format!("received `{method} {uri}` with body `{body:?}`")
/// }
///
/// let router = get(handler).post(handler);
Expand Down Expand Up @@ -650,7 +650,7 @@ impl MethodRouter<(), Infallible> {
/// use std::net::SocketAddr;
///
/// async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
/// format!("Hello {}", addr)
/// format!("Hello {addr}")
/// }
///
/// let router = get(handler).post(handler);
Expand Down
2 changes: 1 addition & 1 deletion axum/src/routing/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -945,7 +945,7 @@ async fn state_isnt_cloned_too_much() {
.filter(|line| line.contains("axum") || line.contains("./src"))
.collect::<Vec<_>>()
.join("\n");
println!("AppState::Clone:\n===============\n{}\n", bt);
println!("AppState::Clone:\n===============\n{bt}\n");
COUNT.fetch_add(1, Ordering::SeqCst);
}
}
Expand Down
10 changes: 5 additions & 5 deletions examples/chat/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
let mut rx = state.tx.subscribe();

// Now send the "joined" message to all subscribers.
let msg = format!("{} joined.", username);
tracing::debug!("{}", msg);
let msg = format!("{username} joined.");
tracing::debug!("{msg}");
let _ = state.tx.send(msg);

// Spawn the first task that will receive broadcast messages and send text
Expand All @@ -124,7 +124,7 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
let mut recv_task = tokio::spawn(async move {
while let Some(Ok(Message::Text(text))) = receiver.next().await {
// Add username before message.
let _ = tx.send(format!("{}: {}", name, text));
let _ = tx.send(format!("{name}: {text}"));
}
});

Expand All @@ -135,8 +135,8 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
};

// Send "user left" message (similar to "joined" above).
let msg = format!("{} left.", username);
tracing::debug!("{}", msg);
let msg = format!("{username} left.");
tracing::debug!("{msg}");
let _ = state.tx.send(msg);

// Remove username from map so new clients can take it again.
Expand Down
4 changes: 2 additions & 2 deletions examples/customize-path-rejection/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ where
},

_ => PathError {
message: format!("Unhandled deserialization error: {}", kind),
message: format!("Unhandled deserialization error: {kind}"),
location: None,
},
};
Expand All @@ -126,7 +126,7 @@ where
_ => (
StatusCode::INTERNAL_SERVER_ERROR,
PathError {
message: format!("Unhandled path rejection: {}", rejection),
message: format!("Unhandled path rejection: {rejection}"),
location: None,
},
),
Expand Down
2 changes: 1 addition & 1 deletion examples/diesel-async-postgres/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async fn main() {

// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
tracing::debug!("listening on {addr}");
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Expand Down
2 changes: 1 addition & 1 deletion examples/diesel-postgres/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ async fn main() {

// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
tracing::debug!("listening on {addr}");
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Expand Down
2 changes: 1 addition & 1 deletion examples/graceful-shutdown/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async fn main() {

// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("listening on {}", addr);
println!("listening on {addr}");
hyper::Server::bind(&addr)
.serve(app.into_make_service())
.with_graceful_shutdown(shutdown_signal())
Expand Down
12 changes: 4 additions & 8 deletions examples/http-proxy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async fn main() {
});

let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
tracing::debug!("listening on {addr}");
hyper::Server::bind(&addr)
.http1_preserve_header_case(true)
.http1_title_case_headers(true)
Expand All @@ -68,10 +68,10 @@ async fn proxy(req: Request) -> Result<Response, hyper::Error> {
match hyper::upgrade::on(req).await {
Ok(upgraded) => {
if let Err(e) = tunnel(upgraded, host_addr).await {
tracing::warn!("server io error: {}", e);
tracing::warn!("server io error: {e}");
};
}
Err(e) => tracing::warn!("upgrade error: {}", e),
Err(e) => tracing::warn!("upgrade error: {e}"),
}
});

Expand All @@ -92,11 +92,7 @@ async fn tunnel(mut upgraded: Upgraded, addr: String) -> std::io::Result<()> {
let (from_client, from_server) =
tokio::io::copy_bidirectional(&mut upgraded, &mut server).await?;

tracing::debug!(
"client wrote {} bytes and received {} bytes",
from_client,
from_server
);
tracing::debug!("client wrote {from_client} bytes and received {from_server} bytes");

Ok(())
}
3 changes: 1 addition & 2 deletions examples/jwt/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ async fn main() {
async fn protected(claims: Claims) -> Result<String, AuthError> {
// Send the protected data to the user
Ok(format!(
"Welcome to the protected area :)\nYour data:\n{}",
claims
"Welcome to the protected area :)\nYour data:\n{claims}",
))
}

Expand Down
2 changes: 1 addition & 1 deletion examples/key-value-store/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,6 @@ async fn handle_error(error: BoxError) -> impl IntoResponse {

(
StatusCode::INTERNAL_SERVER_ERROR,
Cow::from(format!("Unhandled internal error: {}", error)),
Cow::from(format!("Unhandled internal error: {error}")),
)
}
5 changes: 1 addition & 4 deletions examples/multipart-form/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,7 @@ async fn accept_form(mut multipart: Multipart) {
let data = field.bytes().await.unwrap();

println!(
"Length of `{}` (`{}`: `{}`) is {} bytes",
name,
file_name,
content_type,
"Length of `{name}` (`{file_name}`: `{content_type}`) is {} bytes",
data.len()
);
}
Expand Down
11 changes: 4 additions & 7 deletions examples/oauth/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,7 @@ async fn discord_auth(State(client): State<BasicClient>) -> impl IntoResponse {

// Valid user session required. If there is none, redirect to the auth page
async fn protected(user: User) -> impl IntoResponse {
format!(
"Welcome to the protected area :)\nHere's your info:\n{:?}",
user
)
format!("Welcome to the protected area :)\nHere's your info:\n{user:?}")
}

async fn logout(
Expand Down Expand Up @@ -235,7 +232,7 @@ async fn login_authorized(
.context("unexpected error retrieving cookie value")?;

// Build the cookie
let cookie = format!("{}={}; SameSite=Lax; Path=/", COOKIE_NAME, cookie);
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; Path=/");

// Set cookie
let mut headers = HeaderMap::new();
Expand Down Expand Up @@ -273,9 +270,9 @@ where
.map_err(|e| match *e.name() {
header::COOKIE => match e.reason() {
TypedHeaderRejectionReason::Missing => AuthRedirect,
_ => panic!("unexpected error getting Cookie header(s): {}", e),
_ => panic!("unexpected error getting Cookie header(s): {e}"),
},
_ => panic!("unexpected error getting cookies: {}", e),
_ => panic!("unexpected error getting cookies: {e}"),
})?;
let session_cookie = cookies.get(COOKIE_NAME).ok_or(AuthRedirect)?;

Expand Down
4 changes: 2 additions & 2 deletions examples/print-request-response/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ where
Err(err) => {
return Err((
StatusCode::BAD_REQUEST,
format!("failed to read {} body: {}", direction, err),
format!("failed to read {direction} body: {err}"),
));
}
};

if let Ok(body) = std::str::from_utf8(&bytes) {
tracing::debug!("{} body = {:?}", direction, body);
tracing::debug!("{direction} body = {body:?}");
}

Ok(bytes)
Expand Down
4 changes: 2 additions & 2 deletions examples/query-params-with-empty-strings/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn app() -> Router {
}

async fn handler(Query(params): Query<Params>) -> String {
format!("{:?}", params)
format!("{params:?}")
}

/// See the tests below for which combinations of `foo` and `bar` result in
Expand Down Expand Up @@ -107,7 +107,7 @@ mod tests {
let body = app()
.oneshot(
Request::builder()
.uri(format!("/?{}", query))
.uri(format!("/?{query}"))
.body(Body::empty())
.unwrap(),
)
Expand Down
2 changes: 1 addition & 1 deletion examples/rest-grpc-multiplex/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async fn main() {
let service = MultiplexService::new(rest, grpc);

let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
tracing::debug!("listening on {addr}");
hyper::Server::bind(&addr)
.serve(tower::make::Shared::new(service))
.await
Expand Down
2 changes: 1 addition & 1 deletion examples/reverse-proxy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async fn handler(State(client): State<Client>, mut req: Request) -> Result<Respo
.map(|v| v.as_str())
.unwrap_or(path);

let uri = format!("http://127.0.0.1:3000{}", path_query);
let uri = format!("http://127.0.0.1:3000{path_query}");

*req.uri_mut() = Uri::try_from(uri).unwrap();

Expand Down
2 changes: 1 addition & 1 deletion examples/templates/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ where
Ok(html) => Html(html).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to render template. Error: {}", err),
format!("Failed to render template. Error: {err}"),
)
.into_response(),
}
Expand Down
2 changes: 1 addition & 1 deletion examples/testing/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ mod tests {
let response = client
.request(
Request::builder()
.uri(format!("http://{}", addr))
.uri(format!("http://{addr}"))
.body(hyper::Body::empty())
.unwrap(),
)
Expand Down
4 changes: 2 additions & 2 deletions examples/tls-graceful-shutdown/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ async fn main() {

// run https server
let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));
tracing::debug!("listening on {}", addr);
tracing::debug!("listening on {addr}");
axum_server::bind_rustls(addr, config)
.handle(handle)
.serve(app.into_make_service())
Expand Down Expand Up @@ -130,7 +130,7 @@ async fn redirect_http_to_https(ports: Ports, signal: impl Future<Output = ()>)

let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));
//let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
tracing::debug!("listening on {}", &addr);
tracing::debug!("listening on {addr}");
hyper::Server::bind(&addr)
.serve(redirect.into_make_service())
.with_graceful_shutdown(signal)
Expand Down
Loading

0 comments on commit 786329d

Please sign in to comment.