From cdf1f6e5d72fa07d62578ca1d07491245c9d5702 Mon Sep 17 00:00:00 2001 From: Val Lorentz Date: Sat, 4 May 2024 14:08:15 +0200 Subject: [PATCH] Fix clippy warnings (#122) * Fix clippy warnings * Fix new warnings --- client_listener/examples/restart.rs | 2 +- client_listener/src/internal/connection.rs | 13 ++-- sable_ipc/src/lib.rs | 5 +- sable_ircd/src/capability/mod.rs | 4 +- sable_ircd/src/capability/repository.rs | 4 +- sable_ircd/src/command/client_command.rs | 4 +- sable_ircd/src/command/handlers/admin.rs | 21 +++--- .../src/command/handlers/chathistory.rs | 23 +++---- sable_ircd/src/command/handlers/mode.rs | 2 +- sable_ircd/src/command/handlers/monitor.rs | 3 +- sable_ircd/src/command/handlers/names.rs | 2 +- sable_ircd/src/command/handlers/notice.rs | 4 +- sable_ircd/src/command/handlers/oper.rs | 7 +- sable_ircd/src/command/handlers/privmsg.rs | 6 +- sable_ircd/src/command/handlers/rename.rs | 1 + .../src/command/handlers/services/cs/role.rs | 4 +- .../handlers/services/dispatch_alias.rs | 4 +- .../src/command/handlers/services/mod.rs | 66 +++++++++++-------- .../src/command/handlers/services/ns/cert.rs | 4 +- sable_ircd/src/command/handlers/session.rs | 2 +- sable_ircd/src/command/handlers/topic.rs | 2 +- sable_ircd/src/command/handlers/who.rs | 4 +- .../src/command/plumbing/argument_wrappers.rs | 6 +- .../src/command/plumbing/command_response.rs | 2 +- .../plumbing/conditional_argument_types.rs | 6 +- sable_ircd/src/command/plumbing/handler.rs | 1 + .../src/command/plumbing/source_types.rs | 14 ++-- .../src/command/plumbing/target_types.rs | 2 +- sable_ircd/src/isupport.rs | 2 +- sable_ircd/src/messages/batch.rs | 8 +-- sable_ircd/src/messages/mod.rs | 4 +- sable_ircd/src/messages/send_history.rs | 2 +- sable_ircd/src/messages/send_realtime.rs | 4 +- sable_ircd/src/monitor.rs | 11 ++-- .../src/server/async_handler_collection.rs | 2 +- sable_ircd/src/server/command_action.rs | 6 +- sable_ircd/src/server/config.rs | 10 ++- sable_ircd/src/server/mod.rs | 8 +-- sable_ircd/src/server/server_type.rs | 2 +- sable_ircd/src/server/update_handler.rs | 8 +-- sable_ircd/src/utils/line_wrapper.rs | 4 +- sable_macros/src/lib.rs | 2 +- sable_network/src/history/log.rs | 4 +- sable_network/src/network/ban/repository.rs | 12 ++-- sable_network/src/network/event/tests.rs | 4 +- .../src/network/network/accessors.rs | 10 +-- .../src/network/network/alias_users.rs | 8 +-- .../src/network/network/default_roles.rs | 2 +- sable_network/src/network/network/mod.rs | 2 +- .../src/network/network/user_state.rs | 15 ++--- .../src/network/state/access_flag.rs | 6 +- sable_network/src/network/tests/fixtures.rs | 2 +- sable_network/src/network/wrapper/account.rs | 2 +- .../src/network/wrapper/channel_role.rs | 3 +- sable_network/src/network/wrapper/services.rs | 2 +- sable_network/src/node/mod.rs | 3 +- sable_network/src/node/update_receiver.rs | 22 +++---- sable_network/src/policy/ban_resolver.rs | 8 +-- sable_network/src/policy/oper_policy.rs | 2 + .../src/policy/standard_channel_policy.rs | 1 + sable_network/src/sync/config.rs | 8 +-- sable_network/src/sync/eventlog.rs | 2 +- sable_network/src/sync/network.rs | 12 ++-- sable_network/src/sync/replicated_log.rs | 11 ++-- sable_network/src/types/pattern.rs | 2 +- sable_network/src/validated.rs | 8 +-- sable_server/src/config.rs | 5 +- sable_services/src/hashing.rs | 9 +-- .../src/server/command/channel_commands.rs | 2 +- sable_services/src/server/sasl/plain.rs | 2 +- 70 files changed, 226 insertions(+), 234 deletions(-) diff --git a/client_listener/examples/restart.rs b/client_listener/examples/restart.rs index 41776101..aea2be8d 100644 --- a/client_listener/examples/restart.rs +++ b/client_listener/examples/restart.rs @@ -62,7 +62,7 @@ async fn do_restart( ) -> ! { let data = SaveData { listeners: listeners.save().await.unwrap(), - connections: connections.into_iter().map(|(_, c)| c.save()).collect(), + connections: connections.into_values().map(|c| c.save()).collect(), }; let fd = to_memfd(data).unwrap(); diff --git a/client_listener/src/internal/connection.rs b/client_listener/src/internal/connection.rs index ae353416..7031e296 100644 --- a/client_listener/src/internal/connection.rs +++ b/client_listener/src/internal/connection.rs @@ -2,7 +2,7 @@ use crate::internal::*; use crate::*; use sha1::{Digest, Sha1}; -use std::{convert::TryInto, net::IpAddr}; +use std::net::IpAddr; use tokio::{ io::AsyncWriteExt, net::TcpStream, @@ -44,12 +44,11 @@ impl InternalConnection { .get_ref() .1 .peer_certificates() - .map(|c| c.get(0)) - .flatten() + .and_then(|c| c.first()) .map(|cert| { let mut hasher = Sha1::new(); hasher.update(&cert.0); - hex::encode(hasher.finalize()).as_str().try_into().unwrap() + hex::encode(hasher.finalize()).as_str().into() }); tls_info = Some(TlsInfo { fingerprint }); @@ -80,7 +79,11 @@ impl InternalConnection { tls_info, }; - if let Err(_) = events.send(InternalConnectionEventType::New(conn)).await { + if events + .send(InternalConnectionEventType::New(conn)) + .await + .is_err() + { tracing::error!("Error sending new connection"); }; diff --git a/sable_ipc/src/lib.rs b/sable_ipc/src/lib.rs index 36964564..6f4016e6 100644 --- a/sable_ipc/src/lib.rs +++ b/sable_ipc/src/lib.rs @@ -114,13 +114,10 @@ pub struct Receiver { impl Receiver { fn new(socket: UnixDatagram, max_len: u64) -> Self { - let mut recv_buf = Vec::new(); - recv_buf.resize(max_len as usize, 0u8); - Self { socket: Some(socket), max_len, - recv_buffer: Mutex::new(recv_buf), + recv_buffer: Mutex::new(vec![0u8; max_len as usize]), _phantom: PhantomData, } } diff --git a/sable_ircd/src/capability/mod.rs b/sable_ircd/src/capability/mod.rs index f31172d7..885c8b28 100644 --- a/sable_ircd/src/capability/mod.rs +++ b/sable_ircd/src/capability/mod.rs @@ -116,7 +116,7 @@ impl ClientCapabilitySet { self.0 &= !(cap as u64); } - pub fn iter<'a>(&'a self) -> impl Iterator + 'a { + pub fn iter(&self) -> impl Iterator + '_ { ClientCapability::ALL .iter() .cloned() @@ -156,7 +156,7 @@ impl AtomicCapabilitySet { self.0.fetch_and(!(cap as u64), Ordering::Relaxed); } - pub fn iter<'a>(&'a self) -> impl Iterator + 'a { + pub fn iter(&self) -> impl Iterator + '_ { ClientCapability::ALL .iter() .cloned() diff --git a/sable_ircd/src/capability/repository.rs b/sable_ircd/src/capability/repository.rs index e5deae83..b2737435 100644 --- a/sable_ircd/src/capability/repository.rs +++ b/sable_ircd/src/capability/repository.rs @@ -103,11 +103,11 @@ impl CapabilityRepository { self.update_supported_lists(); } */ - pub fn enable_with_values(&self, cap: ClientCapability, values: &Vec) { + pub fn enable_with_values(&self, cap: ClientCapability, values: &[String]) { for entry in &self.supported_caps { if entry.cap == cap { entry.available.store(true, Ordering::Relaxed); - std::mem::swap(entry.values.write().as_mut(), &mut values.clone()) + std::mem::swap(entry.values.write().as_mut(), &mut values.to_owned()) } } self.update_supported_lists(); diff --git a/sable_ircd/src/command/client_command.rs b/sable_ircd/src/command/client_command.rs index b48a3d59..024a22f6 100644 --- a/sable_ircd/src/command/client_command.rs +++ b/sable_ircd/src/command/client_command.rs @@ -18,7 +18,7 @@ impl<'a> CommandSource<'a> { pub fn user(&self) -> Option<&wrapper::User<'a>> { match self { Self::PreClient(_) => None, - Self::User(u, _) => Some(&u), + Self::User(u, _) => Some(u), } } @@ -72,7 +72,7 @@ impl ClientCommand { message: ClientMessage, ) -> Result { let net = server.network(); - let source = Self::translate_message_source(&*net, &*connection)?; + let source = Self::translate_message_source(&net, &connection)?; let response_target = Self::translate_internal_source(&source, net.as_ref()).format(); let response_sink = Self::make_response_sink( Arc::clone(&connection), diff --git a/sable_ircd/src/command/handlers/admin.rs b/sable_ircd/src/command/handlers/admin.rs index aa22584f..f5158192 100644 --- a/sable_ircd/src/command/handlers/admin.rs +++ b/sable_ircd/src/command/handlers/admin.rs @@ -4,20 +4,17 @@ use super::*; fn handle_admin(server: &ClientServer, response: &dyn CommandResponse) -> CommandResult { response.numeric(make_numeric!(AdminMe, server.name())); if let Some(admin_info) = &server.info_strings.admin_info { - admin_info - .server_location - .as_ref() - .map(|i| response.numeric(make_numeric!(AdminLocation1, i))); + if let Some(i) = admin_info.server_location.as_ref() { + response.numeric(make_numeric!(AdminLocation1, i)) + } - admin_info - .description - .as_ref() - .map(|i| response.numeric(make_numeric!(AdminLocation2, i))); + if let Some(i) = admin_info.description.as_ref() { + response.numeric(make_numeric!(AdminLocation2, i)) + } - admin_info - .email - .as_ref() - .map(|i| response.numeric(make_numeric!(AdminEmail, i))); + if let Some(i) = admin_info.email.as_ref() { + response.numeric(make_numeric!(AdminEmail, i)) + } } Ok(()) } diff --git a/sable_ircd/src/command/handlers/chathistory.rs b/sable_ircd/src/command/handlers/chathistory.rs index 472a7d3b..59ffc108 100644 --- a/sable_ircd/src/command/handlers/chathistory.rs +++ b/sable_ircd/src/command/handlers/chathistory.rs @@ -34,6 +34,7 @@ fn parse_msgref(subcommand: &str, target: Option<&str>, msgref: &str) -> Result< } } +#[allow(clippy::too_many_arguments)] #[command_handler("CHATHISTORY")] fn handle_chathistory( source: UserSource, @@ -66,7 +67,7 @@ fn handle_chathistory( // The spec allows the from and to timestamps in either order; list_targets requires from < to list_targets( server, - &response, + response, source, Some(min(from_ts, to_ts)), Some(max(from_ts, to_ts)), @@ -93,10 +94,10 @@ fn handle_chathistory( send_history_for_target( server, - &response, + response, source, subcommand, - &target, + target, None, to_ts, limit, @@ -120,7 +121,7 @@ fn handle_chathistory( send_history_for_target( server, - &response, + response, source, subcommand, target, @@ -147,10 +148,10 @@ fn handle_chathistory( send_history_for_target( server, - &response, + response, source, subcommand, - &target, + target, Some(start_ts), None, Some(0), // backward limit @@ -176,10 +177,10 @@ fn handle_chathistory( send_history_for_target( server, - &response, + response, source, subcommand, - &target, + target, Some(around_ts), None, Some(limit / 2), // backward limit @@ -204,10 +205,10 @@ fn handle_chathistory( send_history_for_target( server, - &response, + response, source, subcommand, - &target, + target, Some(start_ts), Some(end_ts), Some(0), // backward limit @@ -371,7 +372,7 @@ fn send_history_entries<'a>( backward_entries: Vec<&'a HistoryLogEntry>, forward_entries: Vec<&'a HistoryLogEntry>, ) -> CommandResult { - if backward_entries.len() == 0 && forward_entries.len() == 0 { + if backward_entries.is_empty() && forward_entries.is_empty() { into.send(message::Fail::new( "CHATHISTORY", "INVALID_TARGET", diff --git a/sable_ircd/src/command/handlers/mode.rs b/sable_ircd/src/command/handlers/mode.rs index e4762e18..2c6cdedc 100644 --- a/sable_ircd/src/command/handlers/mode.rs +++ b/sable_ircd/src/command/handlers/mode.rs @@ -70,7 +70,7 @@ async fn handle_user_mode( if let Ok(d) = Direction::try_from(c) { dir = d; } else if let Some(flag) = UserModeFlag::from_mode_char(c) { - if server.policy().can_set_umode(&source, flag).is_err() { + if server.policy().can_set_umode(source, flag).is_err() { continue; } diff --git a/sable_ircd/src/command/handlers/monitor.rs b/sable_ircd/src/command/handlers/monitor.rs index 47002ee4..f041d9c0 100644 --- a/sable_ircd/src/command/handlers/monitor.rs +++ b/sable_ircd/src/command/handlers/monitor.rs @@ -36,8 +36,7 @@ fn handle_monitor_add( let mut monitors = server.monitors.write(); let res = targets .iter() - .map(|&target| monitors.insert(target, cmd.connection_id())) - .collect::>() + .try_for_each(|&target| monitors.insert(target, cmd.connection_id())) .map_err( |MonitorInsertError::TooManyMonitorsPerConnection { max, current }| { CommandError::Numeric(make_numeric!(MonListFull, max, current)) diff --git a/sable_ircd/src/command/handlers/names.rs b/sable_ircd/src/command/handlers/names.rs index 1b9f39af..5561c1c9 100644 --- a/sable_ircd/src/command/handlers/names.rs +++ b/sable_ircd/src/command/handlers/names.rs @@ -9,7 +9,7 @@ fn handle_names( ) -> CommandResult { match channel { Ok(channel) => Ok(crate::utils::send_channel_names( - server, &response, &source, &channel, + server, response, &source, &channel, )?), Err(channel_name) => { // "If the channel name is invalid or the channel does not exist, one RPL_ENDOFNAMES numeric diff --git a/sable_ircd/src/command/handlers/notice.rs b/sable_ircd/src/command/handlers/notice.rs index e880cf00..b90948fd 100644 --- a/sable_ircd/src/command/handlers/notice.rs +++ b/sable_ircd/src/command/handlers/notice.rs @@ -31,7 +31,7 @@ async fn handle_notice( */ return Ok(()); }; - if msg.len() == 0 { + if msg.is_empty() { // Ditto return Ok(()); } @@ -44,7 +44,7 @@ async fn handle_notice( } } TargetParameter::Channel(channel) => { - if server.policy().can_send(&source, &channel, msg).is_err() { + if server.policy().can_send(&source, channel, msg).is_err() { // Silent error, see above return Ok(()); } diff --git a/sable_ircd/src/command/handlers/oper.rs b/sable_ircd/src/command/handlers/oper.rs index 226f9162..0660aed9 100644 --- a/sable_ircd/src/command/handlers/oper.rs +++ b/sable_ircd/src/command/handlers/oper.rs @@ -40,10 +40,5 @@ fn find_oper_block<'a>( ) -> Option<&'a config::OperConfig> { let conf = net.config(); - for block in &conf.opers { - if block.name == oper_name { - return Some(block); - } - } - None + conf.opers.iter().find(|&block| block.name == oper_name) } diff --git a/sable_ircd/src/command/handlers/privmsg.rs b/sable_ircd/src/command/handlers/privmsg.rs index c4d5b1ef..85664508 100644 --- a/sable_ircd/src/command/handlers/privmsg.rs +++ b/sable_ircd/src/command/handlers/privmsg.rs @@ -10,14 +10,14 @@ async fn handle_privmsg( target: TargetParameter<'_>, msg: &str, ) -> CommandResult { - if msg.len() == 0 { + if msg.is_empty() { return numeric_error!(NoTextToSend); } match &target { TargetParameter::User(user) => { if let Some(AliasUser { command_alias, .. }) = user.is_alias_user() { - return super::services::dispatch_alias_command(cmd, &user, &command_alias, msg) + return super::services::dispatch_alias_command(cmd, user, command_alias, msg) .await; } @@ -26,7 +26,7 @@ async fn handle_privmsg( } } TargetParameter::Channel(channel) => { - server.policy().can_send(&source, &channel, msg)?; + server.policy().can_send(&source, channel, msg)?; } } diff --git a/sable_ircd/src/command/handlers/rename.rs b/sable_ircd/src/command/handlers/rename.rs index 4135cfd4..df34d5e5 100644 --- a/sable_ircd/src/command/handlers/rename.rs +++ b/sable_ircd/src/command/handlers/rename.rs @@ -1,5 +1,6 @@ use super::*; +#[allow(clippy::too_many_arguments)] #[command_handler("RENAME")] async fn handle_rename( server: &ClientServer, diff --git a/sable_ircd/src/command/handlers/services/cs/role.rs b/sable_ircd/src/command/handlers/services/cs/role.rs index 783f1528..8d947a4b 100644 --- a/sable_ircd/src/command/handlers/services/cs/role.rs +++ b/sable_ircd/src/command/handlers/services/cs/role.rs @@ -78,7 +78,7 @@ async fn role_edit( let (adding, flag_name) = match flag_str.as_bytes()[0] { b'+' => (true, &flag_str[1..]), b'-' => (false, &flag_str[1..]), - _ => (true, &flag_str[..]), + _ => (true, flag_str), }; let Ok(flag) = ChannelAccessFlag::from_str(flag_name) else { @@ -154,7 +154,7 @@ async fn role_add( source: source.account.id(), channel: chan.id(), name: target_role_name, - flags: flags, + flags, }; let registration_response = services_target.send_remote_request(request).await; diff --git a/sable_ircd/src/command/handlers/services/dispatch_alias.rs b/sable_ircd/src/command/handlers/services/dispatch_alias.rs index cb9dfd22..c3720bd7 100644 --- a/sable_ircd/src/command/handlers/services/dispatch_alias.rs +++ b/sable_ircd/src/command/handlers/services/dispatch_alias.rs @@ -6,9 +6,9 @@ pub async fn dispatch_alias_command( alias: &str, command_str: &str, ) -> CommandResult { - let (command, args) = command_str.split_once(" ").unwrap_or((command_str, "")); + let (command, args) = command_str.split_once(' ').unwrap_or((command_str, "")); - let new_args = args.split(" ").map(ToOwned::to_owned).collect::>(); + let new_args = args.split(' ').map(ToOwned::to_owned).collect::>(); let new_arg_iter = ArgListIter::new(&new_args); let new_cmd = ServicesCommand::new(cmd, command, new_arg_iter, Some(through_user)); diff --git a/sable_ircd/src/command/handlers/services/mod.rs b/sable_ircd/src/command/handlers/services/mod.rs index 54f6c112..3e877ff0 100644 --- a/sable_ircd/src/command/handlers/services/mod.rs +++ b/sable_ircd/src/command/handlers/services/mod.rs @@ -66,45 +66,39 @@ impl<'a> Command for ServicesCommand<'a> { } fn notify_error(&self, err: CommandError) { - match err - { + match err { CommandError::UnderlyingError(_) => { todo!() } CommandError::UnknownError(_) => { todo!() } -/* + /* CommandError::CustomError => { todo!() } -*/ + */ CommandError::CommandNotFound(cmd) => { self.notice(format_args!("Unknown command {}", cmd.to_ascii_uppercase())); } CommandError::NotEnoughParameters => { self.notice("Invalid parameters"); } - CommandError::LookupError(le) => { - match le - { - LookupError::NoSuchNick(nick) => { - self.notice(format_args!("There is no such nick {}", nick)) - } - LookupError::NoSuchChannelName(name) => { - self.notice(format_args!("Channel {} does not exist", name)) - } - LookupError::NoSuchAccountNamed(name) => { - self.notice(format_args!("{} is not registered", name)) - } - LookupError::ChannelNotRegistered(name) => { - self.notice(format_args!("{} is not registered", name)) - } - err => { - self.notice(format_args!("Unknown error: {}", err)) - } + CommandError::LookupError(le) => match le { + LookupError::NoSuchNick(nick) => { + self.notice(format_args!("There is no such nick {}", nick)) } - } + LookupError::NoSuchChannelName(name) => { + self.notice(format_args!("Channel {} does not exist", name)) + } + LookupError::NoSuchAccountNamed(name) => { + self.notice(format_args!("{} is not registered", name)) + } + LookupError::ChannelNotRegistered(name) => { + self.notice(format_args!("{} is not registered", name)) + } + err => self.notice(format_args!("Unknown error: {}", err)), + }, CommandError::InvalidNickname(name) => { self.notice(format_args!("Invalid nickname {}", name)); } @@ -131,6 +125,7 @@ impl<'a> Command for ServicesCommand<'a> { PermissionError::User(ue) => { use UserPermissionError::*; + #[allow(clippy::single_match)] // For consistency with other branches match ue { NotLoggedIn => { self.notice("You are not logged in") } _ => {} @@ -158,12 +153,29 @@ impl<'a> Command for ServicesCommand<'a> { } } CommandError::Numeric(n) => { - tracing::warn!("Translating unknown error numeric from services response: {:?}", n); + tracing::warn!( + "Translating unknown error numeric from services response: {:?}", + n + ); self.notice(format_args!("Unknown error: {}", n.debug_format())); } - CommandError::Fail { command, code, context, description } => { - tracing::warn!("Translating unknown error numeric from services response: {} {} {} :{}", command, code, context, description); - self.notice(format_args!("Unknown error: {} {} {} :{}", command, code, context, description)); + CommandError::Fail { + command, + code, + context, + description, + } => { + tracing::warn!( + "Translating unknown error numeric from services response: {} {} {} :{}", + command, + code, + context, + description + ); + self.notice(format_args!( + "Unknown error: {} {} {} :{}", + command, code, context, description + )); } } } diff --git a/sable_ircd/src/command/handlers/services/ns/cert.rs b/sable_ircd/src/command/handlers/services/ns/cert.rs index a4a9da72..a9086ee0 100644 --- a/sable_ircd/src/command/handlers/services/ns/cert.rs +++ b/sable_ircd/src/command/handlers/services/ns/cert.rs @@ -53,7 +53,7 @@ async fn cert_add( if let Some(fp) = cmd .connection() .tls_info() - .and_then(|ti| ti.fingerprint.as_ref().map(|f| f.as_str())) + .and_then(|ti| ti.fingerprint.as_deref()) { fp } else { @@ -65,7 +65,7 @@ async fn cert_add( } }; - if net.account_with_fingerprint(&fingerprint).is_some() { + if net.account_with_fingerprint(fingerprint).is_some() { cmd.notice("That fingerprint is already in use"); return Ok(()); } diff --git a/sable_ircd/src/command/handlers/session.rs b/sable_ircd/src/command/handlers/session.rs index bd535560..57db6448 100644 --- a/sable_ircd/src/command/handlers/session.rs +++ b/sable_ircd/src/command/handlers/session.rs @@ -37,7 +37,7 @@ fn handle_session( if let Some(target_user) = server .network() .raw_users() - .find(|u| matches!(&u.session_key, Some(sk) if &sk.key_hash == key)) + .find(|u| matches!(&u.session_key, Some(sk) if sk.key_hash == key)) { // Ok to ignore an error here, as that'll only happen if the command is run twice let _ = pre_client.attach_user_id.set(target_user.id); diff --git a/sable_ircd/src/command/handlers/topic.rs b/sable_ircd/src/command/handlers/topic.rs index 87b17f33..c6b0270c 100644 --- a/sable_ircd/src/command/handlers/topic.rs +++ b/sable_ircd/src/command/handlers/topic.rs @@ -11,7 +11,7 @@ async fn handle_topic( new_topic: Option<&str>, ) -> CommandResult { if let Some(text) = new_topic { - server.policy().can_set_topic(&source, &channel, &text)?; + server.policy().can_set_topic(&source, &channel, text)?; let details = event::details::NewChannelTopic { channel: channel.id(), diff --git a/sable_ircd/src/command/handlers/who.rs b/sable_ircd/src/command/handlers/who.rs index 6087cee6..28d38a6c 100644 --- a/sable_ircd/src/command/handlers/who.rs +++ b/sable_ircd/src/command/handlers/who.rs @@ -70,7 +70,7 @@ fn send_who_reply( away_letter, membership .map(|m| m.permissions().to_prefixes()) - .unwrap_or_else(|| "".to_string()) + .unwrap_or_default() ) } else { format!( @@ -80,7 +80,7 @@ fn send_who_reply( .and_then(|m| m.permissions().to_highest_prefix()) .as_ref() .map(char::to_string) - .unwrap_or_else(|| "".to_string()) + .unwrap_or_default() ) }; response.numeric(make_numeric!(WhoReply, chname, target, &status, 0)) diff --git a/sable_ircd/src/command/plumbing/argument_wrappers.rs b/sable_ircd/src/command/plumbing/argument_wrappers.rs index 0f787946..73d93603 100644 --- a/sable_ircd/src/command/plumbing/argument_wrappers.rs +++ b/sable_ircd/src/command/plumbing/argument_wrappers.rs @@ -7,9 +7,9 @@ pub struct ServicesTarget<'a> { server: &'a ClientServer, } -impl Into for ServicesTarget<'_> { - fn into(self) -> ServerName { - self.name +impl From> for ServerName { + fn from(val: ServicesTarget<'_>) -> Self { + val.name } } diff --git a/sable_ircd/src/command/plumbing/command_response.rs b/sable_ircd/src/command/plumbing/command_response.rs index 84400778..5b9c51f4 100644 --- a/sable_ircd/src/command/plumbing/command_response.rs +++ b/sable_ircd/src/command/plumbing/command_response.rs @@ -82,7 +82,7 @@ pub struct LabeledResponseSink { batch: LazyMessageBatch>, } -impl<'a, Sink: MessageSink> LabeledResponseSink { +impl LabeledResponseSink { pub(in crate::command) fn new( response_source: String, response_target: String, diff --git a/sable_ircd/src/command/plumbing/conditional_argument_types.rs b/sable_ircd/src/command/plumbing/conditional_argument_types.rs index 52af9975..37f09b1d 100644 --- a/sable_ircd/src/command/plumbing/conditional_argument_types.rs +++ b/sable_ircd/src/command/plumbing/conditional_argument_types.rs @@ -12,9 +12,9 @@ impl std::ops::Deref for IfParses { } } -impl Into> for IfParses { - fn into(self) -> Option { - self.0 +impl From> for Option { + fn from(val: IfParses) -> Self { + val.0 } } diff --git a/sable_ircd/src/command/plumbing/handler.rs b/sable_ircd/src/command/plumbing/handler.rs index 4a3a64ea..57cdb7f5 100644 --- a/sable_ircd/src/command/plumbing/handler.rs +++ b/sable_ircd/src/command/plumbing/handler.rs @@ -51,6 +51,7 @@ macro_rules! define_handler_fn } } + #[allow(clippy::manual_async_fn)] impl<'ctx, T, F, $($ambient,)* $($pos),*> AsyncHandlerFn<'ctx, ($($ambient,)*), ($($pos,)*)> for T where T: Fn($($ambient,)* $($pos),*) -> F, T: Send + Sync, diff --git a/sable_ircd/src/command/plumbing/source_types.rs b/sable_ircd/src/command/plumbing/source_types.rs index d995b08e..99e337f9 100644 --- a/sable_ircd/src/command/plumbing/source_types.rs +++ b/sable_ircd/src/command/plumbing/source_types.rs @@ -74,9 +74,9 @@ impl<'a> std::convert::AsRef> for UserSource<'a> { } } -impl<'a> Into> for UserSource<'a> { - fn into(self) -> wrapper::User<'a> { - self.user +impl<'a> From> for wrapper::User<'a> { + fn from(val: UserSource<'a>) -> Self { + val.user } } @@ -84,7 +84,7 @@ impl std::ops::Deref for PreClientSource { type Target = PreClient; fn deref(&self) -> &Self::Target { - &self.0.deref() + self.0.deref() } } @@ -100,8 +100,8 @@ impl From> for PreClientSource { } } -impl Into> for PreClientSource { - fn into(self) -> Arc { - self.0 +impl From for Arc { + fn from(val: PreClientSource) -> Self { + val.0 } } diff --git a/sable_ircd/src/command/plumbing/target_types.rs b/sable_ircd/src/command/plumbing/target_types.rs index 6762a5b4..705a5638 100644 --- a/sable_ircd/src/command/plumbing/target_types.rs +++ b/sable_ircd/src/command/plumbing/target_types.rs @@ -43,7 +43,7 @@ impl<'a> PositionalArgument<'a> for RegisteredChannel<'a> { registration: reg, }) } else { - Err(CommandError::ChannelNotRegistered(chan.name().clone())) + Err(CommandError::ChannelNotRegistered(*chan.name())) } } } diff --git a/sable_ircd/src/isupport.rs b/sable_ircd/src/isupport.rs index 4154d3ec..c3b3b147 100644 --- a/sable_ircd/src/isupport.rs +++ b/sable_ircd/src/isupport.rs @@ -91,7 +91,7 @@ impl ISupportBuilder { let mut result = Vec::new(); let mut current = Cell::new(String::new()); - for (i, entry) in (&self.entries).iter().enumerate() { + for (i, entry) in self.entries.iter().enumerate() { let s = entry.format(); if current.get_mut().len() + s.len() + 1 > MAX_LEN { diff --git a/sable_ircd/src/messages/batch.rs b/sable_ircd/src/messages/batch.rs index 25967085..612c17bb 100644 --- a/sable_ircd/src/messages/batch.rs +++ b/sable_ircd/src/messages/batch.rs @@ -16,7 +16,7 @@ fn random_batch_name() -> String { format!("{:x}", rand::random::()) } -impl<'a, Underlying: MessageSink> BatchBuilder { +impl BatchBuilder { /// Construct a new builder with the given name pub(super) fn with_name( batch_type: impl ToString, @@ -98,7 +98,7 @@ pub struct MessageBatch { target: Underlying, } -impl<'a, Underlying: MessageSink> Drop for MessageBatch { +impl Drop for MessageBatch { fn drop(&mut self) { let end_msg = message::BatchEnd::new(&self.name).with_required_capabilities(self.capability); @@ -106,7 +106,7 @@ impl<'a, Underlying: MessageSink> Drop for MessageBatch { } } -impl<'a, Underlying: MessageSink> MessageSink for MessageBatch { +impl MessageSink for MessageBatch { fn send(&self, msg: OutboundClientMessage) { let tag = OutboundMessageTag::new("batch", Some(self.name.clone()), self.capability); let message = msg.with_tag(tag); @@ -162,7 +162,7 @@ impl LazyMessageBatch { } } -impl<'a, Underlying: MessageSink> Drop for LazyMessageBatch { +impl Drop for LazyMessageBatch { fn drop(&mut self) { // Only send the batch end if we sent the start if self.is_opened() { diff --git a/sable_ircd/src/messages/mod.rs b/sable_ircd/src/messages/mod.rs index 48999de5..4ee95299 100644 --- a/sable_ircd/src/messages/mod.rs +++ b/sable_ircd/src/messages/mod.rs @@ -78,7 +78,7 @@ impl OutboundClientMessage { Self { caps: Default::default(), tags: Default::default(), - content: content, + content, } } @@ -93,7 +93,7 @@ impl OutboundClientMessage { } /// Add a set of message tags to the message - pub fn with_tags(mut self, tags: &Vec) -> Self { + pub fn with_tags(mut self, tags: &[OutboundMessageTag]) -> Self { self.tags.extend_from_slice(tags); self } diff --git a/sable_ircd/src/messages/send_history.rs b/sable_ircd/src/messages/send_history.rs index 7ada12b0..dfd80876 100644 --- a/sable_ircd/src/messages/send_history.rs +++ b/sable_ircd/src/messages/send_history.rs @@ -215,7 +215,7 @@ impl SendHistoryItem for update::ChannelJoin { if let Some(away_reason) = self.user.user.away_reason { let message = - message::Away::new(&self.user, &away_reason.value()).with_tags_from(from_entry); + message::Away::new(&self.user, away_reason.value()).with_tags_from(from_entry); conn.send(message.with_required_capabilities(ClientCapability::AwayNotify)); } diff --git a/sable_ircd/src/messages/send_realtime.rs b/sable_ircd/src/messages/send_realtime.rs index 06ae0dca..5def8b1e 100644 --- a/sable_ircd/src/messages/send_realtime.rs +++ b/sable_ircd/src/messages/send_realtime.rs @@ -107,7 +107,7 @@ impl SendRealtimeItem for update::ChannelRename { let fake_part = update::ChannelPart { channel: state::Channel { - name: self.old_name.clone(), + name: self.old_name, ..self.channel.clone() }, membership: membership.raw().clone(), @@ -121,7 +121,7 @@ impl SendRealtimeItem for update::ChannelRename { let fake_join = update::ChannelJoin { channel: state::Channel { - name: self.new_name.clone(), + name: self.new_name, ..self.channel.clone() }, membership: membership.raw().clone(), diff --git a/sable_ircd/src/monitor.rs b/sable_ircd/src/monitor.rs index 78a95d72..2848b2f5 100644 --- a/sable_ircd/src/monitor.rs +++ b/sable_ircd/src/monitor.rs @@ -45,10 +45,7 @@ impl MonitorSet { nick: Nickname, monitor: ConnectionId, ) -> Result<(), MonitorInsertError> { - let entry = self - .monitors_by_connection - .entry(monitor) - .or_insert_with(HashSet::new); + let entry = self.monitors_by_connection.entry(monitor).or_default(); if entry.len() >= self.max_per_connection { return Err(MonitorInsertError::TooManyMonitorsPerConnection { max: self.max_per_connection, @@ -58,7 +55,7 @@ impl MonitorSet { entry.insert(nick); self.monitors_by_nickname .entry(nick) - .or_insert_with(HashSet::new) + .or_default() .insert(monitor); Ok(()) } @@ -131,7 +128,7 @@ impl MonitoredItem for update::UserNickChange { if self.user.nickname != self.new_nick { // Don't notify on case change notify_monitors(server, &self.user.nickname, || { - make_numeric!(MonOffline, &self.user.nickname.to_string()) + make_numeric!(MonOffline, self.user.nickname.as_ref()) })?; notify_monitors(server, &self.new_nick, || { make_numeric!( @@ -151,7 +148,7 @@ impl MonitoredItem for update::UserNickChange { impl MonitoredItem for update::UserQuit { fn try_notify_monitors(&self, server: &ClientServer) -> Result<()> { notify_monitors(server, &self.user.nickname, || { - make_numeric!(MonOffline, &self.user.nickname.to_string()) + make_numeric!(MonOffline, self.user.nickname.as_ref()) }) } } diff --git a/sable_ircd/src/server/async_handler_collection.rs b/sable_ircd/src/server/async_handler_collection.rs index 0056c0bb..af03ab3c 100644 --- a/sable_ircd/src/server/async_handler_collection.rs +++ b/sable_ircd/src/server/async_handler_collection.rs @@ -19,7 +19,7 @@ impl<'a> AsyncHandlerCollection<'a> { pub async fn poll(&mut self) { // Poll as many as possible of the futures we're storing - while let Some(_) = self.futures.next().await {} + while (self.futures.next().await).is_some() {} } pub fn is_empty(&self) -> bool { diff --git a/sable_ircd/src/server/command_action.rs b/sable_ircd/src/server/command_action.rs index 70549692..1a8f06b9 100644 --- a/sable_ircd/src/server/command_action.rs +++ b/sable_ircd/src/server/command_action.rs @@ -10,7 +10,7 @@ impl ClientServer { conn.send(make_numeric!(YoureBanned, &reason).format_for(self, &UnknownTarget)); } SaslRequired(reason) => { - if reason.len() > 0 { + if !reason.is_empty() { conn.send(message::Notice::new( self, &UnknownTarget, @@ -56,7 +56,7 @@ impl ClientServer { } // If we get this far, we're registering a new user - if let Err(e) = self.check_user_access(&*self.network(), &*conn) { + if let Err(e) = self.check_user_access(&self.network(), &conn) { self.notify_access_error(&e, conn.as_ref()); RwLockUpgradableReadGuard::upgrade(connections).remove(connection_id); return; @@ -82,7 +82,7 @@ impl ClientServer { nickname: *pre_client.nick.get().unwrap(), username: *pre_client.user.get().unwrap(), visible_hostname: *pre_client.hostname.get().unwrap(), - realname: pre_client.realname.get().unwrap().clone(), + realname: *pre_client.realname.get().unwrap(), mode: state::UserMode::new(umodes), server: self.node.id(), account: pre_client.sasl_account.get().cloned(), diff --git a/sable_ircd/src/server/config.rs b/sable_ircd/src/server/config.rs index 3ab02985..0f32e31b 100644 --- a/sable_ircd/src/server/config.rs +++ b/sable_ircd/src/server/config.rs @@ -36,7 +36,7 @@ impl ServerInfoStrings { pub fn load(raw_info: &RawServerInfo) -> Result { Ok(Self { motd: Self::get_info(&raw_info.motd, "motd")? - .and_then(|file| Some(file.lines().map(|v| v.to_string()).collect())), + .map(|file| file.lines().map(|v| v.to_string()).collect()), admin_info: raw_info.admin.clone(), }) } @@ -46,16 +46,14 @@ impl ServerInfoStrings { name: &str, ) -> Result, ConfigProcessingError> { match path { - Some(real_path) => Ok(Some(Self::read(&real_path, name)?)), + Some(real_path) => Ok(Some(Self::read(real_path, name)?)), None => Ok(None), } } fn read(path: &PathBuf, name: &str) -> Result { - fs::read_to_string(path).or_else(|err| { - Err(ConfigProcessingError { - reason: format!("Unable to read info {name:?} from {path:?}: {err}"), - }) + fs::read_to_string(path).map_err(|err| ConfigProcessingError { + reason: format!("Unable to read info {name:?} from {path:?}: {err}"), }) } } diff --git a/sable_ircd/src/server/mod.rs b/sable_ircd/src/server/mod.rs index 0cdcf009..1c983dd1 100644 --- a/sable_ircd/src/server/mod.rs +++ b/sable_ircd/src/server/mod.rs @@ -343,7 +343,7 @@ impl ClientServer { for (conn_id, message) in connections.poll_messages().collect::>() { if let Some(parsed) = ClientMessage::parse(conn_id, &message) { if let Ok(connection) = connections.get(conn_id) { - if let Ok(command) = ClientCommand::new(Arc::clone(&self), connection, parsed) { + if let Ok(command) = ClientCommand::new(Arc::clone(self), connection, parsed) { if let Some(async_handler) = self.command_dispatcher.dispatch_command(command) { @@ -398,7 +398,7 @@ impl ClientServer { let mut reap_preclients_timer = time::interval(Duration::from_secs(60)); - let shutdown_action = loop { + loop { // tracing::trace!("ClientServer run loop"); // Before looking for an I/O event, do our internal bookkeeping. // First, take inbound client messages and process them @@ -520,8 +520,6 @@ impl ClientServer { } }, } - }; - - shutdown_action + } } } diff --git a/sable_ircd/src/server/server_type.rs b/sable_ircd/src/server/server_type.rs index 52559699..b4444912 100644 --- a/sable_ircd/src/server/server_type.rs +++ b/sable_ircd/src/server/server_type.rs @@ -87,7 +87,7 @@ impl sable_server::ServerType for ClientServer { myinfo: Self::build_myinfo(), isupport: Self::build_basic_isupport(&config), client_caps: CapabilityRepository::new(), - node: node, + node, listeners: Movable::new(client_listeners), info_strings: config.info_strings, monitors: MonitorSet::new(config.monitor.max_per_connection.into()).into(), diff --git a/sable_ircd/src/server/update_handler.rs b/sable_ircd/src/server/update_handler.rs index fcbf3efd..d165f843 100644 --- a/sable_ircd/src/server/update_handler.rs +++ b/sable_ircd/src/server/update_handler.rs @@ -15,16 +15,16 @@ impl ClientServer { if let Some(entry) = history.get(entry_id) { match &entry.details { NetworkStateChange::NewUser(detail) => { - detail.notify_monitors(&self); + detail.notify_monitors(self); } NetworkStateChange::UserNickChange(detail) => { - detail.notify_monitors(&self); + detail.notify_monitors(self); } NetworkStateChange::UserQuit(detail) => { - detail.notify_monitors(&self); + detail.notify_monitors(self); } NetworkStateChange::BulkUserQuit(detail) => { - detail.notify_monitors(&self); + detail.notify_monitors(self); } NetworkStateChange::NewUserConnection(detail) => { let new_user_connection = detail.clone(); diff --git a/sable_ircd/src/utils/line_wrapper.rs b/sable_ircd/src/utils/line_wrapper.rs index 03383eb2..97143d1d 100644 --- a/sable_ircd/src/utils/line_wrapper.rs +++ b/sable_ircd/src/utils/line_wrapper.rs @@ -19,7 +19,7 @@ impl, Iter: Iterator> buf.push_str(item.as_ref()); buf }), - iter: iter, + iter, } } } @@ -34,7 +34,7 @@ impl, Iter: Iterator> Iterator return None; }; - while let Some(item) = self.iter.next() { + for item in self.iter.by_ref() { let item = item.as_ref(); if buf.as_bytes().len() + JOINER.len_utf8() + item.as_bytes().len() <= self.line_length { diff --git a/sable_macros/src/lib.rs b/sable_macros/src/lib.rs index b22845e7..7483bb41 100644 --- a/sable_macros/src/lib.rs +++ b/sable_macros/src/lib.rs @@ -1,5 +1,5 @@ #![allow(clippy::large_enum_variant)] -#![allow(clippy::eval_order_dependence)] +#![allow(clippy::mixed_read_write_in_expression)] extern crate proc_macro; diff --git a/sable_network/src/history/log.rs b/sable_network/src/history/log.rs index 115213a4..f4c81138 100644 --- a/sable_network/src/history/log.rs +++ b/sable_network/src/history/log.rs @@ -176,9 +176,7 @@ impl NetworkHistoryLog { } None => { let mut user_logs_write = RwLockUpgradableReadGuard::upgrade(user_logs); - let log = user_logs_write - .entry(user_id) - .or_insert_with(ConcurrentLog::new); + let log = user_logs_write.entry(user_id).or_default(); log.push(entry_id); } }; diff --git a/sable_network/src/network/ban/repository.rs b/sable_network/src/network/ban/repository.rs index b2381832..ea320dec 100644 --- a/sable_network/src/network/ban/repository.rs +++ b/sable_network/src/network/ban/repository.rs @@ -101,33 +101,33 @@ impl BanRepository { &self, matching: &PreRegistrationBanSettings, ) -> impl Iterator { - let matches = self.pre_registration_engine.eval(&matching); + let matches = self.pre_registration_engine.eval(matching); matches .into_iter() - .filter_map(move |id| self.pre_registration_bans.get(&id)) + .filter_map(move |id| self.pre_registration_bans.get(id)) } pub fn find_new_connection( &self, matching: &NewConnectionBanSettings, ) -> impl Iterator { - let matches = self.new_connection_engine.eval(&matching); + let matches = self.new_connection_engine.eval(matching); matches .into_iter() - .filter_map(move |id| self.new_connection_bans.get(&id)) + .filter_map(move |id| self.new_connection_bans.get(id)) } pub fn find_pre_sasl( &self, matching: &PreSaslBanSettings, ) -> impl Iterator { - let matches = self.pre_sasl_engine.eval(&matching); + let matches = self.pre_sasl_engine.eval(matching); matches .into_iter() - .filter_map(move |id| self.pre_sasl_bans.get(&id)) + .filter_map(move |id| self.pre_sasl_bans.get(id)) } fn compile_engine( diff --git a/sable_network/src/network/event/tests.rs b/sable_network/src/network/event/tests.rs index 16d01e66..b7c168d9 100644 --- a/sable_network/src/network/event/tests.rs +++ b/sable_network/src/network/event/tests.rs @@ -3,7 +3,7 @@ use crate::prelude::*; fn build_event_ids(input: &[[i64; 3]]) -> Vec { let mut ret = Vec::new(); - for v in input.into_iter() { + for v in input.iter() { ret.push(EventId::new(ServerId::new(v[0]), EpochId::new(v[1]), v[2])); } ret @@ -11,7 +11,7 @@ fn build_event_ids(input: &[[i64; 3]]) -> Vec { fn clock_from(ids: &[EventId]) -> EventClock { let mut ret = EventClock::new(); - for id in ids.into_iter() { + for id in ids.iter() { ret.update_with_id(*id); } ret diff --git a/sable_network/src/network/network/accessors.rs b/sable_network/src/network/network/accessors.rs index 31996bac..d2cdea6d 100644 --- a/sable_network/src/network/network/accessors.rs +++ b/sable_network/src/network/network/accessors.rs @@ -82,7 +82,7 @@ impl Network { /// otherwise a hashed nickname (as used in collision resolution) is returned pub fn infallible_nick_for_user(&self, user: UserId) -> Nickname { if let Some((nick, _)) = self.find_alias_user_with_id(user) { - nick.clone() + *nick } else if let Ok(binding) = self.nick_binding_for_user(user) { binding.nick() } else { @@ -153,7 +153,7 @@ impl Network { self.channels .values() .find(|x| &x.name == name) - .ok_or_else(|| NoSuchChannelName(*name)) + .ok_or(NoSuchChannelName(*name)) } /// Look up a channel by name. @@ -161,7 +161,7 @@ impl Network { self.channels .values() .find(|x| &x.name == name) - .ok_or_else(|| NoSuchChannelName(*name)) + .ok_or(NoSuchChannelName(*name)) .wrap(self) } @@ -257,7 +257,7 @@ impl Network { self.current_services .as_ref() .and_then(|state| self.servers.get(&state.server_id)) - .map(|s| s.name.clone()) + .map(|s| s.name) } /// Retrieve the current services data @@ -285,7 +285,7 @@ impl Network { self.accounts .values() .find(|a| &a.name == name) - .ok_or_else(|| LookupError::NoSuchAccountNamed(name.clone())) + .ok_or(LookupError::NoSuchAccountNamed(*name)) .wrap(self) } diff --git a/sable_network/src/network/network/alias_users.rs b/sable_network/src/network/network/alias_users.rs index cffac2e4..aa57f51a 100644 --- a/sable_network/src/network/network/alias_users.rs +++ b/sable_network/src/network/network/alias_users.rs @@ -7,12 +7,12 @@ impl Network { for (id, user_config) in self.config.alias_users.iter().enumerate() { // Create alias users with invalid ID and server ID alias_users.insert( - user_config.nick.clone(), + user_config.nick, state::User { id: UserId::new(ServerId::new(0), EpochId::new(0), id as LocalId), - user: user_config.user.clone(), - visible_host: user_config.host.clone(), - realname: user_config.realname.clone(), + user: user_config.user, + visible_host: user_config.host, + realname: user_config.realname, mode: state::UserMode::new(UserModeSet::new()), oper_privileges: None, away_reason: None, // Never away diff --git a/sable_network/src/network/network/default_roles.rs b/sable_network/src/network/network/default_roles.rs index b2dd1684..62a92984 100644 --- a/sable_network/src/network/network/default_roles.rs +++ b/sable_network/src/network/network/default_roles.rs @@ -18,7 +18,7 @@ impl Network { id: DEFAULT_ROLE_ID, name: name.clone(), channel: None, - flags: flags.clone(), + flags: *flags, }; new_cache.insert(name.clone(), cache_role); diff --git a/sable_network/src/network/network/mod.rs b/sable_network/src/network/network/mod.rs index c9e7d19d..09fb34ff 100644 --- a/sable_network/src/network/network/mod.rs +++ b/sable_network/src/network/network/mod.rs @@ -217,7 +217,7 @@ impl Network { })?; self.clock.update_with_id(event.id); - updates.notify(EventComplete {}, &event); + updates.notify(EventComplete {}, event); Ok(()) } diff --git a/sable_network/src/network/network/user_state.rs b/sable_network/src/network/network/user_state.rs index 0dffafc3..e573d563 100644 --- a/sable_network/src/network/network/user_state.rs +++ b/sable_network/src/network/network/user_state.rs @@ -30,10 +30,9 @@ impl Network { let removed_nickname = if let Ok(binding) = self.nick_binding_for_user(user.id) { let nick = binding.nick(); self.nick_bindings.remove(&nick); - let historic_nick_users = - self.historic_nick_users.entry(nick.clone()).or_insert_with( - || VecDeque::with_capacity(8), // arbitrary power of two - ); + let historic_nick_users = self.historic_nick_users.entry(nick).or_insert_with( + || VecDeque::with_capacity(8), // arbitrary power of two + ); if historic_nick_users.len() == historic_nick_users.capacity() { historic_nick_users.pop_back(); } @@ -205,9 +204,9 @@ impl Network { target, detail.username, detail.visible_hostname, - detail.realname.clone(), + detail.realname, detail.mode.clone(), - detail.account.clone(), + detail.account, ); // First insert the user (with no nickname yet) so that the nick binding can see @@ -250,8 +249,8 @@ impl Network { updates: &dyn NetworkUpdateReceiver, ) { if let Some(user) = self.users.get_mut(&target) { - let new_reason = update.reason.clone(); - let mut old_reason = new_reason.clone(); + let new_reason = update.reason; + let mut old_reason = new_reason; std::mem::swap(&mut user.away_reason, &mut old_reason); let update_user = user.clone(); diff --git a/sable_network/src/network/state/access_flag.rs b/sable_network/src/network/state/access_flag.rs index f9cb4769..4d9850fa 100644 --- a/sable_network/src/network/state/access_flag.rs +++ b/sable_network/src/network/state/access_flag.rs @@ -231,7 +231,7 @@ impl From for HumanReadableChannelAccessSet { impl std::fmt::Display for HumanReadableChannelAccessSet { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let vec: Vec<_> = self.0.clone().into(); + let vec: Vec<_> = self.0.into(); let names: Vec<_> = vec.iter().map(ToString::to_string).collect(); f.write_str(&names.join(",")) @@ -243,7 +243,7 @@ impl serde_with::SerializeAs for HumanReadableChannelAccessSet where S: serde::Serializer, { - let vec: Vec = source.clone().into(); + let vec: Vec = (*source).into(); vec.serialize(serializer) } } @@ -263,7 +263,7 @@ impl serde::Serialize for HumanReadableChannelAccessSet { where S: serde::Serializer, { - let vec: Vec = self.0.clone().into(); + let vec: Vec = self.0.into(); vec.serialize(serializer) } } diff --git a/sable_network/src/network/tests/fixtures.rs b/sable_network/src/network/tests/fixtures.rs index 511a16bc..75816772 100644 --- a/sable_network/src/network/tests/fixtures.rs +++ b/sable_network/src/network/tests/fixtures.rs @@ -43,7 +43,7 @@ impl NetworkBuilder { self.id_gen.next_channel(), details::NewChannel { mode: state::ChannelMode::new(ChannelModeSet::default()), - name: name, + name, }, ); } diff --git a/sable_network/src/network/wrapper/account.rs b/sable_network/src/network/wrapper/account.rs index 16e579c8..f1c7976f 100644 --- a/sable_network/src/network/wrapper/account.rs +++ b/sable_network/src/network/wrapper/account.rs @@ -36,7 +36,7 @@ impl Account<'_> { } pub fn fingerprints(&self) -> &Vec { - &&self.data.authorised_fingerprints + &self.data.authorised_fingerprints } } diff --git a/sable_network/src/network/wrapper/channel_role.rs b/sable_network/src/network/wrapper/channel_role.rs index bf3f302c..35a6643c 100644 --- a/sable_network/src/network/wrapper/channel_role.rs +++ b/sable_network/src/network/wrapper/channel_role.rs @@ -13,8 +13,7 @@ impl ChannelRole<'_> { pub fn channel(&self) -> Option { self.data .channel - .map(|id| self.network.channel_registration(id).ok()) - .flatten() + .and_then(|id| self.network.channel_registration(id).ok()) } pub fn name(&self) -> &state::ChannelRoleName { diff --git a/sable_network/src/network/wrapper/services.rs b/sable_network/src/network/wrapper/services.rs index e5d33e08..7059d729 100644 --- a/sable_network/src/network/wrapper/services.rs +++ b/sable_network/src/network/wrapper/services.rs @@ -17,7 +17,7 @@ impl ServicesData<'_> { } pub fn server_name(&self) -> LookupResult { - self.server().map(|s| s.name().clone()) + self.server().map(|s| *s.name()) } pub fn sasl_mechanisms(&self) -> &Vec { diff --git a/sable_network/src/node/mod.rs b/sable_network/src/node/mod.rs index d1dc3408..cbc6f1cf 100644 --- a/sable_network/src/node/mod.rs +++ b/sable_network/src/node/mod.rs @@ -54,6 +54,7 @@ where } impl NetworkNode { + #[allow(clippy::too_many_arguments)] /// Construct a network node. /// /// Arguments: @@ -179,7 +180,7 @@ impl NetworkNode { fn build_version() -> String { let git_version = crate::build_data::GIT_COMMIT_HASH .map(|s| format!("-{}", s)) - .unwrap_or_else(String::new); + .unwrap_or_default(); let git_dirty = if matches!(crate::build_data::GIT_DIRTY, Some(true)) { "-dirty".to_string() } else { diff --git a/sable_network/src/node/update_receiver.rs b/sable_network/src/node/update_receiver.rs index e6c4adee..4086debb 100644 --- a/sable_network/src/node/update_receiver.rs +++ b/sable_network/src/node/update_receiver.rs @@ -85,7 +85,7 @@ impl NetworkNode { let mut notified = HashSet::new(); for m1 in &detail.memberships { - let m1: wrapper::Membership = ObjectWrapper::wrap(&*net, m1); + let m1: wrapper::Membership = ObjectWrapper::wrap(&net, m1); for m2 in m1.channel()?.members() { notified.insert(m2.user_id()); } @@ -118,7 +118,7 @@ impl NetworkNode { detail: &update::ChannelModeChange, ) -> HandleResult { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members(&channel, entry); @@ -131,7 +131,7 @@ impl NetworkNode { detail: &update::ListModeAdded, ) -> HandleResult { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members_where(&channel, entry, |m| { self.policy_service @@ -147,7 +147,7 @@ impl NetworkNode { detail: &update::ListModeRemoved, ) -> HandleResult { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members_where(&channel, entry, |m| { self.policy_service @@ -163,7 +163,7 @@ impl NetworkNode { detail: &update::ChannelTopicChange, ) -> HandleResult { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members(&channel, entry); @@ -176,7 +176,7 @@ impl NetworkNode { detail: &update::MembershipFlagChange, ) -> HandleResult { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members(&channel, entry); @@ -185,7 +185,7 @@ impl NetworkNode { fn handle_join(&self, entry: &HistoryLogEntry, detail: &update::ChannelJoin) -> HandleResult { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members(&channel, entry); @@ -196,7 +196,7 @@ impl NetworkNode { self.notify_user(detail.user.user.id, entry.id); let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members(&channel, entry); @@ -207,7 +207,7 @@ impl NetworkNode { self.notify_user(detail.user.user.id, entry.id); let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members(&channel, entry); @@ -230,7 +230,7 @@ impl NetworkNode { detail: &update::ChannelRename, ) -> HandleResult { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, &detail.channel); + let channel = wrapper::Channel::wrap(&network, &detail.channel); self.notify_channel_members(&channel, entry); @@ -245,7 +245,7 @@ impl NetworkNode { match &detail.target { update::HistoricMessageTarget::Channel(channel) => { let network = self.network(); - let channel = wrapper::Channel::wrap(&*network, channel); + let channel = wrapper::Channel::wrap(&network, channel); self.notify_channel_members(&channel, entry); } diff --git a/sable_network/src/policy/ban_resolver.rs b/sable_network/src/policy/ban_resolver.rs index 130ac1ff..bbe8a890 100644 --- a/sable_network/src/policy/ban_resolver.rs +++ b/sable_network/src/policy/ban_resolver.rs @@ -11,12 +11,8 @@ pub trait BanResolver { user: &User, list: &'a ListMode<'a>, ) -> Option> { - for entry in list.entries() { - if self.user_matches_entry(user, &entry) { - return Some(entry); - } - } - None + list.entries() + .find(|entry| self.user_matches_entry(user, entry)) } } diff --git a/sable_network/src/policy/oper_policy.rs b/sable_network/src/policy/oper_policy.rs index 72959d6c..e3b03428 100644 --- a/sable_network/src/policy/oper_policy.rs +++ b/sable_network/src/policy/oper_policy.rs @@ -1,3 +1,5 @@ +#![allow(clippy::crate_in_macro_def)] + use super::*; /// Makes authentication decisions for users attempting to gain oper access diff --git a/sable_network/src/policy/standard_channel_policy.rs b/sable_network/src/policy/standard_channel_policy.rs index 287241d2..7aa86bbd 100644 --- a/sable_network/src/policy/standard_channel_policy.rs +++ b/sable_network/src/policy/standard_channel_policy.rs @@ -47,6 +47,7 @@ fn has_default_access(channel: &Channel) -> Option { .map(|r| r.flags()) } +#[allow(clippy::if_same_then_else)] fn has_access(user: &User, channel: &Channel, flag: ChannelAccessFlag) -> PermissionResult { let assigned = has_assigned_access(user, channel); let ephemeral = has_ephemeral_access(user, channel); diff --git a/sable_network/src/sync/config.rs b/sable_network/src/sync/config.rs index ef2c45b5..cebaefd5 100644 --- a/sable_network/src/sync/config.rs +++ b/sable_network/src/sync/config.rs @@ -64,8 +64,8 @@ impl SyncConfig { let mut config = String::new(); file.read_to_string(&mut config) .map_err(|e| ConfigError::IoError(e, filename.as_ref().to_owned()))?; - Ok(json5::from_str(&config) - .map_err(|e| ConfigError::JsonError(e, filename.as_ref().to_owned()))?) + json5::from_str(&config) + .map_err(|e| ConfigError::JsonError(e, filename.as_ref().to_owned())) } /// Load and return the CA certificate for the network from the referenced @@ -96,8 +96,8 @@ impl NodeConfig { let mut config = String::new(); file.read_to_string(&mut config) .map_err(|e| ConfigError::IoError(e, filename.as_ref().to_owned()))?; - Ok(json5::from_str(&config) - .map_err(|e| ConfigError::JsonError(e, filename.as_ref().to_owned()))?) + json5::from_str(&config) + .map_err(|e| ConfigError::JsonError(e, filename.as_ref().to_owned())) } /// Load and return the client certificate and private key for this node diff --git a/sable_network/src/sync/eventlog.rs b/sable_network/src/sync/eventlog.rs index 6a1611d2..c36011fc 100644 --- a/sable_network/src/sync/eventlog.rs +++ b/sable_network/src/sync/eventlog.rs @@ -189,7 +189,7 @@ impl EventLog { let s = e.id.server(); let id = e.id; - self.history.entry(s).or_insert_with(BTreeMap::new); + self.history.entry(s).or_default(); let server_map = self.history.get_mut(&s).unwrap(); server_map.insert(e.id, e); diff --git a/sable_network/src/sync/network.rs b/sable_network/src/sync/network.rs index ab90c316..9eb1d880 100644 --- a/sable_network/src/sync/network.rs +++ b/sable_network/src/sync/network.rs @@ -168,12 +168,12 @@ impl GossipNetwork { pub fn save_state(&self) -> GossipNetworkState { GossipNetworkState { - server_name: self.me.name.clone(), + server_name: self.me.name, peer_states: self .task_state .peers .iter() - .map(|peer| (peer.conf.name.clone(), peer.enabled.load(Ordering::SeqCst))) + .map(|peer| (peer.conf.name, peer.enabled.load(Ordering::SeqCst))) .collect(), } } @@ -241,7 +241,7 @@ impl GossipNetwork { } /// Choose a peer at random that isn't in the provided list - pub fn choose_peer_except(&self, except: &Vec) -> Option<&PeerConfig> { + pub fn choose_peer_except(&self, except: &[ServerName]) -> Option<&PeerConfig> { let ret = self .task_state .peers @@ -341,7 +341,7 @@ impl GossipNetwork { }; let socket = Self::get_socket_for_addr(local_addr)?; - socket.bind(local_addr.clone())?; + socket.bind(*local_addr)?; match socket.connect(ip_addr).await { Ok(conn) => { tracing::info!("Connected to {} ({})", host_addr, ip_addr); @@ -374,7 +374,7 @@ impl GossipNetwork { local_addr.set_port(0); let connector = TlsConnector::from(Arc::clone(&self.tls_client_config)); let conn = Self::connect(&local_addr, &peer.address).await?; - let server_name = (&peer.name.value() as &str) + let server_name = (peer.name.value() as &str) .try_into() .expect("Invalid server name"); let stream = connector.connect(server_name, conn).await?; @@ -575,7 +575,7 @@ impl NetworkTaskState { let (req_send, mut req_recv) = channel(8); let req = Request { - received_from: peer_name.clone(), + received_from: peer_name, response: req_send, message: msg, }; diff --git a/sable_network/src/sync/replicated_log.rs b/sable_network/src/sync/replicated_log.rs index 230888c7..b6cfbb95 100644 --- a/sable_network/src/sync/replicated_log.rs +++ b/sable_network/src/sync/replicated_log.rs @@ -276,8 +276,8 @@ impl ReplicatedEventLog { let (sender, receiver) = oneshot::channel(); let targeted_message = TargetedMessage { - source: self.net.me().name.clone(), - target: target, + source: self.net.me().name, + target, via: Vec::new(), content: request, }; @@ -333,6 +333,9 @@ impl ReplicatedEventLog { net } + #[allow(clippy::await_holding_refcell_ref)] // don't care about 'attempts' being borrowed too + // long, the closure can't be running more than + // once at a time. async fn start_sync_to_network( &self, sender: UnboundedSender, @@ -626,7 +629,7 @@ impl TaskState { // to try to send it along // Make sure it doesn't come back to us - detail.via.push(self.net.me().name.clone()); + detail.via.push(self.net.me().name); // Keep going until we succeed in sending it somewhere while let Some(peer) = self.net.choose_peer_except(&detail.via) { @@ -766,7 +769,7 @@ impl TaskState { // Then reset our list of active peers to those that are active in the incoming state for server in net.servers() { - self.net.enable_peer(&server.name()); + self.net.enable_peer(server.name()); } if let Err(e) = self diff --git a/sable_network/src/types/pattern.rs b/sable_network/src/types/pattern.rs index ef82cb36..9b568632 100644 --- a/sable_network/src/types/pattern.rs +++ b/sable_network/src/types/pattern.rs @@ -34,7 +34,7 @@ impl PartialEq for Pattern { impl PartialEq for Pattern { fn eq(&self, other: &str) -> bool { - &self.0 == other + self.0 == other } } diff --git a/sable_network/src/validated.rs b/sable_network/src/validated.rs index 60473802..6349ddfc 100644 --- a/sable_network/src/validated.rs +++ b/sable_network/src/validated.rs @@ -47,7 +47,7 @@ const DIGIT: &str = "0123456789"; define_validated! { AwayReason(ArrayString<{ AwayReason::LENGTH }>) { - if value.len() == 0 { + if value.is_empty() { Self::error(value) } else { Ok(()) @@ -67,7 +67,7 @@ define_validated! { } Username(ArrayString<{ Username::LENGTH }>) { - if value.len() == 0 { + if value.is_empty() { Self::error(value) } else { Ok(()) @@ -75,7 +75,7 @@ define_validated! { } Realname(ArrayString<{ Realname::LENGTH }>) { - if value.len() == 0 { + if value.is_empty() { Self::error(value) } else { Ok(()) @@ -119,7 +119,7 @@ define_validated! { return Self::error(value); } } - if value.len() == 0 { + if value.is_empty() { return Self::error(value); } Ok(()) diff --git a/sable_server/src/config.rs b/sable_server/src/config.rs index 0bf7fb93..96a4d654 100644 --- a/sable_server/src/config.rs +++ b/sable_server/src/config.rs @@ -112,9 +112,8 @@ pub fn load_network_config( let mut config = String::new(); file.read_to_string(&mut config) .map_err(|e| sable_network::sync::ConfigError::IoError(e, filename.as_ref().to_owned()))?; - Ok(json5::from_str(&config).map_err(|e| { - sable_network::sync::ConfigError::JsonError(e, filename.as_ref().to_owned()) - })?) + json5::from_str(&config) + .map_err(|e| sable_network::sync::ConfigError::JsonError(e, filename.as_ref().to_owned())) } impl From for LevelFilter { diff --git a/sable_services/src/hashing.rs b/sable_services/src/hashing.rs index ca063a80..4d1b0f7a 100644 --- a/sable_services/src/hashing.rs +++ b/sable_services/src/hashing.rs @@ -14,7 +14,7 @@ const fn default_bcrypt_cost() -> u32 { /// [`bcrypt::Version`] but it's Serde-deserializable /// /// [Bcrypt versions](https://en.wikipedia.org/wiki/Bcrypt#Versioning_history) -#[derive(Deserialize, Clone)] +#[derive(Deserialize, Clone, Default)] pub enum BcryptVersion { #[serde(rename = "2a")] TwoA, @@ -23,15 +23,10 @@ pub enum BcryptVersion { #[serde(rename = "2y")] TwoY, #[serde(rename = "2b")] + #[default] TwoB, } -impl Default for BcryptVersion { - fn default() -> BcryptVersion { - BcryptVersion::TwoB - } -} - impl From for bcrypt::Version { fn from(v: BcryptVersion) -> bcrypt::Version { match v { diff --git a/sable_services/src/server/command/channel_commands.rs b/sable_services/src/server/command/channel_commands.rs index ad0a86f4..b726e93c 100644 --- a/sable_services/src/server/command/channel_commands.rs +++ b/sable_services/src/server/command/channel_commands.rs @@ -14,7 +14,7 @@ impl ServicesServer { let new_channel_registration = state::ChannelRegistration { id: self.node.ids().next_channel_registration(), - channelname: channel.name().clone(), + channelname: *channel.name(), }; let new_channel_registration = diff --git a/sable_services/src/server/sasl/plain.rs b/sable_services/src/server/sasl/plain.rs index 3a097d6a..1ab58887 100644 --- a/sable_services/src/server/sasl/plain.rs +++ b/sable_services/src/server/sasl/plain.rs @@ -22,7 +22,7 @@ impl SaslMechanism for SaslPlain { _ => return Ok(Fail), }; - let account_name = std::str::from_utf8(&account_name)?; + let account_name = std::str::from_utf8(account_name)?; let account_name = Nickname::from_str(account_name)?; let account = server.db.account_named(&account_name)?;