From c86313d4fa5b4d074e5ef40442a8a272d915dd3a Mon Sep 17 00:00:00 2001
From: Nyaaori <+@nyaaori.cat>
Date: Wed, 21 Dec 2022 10:42:12 +0100
Subject: [PATCH] chore: code cleanup

https://rust-lang.github.io/rust-clippy/master/index.html#op_ref

https://rust-lang.github.io/rust-clippy/master/index.html#str_to_string

https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
---
 src/api/client_server/account.rs       |  9 ++--
 src/api/client_server/directory.rs     |  2 +-
 src/api/client_server/membership.rs    | 15 +++---
 src/api/ruma_wrapper/axum.rs           |  3 +-
 src/api/server_server.rs               | 15 +++---
 src/config/mod.rs                      |  2 +-
 src/database/abstraction/sqlite.rs     |  2 +-
 src/database/mod.rs                    |  4 +-
 src/main.rs                            | 12 ++---
 src/service/admin/mod.rs               | 69 +++++++++-----------------
 src/service/rooms/auth_chain/mod.rs    |  5 +-
 src/service/rooms/event_handler/mod.rs |  2 +-
 src/service/rooms/state_cache/data.rs  |  2 +-
 src/service/rooms/timeline/mod.rs      |  2 +-
 src/utils/error.rs                     |  4 +-
 15 files changed, 56 insertions(+), 92 deletions(-)

diff --git a/src/api/client_server/account.rs b/src/api/client_server/account.rs
index 50a6a187..74592546 100644
--- a/src/api/client_server/account.rs
+++ b/src/api/client_server/account.rs
@@ -225,8 +225,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
     services()
         .admin
         .send_message(RoomMessageEventContent::notice_plain(format!(
-            "New user {} registered on this server.",
-            user_id
+            "New user {user_id} registered on this server."
         )));
 
     // If this is the first real user, grant them admin privileges
@@ -318,8 +317,7 @@ pub async fn change_password_route(
     services()
         .admin
         .send_message(RoomMessageEventContent::notice_plain(format!(
-            "User {} changed their password.",
-            sender_user
+            "User {sender_user} changed their password."
         )));
 
     Ok(change_password::v3::Response {})
@@ -396,8 +394,7 @@ pub async fn deactivate_route(
     services()
         .admin
         .send_message(RoomMessageEventContent::notice_plain(format!(
-            "User {} deactivated their account.",
-            sender_user
+            "User {sender_user} deactivated their account."
         )));
 
     Ok(deactivate::v3::Response {
diff --git a/src/api/client_server/directory.rs b/src/api/client_server/directory.rs
index 645710f1..e1322109 100644
--- a/src/api/client_server/directory.rs
+++ b/src/api/client_server/directory.rs
@@ -361,7 +361,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
     let prev_batch = if num_since == 0 {
         None
     } else {
-        Some(format!("p{}", num_since))
+        Some(format!("p{num_since}"))
     };
 
     let next_batch = if chunk.len() < limit as usize {
diff --git a/src/api/client_server/membership.rs b/src/api/client_server/membership.rs
index d6a1bd8c..87954ed3 100644
--- a/src/api/client_server/membership.rs
+++ b/src/api/client_server/membership.rs
@@ -583,7 +583,7 @@ async fn join_room_by_id_helper(
 
         if let Some(signed_raw) = &send_join_response.room_state.event {
             let (signed_event_id, signed_value) =
-                match gen_event_id_canonical_json(&signed_raw, &room_version_id) {
+                match gen_event_id_canonical_json(signed_raw, &room_version_id) {
                     Ok(t) => t,
                     Err(_) => {
                         // Event could not be converted to canonical json
@@ -594,7 +594,7 @@ async fn join_room_by_id_helper(
                     }
                 };
 
-            if &signed_event_id != event_id {
+            if signed_event_id != event_id {
                 return Err(Error::BadRequest(
                     ErrorKind::InvalidParam,
                     "Server sent event with wrong event id",
@@ -753,12 +753,12 @@ async fn join_room_by_id_helper(
             .set_room_state(room_id, statehash_after_join, &state_lock)?;
     } else {
         let join_rules_event = services().rooms.state_accessor.room_state_get(
-            &room_id,
+            room_id,
             &StateEventType::RoomJoinRules,
             "",
         )?;
         let power_levels_event = services().rooms.state_accessor.room_state_get(
-            &room_id,
+            room_id,
             &StateEventType::RoomPowerLevels,
             "",
         )?;
@@ -835,8 +835,7 @@ async fn join_room_by_id_helper(
                             .state_cache
                             .room_members(restriction_room_id)
                             .filter_map(|r| r.ok())
-                            .filter(|uid| uid.server_name() == services().globals.server_name())
-                            .next()
+                            .find(|uid| uid.server_name() == services().globals.server_name())
                     });
                 Some(authorized_user)
             })
@@ -982,7 +981,7 @@ async fn join_room_by_id_helper(
                         }
                     };
 
-                if &signed_event_id != event_id {
+                if signed_event_id != event_id {
                     return Err(Error::BadRequest(
                         ErrorKind::InvalidParam,
                         "Server sent event with wrong event id",
@@ -1179,7 +1178,7 @@ pub(crate) async fn invite_helper<'a>(
                 user_id.server_name(),
                 create_invite::v2::Request {
                     room_id: room_id.to_owned(),
-                    event_id: (&*pdu.event_id).to_owned(),
+                    event_id: (*pdu.event_id).to_owned(),
                     room_version: room_version_id.clone(),
                     event: PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()),
                     invite_room_state,
diff --git a/src/api/ruma_wrapper/axum.rs b/src/api/ruma_wrapper/axum.rs
index d056f3f2..ed28f9d3 100644
--- a/src/api/ruma_wrapper/axum.rs
+++ b/src/api/ruma_wrapper/axum.rs
@@ -308,8 +308,7 @@ impl Credentials for XMatrix {
     fn decode(value: &http::HeaderValue) -> Option<Self> {
         debug_assert!(
             value.as_bytes().starts_with(b"X-Matrix "),
-            "HeaderValue to decode should start with \"X-Matrix ..\", received = {:?}",
-            value,
+            "HeaderValue to decode should start with \"X-Matrix ..\", received = {value:?}",
         );
 
         let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..])
diff --git a/src/api/server_server.rs b/src/api/server_server.rs
index 2b854a68..fc3e2c0f 100644
--- a/src/api/server_server.rs
+++ b/src/api/server_server.rs
@@ -84,8 +84,8 @@ pub enum FedDest {
 impl FedDest {
     fn into_https_string(self) -> String {
         match self {
-            Self::Literal(addr) => format!("https://{}", addr),
-            Self::Named(host, port) => format!("https://{}{}", host, port),
+            Self::Literal(addr) => format!("https://{addr}"),
+            Self::Named(host, port) => format!("https://{host}{port}"),
         }
     }
 
@@ -385,7 +385,7 @@ async fn find_actual_destination(destination: &'_ ServerName) -> (FedDest, FedDe
                                         }
 
                                         if let Some(port) = force_port {
-                                            FedDest::Named(delegated_hostname, format!(":{}", port))
+                                            FedDest::Named(delegated_hostname, format!(":{port}"))
                                         } else {
                                             add_port_to_hostname(&delegated_hostname)
                                         }
@@ -427,7 +427,7 @@ async fn find_actual_destination(destination: &'_ ServerName) -> (FedDest, FedDe
                                 }
 
                                 if let Some(port) = force_port {
-                                    FedDest::Named(hostname.clone(), format!(":{}", port))
+                                    FedDest::Named(hostname.clone(), format!(":{port}"))
                                 } else {
                                     add_port_to_hostname(&hostname)
                                 }
@@ -460,7 +460,7 @@ async fn query_srv_record(hostname: &'_ str) -> Option<FedDest> {
     if let Ok(Some(host_port)) = services()
         .globals
         .dns_resolver()
-        .srv_lookup(format!("_matrix._tcp.{}", hostname))
+        .srv_lookup(format!("_matrix._tcp.{hostname}"))
         .await
         .map(|srv| {
             srv.iter().next().map(|result| {
@@ -482,10 +482,7 @@ async fn request_well_known(destination: &str) -> Option<String> {
         &services()
             .globals
             .default_client()
-            .get(&format!(
-                "https://{}/.well-known/matrix/server",
-                destination
-            ))
+            .get(&format!("https://{destination}/.well-known/matrix/server"))
             .send()
             .await
             .ok()?
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 6b862bb6..8a4b54ea 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -197,7 +197,7 @@ impl fmt::Display for Config {
             msg += &format!("{}: {}\n", line.1 .0, line.1 .1);
         }
 
-        write!(f, "{}", msg)
+        write!(f, "{msg}")
     }
 }
 
diff --git a/src/database/abstraction/sqlite.rs b/src/database/abstraction/sqlite.rs
index af3e1922..b69efb61 100644
--- a/src/database/abstraction/sqlite.rs
+++ b/src/database/abstraction/sqlite.rs
@@ -106,7 +106,7 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
     }
 
     fn open_tree(&self, name: &str) -> Result<Arc<dyn KvTree>> {
-        self.write_lock().execute(&format!("CREATE TABLE IF NOT EXISTS {} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )", name), [])?;
+        self.write_lock().execute(&format!("CREATE TABLE IF NOT EXISTS {name} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )"), [])?;
 
         Ok(Arc::new(SqliteTable {
             engine: Arc::clone(self),
diff --git a/src/database/mod.rs b/src/database/mod.rs
index ebaa7466..78bb358b 100644
--- a/src/database/mod.rs
+++ b/src/database/mod.rs
@@ -827,7 +827,7 @@ impl KeyValueDatabase {
                         let rule = rules_list.content.get(content_rule_transformation[0]);
                         if rule.is_some() {
                             let mut rule = rule.unwrap().clone();
-                            rule.rule_id = content_rule_transformation[1].to_string();
+                            rule.rule_id = content_rule_transformation[1].to_owned();
                             rules_list.content.remove(content_rule_transformation[0]);
                             rules_list.content.insert(rule);
                         }
@@ -850,7 +850,7 @@ impl KeyValueDatabase {
                             let rule = rules_list.underride.get(transformation[0]);
                             if let Some(rule) = rule {
                                 let mut rule = rule.clone();
-                                rule.rule_id = transformation[1].to_string();
+                                rule.rule_id = transformation[1].to_owned();
                                 rules_list.underride.remove(transformation[0]);
                                 rules_list.underride.insert(rule);
                             }
diff --git a/src/main.rs b/src/main.rs
index 49ac22d5..da80507c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -68,10 +68,7 @@ async fn main() {
     let config = match raw_config.extract::<Config>() {
         Ok(s) => s,
         Err(e) => {
-            eprintln!(
-                "It looks like your config is invalid. The following error occurred: {}",
-                e
-            );
+            eprintln!("It looks like your config is invalid. The following error occurred: {e}");
             std::process::exit(1);
         }
     };
@@ -91,8 +88,7 @@ async fn main() {
             Ok(s) => s,
             Err(e) => {
                 eprintln!(
-                    "It looks like your log config is invalid. The following error occurred: {}",
-                    e
+                    "It looks like your log config is invalid. The following error occurred: {e}"
                 );
                 EnvFilter::try_new("warn").unwrap()
             }
@@ -118,7 +114,7 @@ async fn main() {
         let filter_layer = match EnvFilter::try_new(&config.log) {
             Ok(s) => s,
             Err(e) => {
-                eprintln!("It looks like your config is invalid. The following error occured while parsing it: {}", e);
+                eprintln!("It looks like your config is invalid. The following error occured while parsing it: {e}");
                 EnvFilter::try_new("warn").unwrap()
             }
         };
@@ -534,6 +530,6 @@ fn method_to_filter(method: Method) -> MethodFilter {
         Method::POST => MethodFilter::POST,
         Method::PUT => MethodFilter::PUT,
         Method::TRACE => MethodFilter::TRACE,
-        m => panic!("Unsupported HTTP method: {:?}", m),
+        m => panic!("Unsupported HTTP method: {m:?}"),
     }
 }
diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs
index e2b2fd8d..77f351a9 100644
--- a/src/service/admin/mod.rs
+++ b/src/service/admin/mod.rs
@@ -287,13 +287,11 @@ impl Service {
             Err(error) => {
                 let markdown_message = format!(
                     "Encountered an error while handling the command:\n\
-                    ```\n{}\n```",
-                    error,
+                    ```\n{error}\n```",
                 );
                 let html_message = format!(
                     "Encountered an error while handling the command:\n\
-                    <pre>\n{}\n</pre>",
-                    error,
+                    <pre>\n{error}\n</pre>",
                 );
 
                 RoomMessageEventContent::text_html(markdown_message, html_message)
@@ -338,17 +336,14 @@ impl Service {
                     match parsed_config {
                         Ok(yaml) => match services().appservice.register_appservice(yaml) {
                             Ok(id) => RoomMessageEventContent::text_plain(format!(
-                                "Appservice registered with ID: {}.",
-                                id
+                                "Appservice registered with ID: {id}."
                             )),
                             Err(e) => RoomMessageEventContent::text_plain(format!(
-                                "Failed to register appservice: {}",
-                                e
+                                "Failed to register appservice: {e}"
                             )),
                         },
                         Err(e) => RoomMessageEventContent::text_plain(format!(
-                            "Could not parse appservice config: {}",
-                            e
+                            "Could not parse appservice config: {e}"
                         )),
                     }
                 } else {
@@ -365,8 +360,7 @@ impl Service {
             {
                 Ok(()) => RoomMessageEventContent::text_plain("Appservice unregistered."),
                 Err(e) => RoomMessageEventContent::text_plain(format!(
-                    "Failed to unregister appservice: {}",
-                    e
+                    "Failed to unregister appservice: {e}"
                 )),
             },
             AdminCommand::ListAppservices => {
@@ -459,8 +453,7 @@ impl Service {
                         .count();
                     let elapsed = start.elapsed();
                     RoomMessageEventContent::text_plain(format!(
-                        "Loaded auth chain with length {} in {:?}",
-                        count, elapsed
+                        "Loaded auth chain with length {count} in {elapsed:?}"
                     ))
                 } else {
                     RoomMessageEventContent::text_plain("Event not found.")
@@ -474,30 +467,26 @@ impl Service {
                         Ok(value) => {
                             match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
                                 Ok(hash) => {
-                                    let event_id = EventId::parse(format!("${}", hash));
+                                    let event_id = EventId::parse(format!("${hash}"));
 
                                     match serde_json::from_value::<PduEvent>(
                                         serde_json::to_value(value).expect("value is json"),
                                     ) {
                                         Ok(pdu) => RoomMessageEventContent::text_plain(format!(
-                                            "EventId: {:?}\n{:#?}",
-                                            event_id, pdu
+                                            "EventId: {event_id:?}\n{pdu:#?}"
                                         )),
                                         Err(e) => RoomMessageEventContent::text_plain(format!(
-                                            "EventId: {:?}\nCould not parse event: {}",
-                                            event_id, e
+                                            "EventId: {event_id:?}\nCould not parse event: {e}"
                                         )),
                                     }
                                 }
                                 Err(e) => RoomMessageEventContent::text_plain(format!(
-                                    "Could not parse PDU JSON: {:?}",
-                                    e
+                                    "Could not parse PDU JSON: {e:?}"
                                 )),
                             }
                         }
                         Err(e) => RoomMessageEventContent::text_plain(format!(
-                            "Invalid json in command body: {}",
-                            e
+                            "Invalid json in command body: {e}"
                         )),
                     }
                 } else {
@@ -545,8 +534,7 @@ impl Service {
             AdminCommand::DatabaseMemoryUsage => match services().globals.db.memory_usage() {
                 Ok(response) => RoomMessageEventContent::text_plain(response),
                 Err(e) => RoomMessageEventContent::text_plain(format!(
-                    "Failed to get database memory usage: {}",
-                    e
+                    "Failed to get database memory usage: {e}"
                 )),
             },
             AdminCommand::ShowConfig => {
@@ -561,8 +549,7 @@ impl Service {
                     Ok(id) => id,
                     Err(e) => {
                         return Ok(RoomMessageEventContent::text_plain(format!(
-                            "The supplied username is not a valid username: {}",
-                            e
+                            "The supplied username is not a valid username: {e}"
                         )))
                     }
                 };
@@ -589,12 +576,10 @@ impl Service {
                     .set_password(&user_id, Some(new_password.as_str()))
                 {
                     Ok(()) => RoomMessageEventContent::text_plain(format!(
-                        "Successfully reset the password for user {}: {}",
-                        user_id, new_password
+                        "Successfully reset the password for user {user_id}: {new_password}"
                     )),
                     Err(e) => RoomMessageEventContent::text_plain(format!(
-                        "Couldn't reset the password for user {}: {}",
-                        user_id, e
+                        "Couldn't reset the password for user {user_id}: {e}"
                     )),
                 }
             }
@@ -609,8 +594,7 @@ impl Service {
                     Ok(id) => id,
                     Err(e) => {
                         return Ok(RoomMessageEventContent::text_plain(format!(
-                            "The supplied username is not a valid username: {}",
-                            e
+                            "The supplied username is not a valid username: {e}"
                         )))
                     }
                 };
@@ -676,8 +660,7 @@ impl Service {
                 let user_id = Arc::<UserId>::from(user_id);
                 if services().users.exists(&user_id)? {
                     RoomMessageEventContent::text_plain(format!(
-                        "Making {} leave all rooms before deactivation...",
-                        user_id
+                        "Making {user_id} leave all rooms before deactivation..."
                     ));
 
                     services().users.deactivate_account(&user_id)?;
@@ -687,13 +670,11 @@ impl Service {
                     }
 
                     RoomMessageEventContent::text_plain(format!(
-                        "User {} has been deactivated",
-                        user_id
+                        "User {user_id} has been deactivated"
                     ))
                 } else {
                     RoomMessageEventContent::text_plain(format!(
-                        "User {} doesn't exist on this server",
-                        user_id
+                        "User {user_id} doesn't exist on this server"
                     ))
                 }
             }
@@ -709,8 +690,7 @@ impl Service {
                             Ok(user_id) => user_ids.push(user_id),
                             Err(_) => {
                                 return Ok(RoomMessageEventContent::text_plain(format!(
-                                    "{} is not a valid username",
-                                    username
+                                    "{username} is not a valid username"
                                 )))
                             }
                         }
@@ -746,8 +726,7 @@ impl Service {
 
                     if admins.is_empty() {
                         RoomMessageEventContent::text_plain(format!(
-                            "Deactivated {} accounts.",
-                            deactivation_count
+                            "Deactivated {deactivation_count} accounts."
                         ))
                     } else {
                         RoomMessageEventContent::text_plain(format!("Deactivated {} accounts.\nSkipped admin accounts: {:?}. Use --force to deactivate admin accounts", deactivation_count, admins.join(", ")))
@@ -767,8 +746,8 @@ impl Service {
     fn usage_to_html(&self, text: &str, server_name: &ServerName) -> String {
         // Replace `@conduit:servername:-subcmdname` with `@conduit:servername: subcmdname`
         let text = text.replace(
-            &format!("@conduit:{}:-", server_name),
-            &format!("@conduit:{}: ", server_name),
+            &format!("@conduit:{server_name}:-"),
+            &format!("@conduit:{server_name}: "),
         );
 
         // For the conduit admin room, subcommands become main commands
diff --git a/src/service/rooms/auth_chain/mod.rs b/src/service/rooms/auth_chain/mod.rs
index 92fdd0c3..da1944e2 100644
--- a/src/service/rooms/auth_chain/mod.rs
+++ b/src/service/rooms/auth_chain/mod.rs
@@ -15,10 +15,7 @@ pub struct Service {
 }
 
 impl Service {
-    pub fn get_cached_eventid_authchain<'a>(
-        &'a self,
-        key: &[u64],
-    ) -> Result<Option<Arc<HashSet<u64>>>> {
+    pub fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<HashSet<u64>>>> {
         self.db.get_cached_eventid_authchain(key)
     }
 
diff --git a/src/service/rooms/event_handler/mod.rs b/src/service/rooms/event_handler/mod.rs
index cf1f3705..7531674b 100644
--- a/src/service/rooms/event_handler/mod.rs
+++ b/src/service/rooms/event_handler/mod.rs
@@ -639,7 +639,7 @@ impl Service {
                     origin,
                     get_room_state_ids::v1::Request {
                         room_id: room_id.to_owned(),
-                        event_id: (&*incoming_pdu.event_id).to_owned(),
+                        event_id: (*incoming_pdu.event_id).to_owned(),
                     },
                 )
                 .await
diff --git a/src/service/rooms/state_cache/data.rs b/src/service/rooms/state_cache/data.rs
index 42de56d2..d8bb4a44 100644
--- a/src/service/rooms/state_cache/data.rs
+++ b/src/service/rooms/state_cache/data.rs
@@ -37,7 +37,7 @@ pub trait Data: Send + Sync {
         room_id: &RoomId,
     ) -> Box<dyn Iterator<Item = Result<OwnedServerName>> + 'a>;
 
-    fn server_in_room<'a>(&'a self, server: &ServerName, room_id: &RoomId) -> Result<bool>;
+    fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result<bool>;
 
     /// Returns an iterator of all rooms a server participates in (as far as we know).
     fn server_rooms<'a>(
diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs
index 619dca28..34399d46 100644
--- a/src/service/rooms/timeline/mod.rs
+++ b/src/service/rooms/timeline/mod.rs
@@ -378,7 +378,7 @@ impl Service {
                     )?;
                     let server_user = format!("@conduit:{}", services().globals.server_name());
 
-                    let to_conduit = body.starts_with(&format!("{}: ", server_user));
+                    let to_conduit = body.starts_with(&format!("{server_user}: "));
 
                     // This will evaluate to false if the emergency password is set up so that
                     // the administrator can execute commands as conduit
diff --git a/src/utils/error.rs b/src/utils/error.rs
index 3e0d8ca3..4f044ca2 100644
--- a/src/utils/error.rs
+++ b/src/utils/error.rs
@@ -104,12 +104,12 @@ impl Error {
             let mut error = error.clone();
             error.body = ErrorBody::Standard {
                 kind: Unknown,
-                message: format!("Answer from {}: {}", origin, error),
+                message: format!("Answer from {origin}: {error}"),
             };
             return RumaResponse(UiaaResponse::MatrixError(error));
         }
 
-        let message = format!("{}", self);
+        let message = format!("{self}");
 
         use ErrorKind::*;
         let (kind, status_code) = match self {