From 54502ad61b23b8129918e06a129bc0da4ccbbf39 Mon Sep 17 00:00:00 2001 From: Natsu Kagami Date: Sun, 22 Oct 2023 17:45:13 +0200 Subject: [PATCH] Massive lint fix --- youmubot-cf/src/announcer.rs | 12 +++++------ youmubot-cf/src/embed.rs | 6 +++--- youmubot-cf/src/hook.rs | 6 +++--- youmubot-cf/src/lib.rs | 18 ++++++++-------- youmubot-cf/src/live.rs | 16 ++++++-------- youmubot-core/src/admin/soft_ban.rs | 10 ++++----- youmubot-core/src/community/mod.rs | 2 +- youmubot-core/src/community/roles.rs | 22 +++++++++---------- youmubot-core/src/community/votes.rs | 2 +- youmubot-core/src/db.rs | 2 +- youmubot-core/src/fun/images.rs | 2 +- youmubot-core/src/fun/mod.rs | 2 +- youmubot-osu/src/discord/announcer.rs | 8 +++---- youmubot-osu/src/discord/beatmap_cache.rs | 2 +- youmubot-osu/src/discord/display.rs | 2 +- youmubot-osu/src/discord/embeds.rs | 26 +++++++++++------------ youmubot-osu/src/discord/hook.rs | 25 +++++++++++----------- youmubot-osu/src/discord/mod.rs | 24 ++++++++++----------- youmubot-osu/src/discord/oppai_cache.rs | 10 ++++----- youmubot-osu/src/discord/server_rank.rs | 2 +- youmubot-osu/src/lib.rs | 8 +++---- youmubot-osu/src/models/parse.rs | 4 ++-- youmubot-osu/src/test.rs | 2 +- youmubot-prelude/src/announcer.rs | 10 ++++----- youmubot-prelude/src/args.rs | 6 +++--- youmubot-prelude/src/flags.rs | 2 +- youmubot-prelude/src/pagination.rs | 4 ++-- youmubot/src/main.rs | 4 ++-- 28 files changed, 117 insertions(+), 122 deletions(-) diff --git a/youmubot-cf/src/announcer.rs b/youmubot-cf/src/announcer.rs index e36986d..64e2993 100644 --- a/youmubot-cf/src/announcer.rs +++ b/youmubot-cf/src/announcer.rs @@ -24,14 +24,14 @@ impl youmubot_prelude::Announcer for Announcer { ) -> Result<()> { let data = data.read().await; let client = data.get::().unwrap(); - let mut users = CfSavedUsers::open(&*data).borrow()?.clone(); + let mut users = CfSavedUsers::open(&data).borrow()?.clone(); users .iter_mut() .map(|(user_id, cfu)| { let http = http.clone(); let channels = &channels; async move { - if let Err(e) = update_user(http, &channels, &client, *user_id, cfu).await { + if let Err(e) = update_user(http, channels, client, *user_id, cfu).await { cfu.failures += 1; eprintln!( "Codeforces: cannot update user {}: {} [{} failures]", @@ -45,7 +45,7 @@ impl youmubot_prelude::Announcer for Announcer { .collect::>() .collect::<()>() .await; - let mut db = CfSavedUsers::open(&*data); + let mut db = CfSavedUsers::open(&data); let mut db = db.borrow_mut()?; for (key, user) in users { match db.get(&key).map(|v| v.last_update) { @@ -74,13 +74,13 @@ async fn update_user( user_id: UserId, cfu: &mut CfUser, ) -> Result<()> { - let info = User::info(&*client, &[cfu.handle.as_str()]) + let info = User::info(client, &[cfu.handle.as_str()]) .await? .into_iter() .next() .ok_or_else(|| Error::msg("Not found"))?; - let rating_changes = info.rating_changes(&*client).await?; + let rating_changes = info.rating_changes(client).await?; let channels_list = channels.channels_of(&http, user_id).await; cfu.last_update = Utc::now(); @@ -119,7 +119,7 @@ async fn update_user( return Ok(()); } let (contest, _, _) = - codeforces::Contest::standings(&*client, rc.contest_id, |f| f.limit(1, 1)) + codeforces::Contest::standings(client, rc.contest_id, |f| f.limit(1, 1)) .await?; channels .iter() diff --git a/youmubot-cf/src/embed.rs b/youmubot-cf/src/embed.rs index 5387cd2..3551645 100644 --- a/youmubot-cf/src/embed.rs +++ b/youmubot-cf/src/embed.rs @@ -26,7 +26,7 @@ pub fn user_embed<'a>(user: &User, e: &'a mut CreateEmbed) -> &'a mut CreateEmbe .join(", "); e.color(user.color()) .author(|a| a.name(&rank)) - .thumbnail(format!("{}", user.title_photo)) + .thumbnail(user.title_photo.to_string()) .title(&user.handle) .url(user.profile_url()) .description(format!( @@ -63,7 +63,7 @@ pub fn rating_change_embed<'a>( user_id: serenity::model::id::UserId, e: &'a mut CreateEmbed, ) -> &'a mut CreateEmbed { - let delta = (rating_change.new_rating as i64) - (rating_change.old_rating as i64); + let delta = rating_change.new_rating - rating_change.old_rating; let color = if delta < 0 { 0xff0000 } else { 0x00ff00 }; let message = if delta > 0 { MessageBuilder::new() @@ -90,7 +90,7 @@ pub fn rating_change_embed<'a>( }; e.author(|a| { - a.icon_url(format!("{}", &user.avatar)) + a.icon_url(user.avatar.to_string()) .url(user.profile_url()) .name(&user.handle) }) diff --git a/youmubot-cf/src/hook.rs b/youmubot-cf/src/hook.rs index c3750fc..01aa85e 100644 --- a/youmubot-cf/src/hook.rs +++ b/youmubot-cf/src/hook.rs @@ -53,8 +53,8 @@ impl ContestCache { async fn fetch_contest_list(http: Client) -> Result> { log::info!("Fetching contest list, this might take a few seconds to complete..."); - let gyms = Contest::list(&*http, true).await?; - let contests = Contest::list(&*http, false).await?; + let gyms = Contest::list(&http, true).await?; + let contests = Contest::list(&http, false).await?; let r: StdHashMap = gyms .into_iter() .chain(contests.into_iter()) @@ -78,7 +78,7 @@ impl ContestCache { &self, contest_id: u64, ) -> Result<(Contest, Option>)> { - let (c, p) = match Contest::standings(&*self.http, contest_id, |f| f.limit(1, 1)).await { + let (c, p) = match Contest::standings(&self.http, contest_id, |f| f.limit(1, 1)).await { Ok((c, p, _)) => (c, Some(p)), Err(codeforces::Error::Codeforces(s)) if s.ends_with("has not started") => { let c = self.get_from_list(contest_id).await?; diff --git a/youmubot-cf/src/lib.rs b/youmubot-cf/src/lib.rs index fec0e31..a24adf9 100644 --- a/youmubot-cf/src/lib.rs +++ b/youmubot-cf/src/lib.rs @@ -63,7 +63,7 @@ pub async fn profile(ctx: &Context, m: &Message, mut args: Args) -> CommandResul let handle = match handle { UsernameArg::Raw(s) => s, UsernameArg::Tagged(u) => { - let db = CfSavedUsers::open(&*data); + let db = CfSavedUsers::open(&data); let user = db.borrow()?.get(&u).map(|u| u.handle.clone()); match user { Some(v) => v, @@ -75,7 +75,7 @@ pub async fn profile(ctx: &Context, m: &Message, mut args: Args) -> CommandResul } }; - let account = codeforces::User::info(&*http, &[&handle[..]]) + let account = codeforces::User::info(http, &[&handle[..]]) .await? .into_iter() .next(); @@ -107,7 +107,7 @@ pub async fn save(ctx: &Context, m: &Message, mut args: Args) -> CommandResult { let handle = args.single::()?; let http = data.get::().unwrap(); - let account = codeforces::User::info(&*http, &[&handle[..]]) + let account = codeforces::User::info(http, &[&handle[..]]) .await? .into_iter() .next(); @@ -119,8 +119,8 @@ pub async fn save(ctx: &Context, m: &Message, mut args: Args) -> CommandResult { } Some(acc) => { // Collect rating changes data. - let rating_changes = acc.rating_changes(&*http).await?; - let mut db = CfSavedUsers::open(&*data); + let rating_changes = acc.rating_changes(http).await?; + let mut db = CfSavedUsers::open(&data); m.reply( &ctx, format!("account `{}` has been linked to your account.", &acc.handle), @@ -141,7 +141,7 @@ pub async fn save(ctx: &Context, m: &Message, mut args: Args) -> CommandResult { pub async fn ranks(ctx: &Context, m: &Message) -> CommandResult { let data = ctx.data.read().await; let everyone = { - let db = CfSavedUsers::open(&*data); + let db = CfSavedUsers::open(&data); let db = db.borrow()?; db.iter().map(|(k, v)| (*k, v.clone())).collect::>() }; @@ -254,7 +254,7 @@ pub async fn contestranks(ctx: &Context, m: &Message, mut args: Args) -> Command let contest_id: u64 = args.single()?; let guild = m.guild_id.unwrap(); // Guild-only command let member_cache = data.get::().unwrap(); - let members = CfSavedUsers::open(&*data).borrow()?.clone(); + let members = CfSavedUsers::open(&data).borrow()?.clone(); let members = members .into_iter() .map(|(user_id, cf_user)| { @@ -267,8 +267,8 @@ pub async fn contestranks(ctx: &Context, m: &Message, mut args: Args) -> Command .collect::>() .await; let http = data.get::().unwrap(); - let (contest, problems, ranks) = Contest::standings(&*http, contest_id, |f| { - f.handles(members.iter().map(|(k, _)| k.clone()).collect()) + let (contest, problems, ranks) = Contest::standings(http, contest_id, |f| { + f.handles(members.keys().cloned().collect()) }) .await?; diff --git a/youmubot-cf/src/live.rs b/youmubot-cf/src/live.rs index bd8bf89..89c70fc 100644 --- a/youmubot-cf/src/live.rs +++ b/youmubot-cf/src/live.rs @@ -65,7 +65,7 @@ pub async fn watch_contest( contest_id: u64, ) -> Result<()> { let data = ctx.data.read().await; - let db = CfSavedUsers::open(&*data).borrow()?.clone(); + let db = CfSavedUsers::open(&data).borrow()?.clone(); let member_cache = data.get::().unwrap().clone(); let watch_data = data.get::().unwrap().clone(); @@ -130,7 +130,7 @@ pub async fn watch_contest( let http = data.get::().unwrap(); let (mut contest, problems, _) = - Contest::standings(&*http, contest_id, |f| f.limit(1, 1)).await?; + Contest::standings(http, contest_id, |f| f.limit(1, 1)).await?; // Collect an initial member list. // This never changes during the scan. let mut member_results: HashMap = db @@ -159,9 +159,7 @@ pub async fn watch_contest( e.content(format!( "Youmu is watching contest **{}**, with the following members: {}", contest.name, - member_results - .iter() - .map(|(_, m)| serenity::utils::MessageBuilder::new() + member_results.values().map(|m| serenity::utils::MessageBuilder::new() .push_safe(m.member.distinct()) .push(" (") .push_mono_safe(&m.handle) @@ -175,7 +173,7 @@ pub async fn watch_contest( msg.pin(ctx).await.ok(); loop { - if let Ok(messages) = scan_changes(&*http, &mut member_results, &mut contest).await { + if let Ok(messages) = scan_changes(http, &mut member_results, &mut contest).await { for message in messages { channel .send_message(&ctx, |e| { @@ -204,7 +202,7 @@ pub async fn watch_contest( ranks.sort_by(|(_, _, a), (_, _, b)| a.rank.cmp(&b.rank)); msg.unpin(ctx).await.ok(); - crate::contest_rank_table(&ctx, &msg, contest, problems, ranks).await?; + crate::contest_rank_table(ctx, &msg, contest, problems, ranks).await?; Ok(()) } @@ -230,7 +228,7 @@ async fn scan_changes( .iter() .map(|(_, h)| h.handle.clone()) .collect::>(); - Contest::standings(&http, contest.id, |f| f.handles(handles)).await? + Contest::standings(http, contest.id, |f| f.handles(handles)).await? }; // Change of phase. if contest.phase != updated_contest.phase { @@ -282,7 +280,7 @@ async fn scan_changes( .iter() .zip(row.problem_results.iter()), ) { - if let Some(message) = analyze_change(&contest, old, new).map(|c| { + if let Some(message) = analyze_change(contest, old, new).map(|c| { translate_change( contest.phase, member_result.handle.as_str(), diff --git a/youmubot-core/src/admin/soft_ban.rs b/youmubot-core/src/admin/soft_ban.rs index a13682c..cba6bf1 100644 --- a/youmubot-core/src/admin/soft_ban.rs +++ b/youmubot-core/src/admin/soft_ban.rs @@ -32,7 +32,7 @@ pub async fn soft_ban(ctx: &Context, msg: &Message, mut args: Args) -> CommandRe .guild_id .ok_or_else(|| Error::msg("Command is guild only"))?; - let mut db = SoftBans::open(&*data); + let mut db = SoftBans::open(&data); let val = db .borrow()? .get(&guild) @@ -85,13 +85,13 @@ pub async fn soft_ban(ctx: &Context, msg: &Message, mut args: Args) -> CommandRe pub async fn soft_ban_init(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let role_id = args.single::()?; let data = ctx.data.read().await; - let guild = msg.guild(&ctx).unwrap(); + let guild = msg.guild(ctx).unwrap(); // Check whether the role_id is the one we wanted if !guild.roles.contains_key(&role_id) { return Err(Error::msg(format!("{} is not a role in this server.", role_id)).into()); } // Check if we already set up - let mut db = SoftBans::open(&*data); + let mut db = SoftBans::open(&data); let set_up = db.borrow()?.contains_key(&guild.id); if !set_up { @@ -111,7 +111,7 @@ pub async fn watch_soft_bans(cache_http: Arc, data: AppData) { { // Poll the data for any changes. let data = data.read().await; - let mut data = SoftBans::open(&*data); + let mut data = SoftBans::open(&data); let mut db = data.borrow().unwrap().clone(); let now = Utc::now(); for (server_id, bans) in db.iter_mut() { @@ -131,7 +131,7 @@ pub async fn watch_soft_bans(cache_http: Arc, data: AppData) { .map(|user_id| { bans.periodical_bans.remove(&user_id); lift_soft_ban_for( - &*cache_http, + &cache_http, *server_id, &server_name[..], bans.role, diff --git a/youmubot-core/src/community/mod.rs b/youmubot-core/src/community/mod.rs index 08f6a2c..02ceb5c 100644 --- a/youmubot-core/src/community/mod.rs +++ b/youmubot-core/src/community/mod.rs @@ -62,7 +62,7 @@ pub async fn choose(ctx: &Context, m: &Message, mut args: Args) -> CommandResult let online_only = !flags.contains("everyone"); let users: Result, Error> = { - let guild = m.guild(&ctx).unwrap(); + let guild = m.guild(ctx).unwrap(); let presences = &guild.presences; let channel = m.channel_id.to_channel(&ctx).await?; if let Channel::Guild(channel) = channel { diff --git a/youmubot-core/src/community/roles.rs b/youmubot-core/src/community/roles.rs index 0db8ebf..9c40489 100644 --- a/youmubot-core/src/community/roles.rs +++ b/youmubot-core/src/community/roles.rs @@ -19,7 +19,7 @@ pub use reaction_watcher::Watchers as ReactionWatchers; async fn list(ctx: &Context, m: &Message, _: Args) -> CommandResult { let guild_id = m.guild_id.unwrap(); // only_in(guilds) let data = ctx.data.read().await; - let db = DB::open(&*data); + let db = DB::open(&data); let roles = db .borrow()? .get(&guild_id) @@ -190,7 +190,7 @@ async fn add(ctx: &Context, m: &Message, mut args: Args) -> CommandResult { m.reply(&ctx, "No such role exists").await?; } Some(role) => { - DB::open(&*data) + DB::open(&data) .borrow_mut()? .entry(guild_id) .or_default() @@ -227,7 +227,7 @@ async fn remove(ctx: &Context, m: &Message, mut args: Args) -> CommandResult { m.reply(&ctx, "No such role exists").await?; } Some(role) - if !DB::open(&*data) + if !DB::open(&data) .borrow()? .get(&guild_id) .map(|g| g.roles.contains_key(&role.id)) @@ -237,7 +237,7 @@ async fn remove(ctx: &Context, m: &Message, mut args: Args) -> CommandResult { .await?; } Some(role) => { - DB::open(&*data) + DB::open(&data) .borrow_mut()? .entry(guild_id) .or_default() @@ -289,7 +289,7 @@ async fn parse( let title = args.single_quoted::().unwrap(); let data = ctx.data.read().await; let guild_id = m.guild_id.unwrap(); - let assignables = DB::open(&*data) + let assignables = DB::open(&data) .borrow()? .get(&guild_id) .filter(|v| !v.roles.is_empty()) @@ -369,7 +369,7 @@ async fn updaterolemessage(ctx: &Context, m: &Message, args: Args) -> CommandRes { data.get::() .unwrap() - .setup(&mut *message, ctx.clone(), guild_id, title, roles) + .setup(&mut message, ctx.clone(), guild_id, title, roles) .await?; } else { m.reply(&ctx, "Message does not come with a reaction handler") @@ -436,7 +436,7 @@ mod reaction_watcher { impl Watchers { pub fn new(data: &TypeMap) -> Result { - let init = Roles::open(&*data) + let init = Roles::open(data) .borrow()? .iter() .flat_map(|(&guild, rs)| { @@ -510,7 +510,7 @@ mod reaction_watcher { // Store the message into the list. { let data = ctx.data.read().await; - Roles::open(&*data) + Roles::open(&data) .borrow_mut()? .entry(guild) .or_default() @@ -537,7 +537,7 @@ mod reaction_watcher { message: MessageId, ) -> Result { let data = ctx.data.read().await; - Roles::open(&*data) + Roles::open(&data) .borrow_mut()? .entry(guild) .or_default() @@ -583,7 +583,7 @@ mod reaction_watcher { } }; eprintln!("{:?}", reaction); - if let Err(e) = Self::handle_reaction(&ctx, guild, message, &*reaction).await { + if let Err(e) = Self::handle_reaction(&ctx, guild, message, &reaction).await { eprintln!("Handling {:?}: {}", reaction, e); break; } @@ -610,7 +610,7 @@ mod reaction_watcher { return Ok(()); } // Get the role list. - let role = Roles::open(&*data) + let role = Roles::open(&data) .borrow()? .get(&guild) .ok_or_else(|| Error::msg("guild no longer has role list"))? diff --git a/youmubot-core/src/community/votes.rs b/youmubot-core/src/community/votes.rs index f08e2b3..7508031 100644 --- a/youmubot-core/src/community/votes.rs +++ b/youmubot-core/src/community/votes.rs @@ -116,7 +116,7 @@ pub async fn vote(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult // Collect reactions... let user_reactions = panel - .await_reactions(&ctx) + .await_reactions(ctx) .removed(true) .timeout(*duration) .build() diff --git a/youmubot-core/src/db.rs b/youmubot-core/src/db.rs index 67f4a95..0b4d9c1 100644 --- a/youmubot-core/src/db.rs +++ b/youmubot-core/src/db.rs @@ -64,7 +64,7 @@ pub fn load_role_list( match legacy::RolesV1::load_from_path(v1_path.as_ref()) { Ok(v1) => { Roles::insert_into(map, path)?; - *Roles::open(&map).borrow_mut()? = v1 + *Roles::open(map).borrow_mut()? = v1 .get_data(true)? .into_iter() .map(|(guild, roles)| { diff --git a/youmubot-core/src/fun/images.rs b/youmubot-core/src/fun/images.rs index f3869b8..90abaa1 100644 --- a/youmubot-core/src/fun/images.rs +++ b/youmubot-core/src/fun/images.rs @@ -103,7 +103,7 @@ async fn get_image( // Fix the tags: change whitespaces to + let tags = tags.split_whitespace().collect::>().join("_"); let req = client - .get(&format!( + .get(format!( "https://danbooru.donmai.us/posts.json?tags=rating:{}+{}", rating.to_string(), tags diff --git a/youmubot-core/src/fun/mod.rs b/youmubot-core/src/fun/mod.rs index 4401483..aacf08f 100644 --- a/youmubot-core/src/fun/mod.rs +++ b/youmubot-core/src/fun/mod.rs @@ -95,7 +95,7 @@ async fn pick(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { .peekable(); // If we have the first argument as question, use it. let question = match choices.peek() { - Some(ref q) if q.starts_with('?') => Some(q.replacen("?", "", 1) + "?"), + Some(q) if q.starts_with('?') => Some(q.replacen('?', "", 1) + "?"), _ => None, }; // If we have a question, that's not a choice. diff --git a/youmubot-osu/src/discord/announcer.rs b/youmubot-osu/src/discord/announcer.rs index 8976eb8..22bbeb7 100644 --- a/youmubot-osu/src/discord/announcer.rs +++ b/youmubot-osu/src/discord/announcer.rs @@ -125,7 +125,7 @@ impl Announcer { .iter() .filter_map(|u| u.to_event_rank()) .filter(|u| u.mode == mode && u.date > last_update && u.date <= now) - .map(|ev| CollectedScore::from_event(&*client, &user, ev, user_id, &channels[..])) + .map(|ev| CollectedScore::from_event(&client, &user, ev, user_id, &channels[..])) .collect::>() .filter_map(|u| future::ready(u.pls_ok())) .collect::>() @@ -235,7 +235,7 @@ impl<'a> CollectedScore<'a> { impl<'a> CollectedScore<'a> { async fn send_message(self, ctx: &Context) -> Result> { - let (bm, content) = self.get_beatmap(&ctx).await?; + let (bm, content) = self.get_beatmap(ctx).await?; self.channels .iter() .map(|c| self.send_message_to(*c, ctx, &bm, &content)) @@ -293,7 +293,7 @@ impl<'a> CollectedScore<'a> { } }) .embed(|e| { - let mut b = score_embed(&self.score, &bm, content, self.user); + let mut b = score_embed(&self.score, bm, content, self.user); match self.kind { ScoreType::TopRecord(rank) => b.top_record(rank), ScoreType::WorldRecord(rank) => b.world_record(rank), @@ -302,7 +302,7 @@ impl<'a> CollectedScore<'a> { }) }) .await?; - save_beatmap(&*ctx.data.read().await, channel, &bm) + save_beatmap(&*ctx.data.read().await, channel, bm) .await .pls_ok(); Ok(m) diff --git a/youmubot-osu/src/discord/beatmap_cache.rs b/youmubot-osu/src/discord/beatmap_cache.rs index 6f8aabb..93e1f49 100644 --- a/youmubot-osu/src/discord/beatmap_cache.rs +++ b/youmubot-osu/src/discord/beatmap_cache.rs @@ -105,7 +105,7 @@ impl BeatmapMetaCache { // Save each beatmap. let mut t = self.pool.begin().await?; for b in &beatmaps { - let mut b = Self::to_cached_beatmap(&b, None); + let mut b = Self::to_cached_beatmap(b, None); b.store(&mut t).await?; // Save the beatmapset mapping. b.link_beatmapset(id as i64, &mut t).await?; diff --git a/youmubot-osu/src/discord/display.rs b/youmubot-osu/src/discord/display.rs index 1aa90b3..c15c1be 100644 --- a/youmubot-osu/src/discord/display.rs +++ b/youmubot-osu/src/discord/display.rs @@ -249,7 +249,7 @@ mod scores { b.map(|(beatmap, info)| { format!( "[{:.1}*] {} - {} [{}] ({})", - info.map(|i| i.stars as f64) + info.map(|i| i.stars) .unwrap_or(beatmap.difficulty.stars), beatmap.artist, beatmap.title, diff --git a/youmubot-osu/src/discord/embeds.rs b/youmubot-osu/src/discord/embeds.rs index 3c5255c..4e6a240 100644 --- a/youmubot-osu/src/discord/embeds.rs +++ b/youmubot-osu/src/discord/embeds.rs @@ -7,6 +7,8 @@ use serenity::{builder::CreateEmbed, utils::MessageBuilder}; use std::time::Duration; use youmubot_prelude::*; +type CreateEmbedFn = dyn FnOnce(&mut CreateEmbed) -> &mut CreateEmbed + Send + Sync; + /// Writes a number grouped in groups of 3. pub(crate) fn grouped_number(num: u64) -> String { let s = num.to_string(); @@ -22,7 +24,7 @@ pub(crate) fn grouped_number(num: u64) -> String { fn beatmap_description(b: &Beatmap) -> String { MessageBuilder::new() - .push_bold_line(&b.approval) + .push_bold_line(b.approval) .push({ let link = b.download_link(false); format!( @@ -34,9 +36,9 @@ fn beatmap_description(b: &Beatmap) -> String { }) .push_line(format!(" [[Beatmapset]]({})", b.beatmapset_link())) .push("Language: ") - .push_bold(&b.language) + .push_bold(b.language) .push(" | Genre: ") - .push_bold_line(&b.genre) + .push_bold_line(b.genre) .push( b.source .as_ref() @@ -60,12 +62,12 @@ pub fn beatmap_offline_embed( b: &'_ crate::discord::oppai_cache::BeatmapContent, m: Mode, mods: Mods, -) -> Result &mut CreateEmbed + Send + Sync>> { +) -> Result> { let bm = b.content.clone(); let metadata = b.metadata.clone(); let (info, pp) = b.get_possible_pp_with(m, mods)?; - let total_length = if bm.hit_objects.len() >= 1 { + let total_length = if !bm.hit_objects.is_empty() { Duration::from_millis( (bm.hit_objects.last().unwrap().end_time() - bm.hit_objects.first().unwrap().start_time) as u64, @@ -309,7 +311,7 @@ impl<'a> ScoreEmbedBuilder<'a> { s.mods, ) .ok() - .map(|pp| (pp as f64, format!("{:.2}pp [?]", pp))) + .map(|pp| (pp, format!("{:.2}pp [?]", pp))) }); let pp = if !s.perfect { content @@ -320,11 +322,7 @@ impl<'a> ScoreEmbedBuilder<'a> { s.mods, ) .ok() - .filter(|&v| { - pp.as_ref() - .map(|&(origin, _)| origin < v as f64) - .unwrap_or(false) - }) + .filter(|&v| pp.as_ref().map(|&(origin, _)| origin < v).unwrap_or(false)) .and_then(|value| { pp.as_ref() .map(|(_, original)| format!("{} ({:.2}pp if FC?)", original, value)) @@ -409,7 +407,7 @@ impl<'a> ScoreEmbedBuilder<'a> { true, ) .field("Map stats", diff.format_info(mode, s.mods, b), false); - let mut footer = self.footer.take().unwrap_or_else(String::new); + let mut footer = self.footer.take().unwrap_or_default(); if mode != Mode::Std && s.mods != Mods::NOMOD { footer += " Star difficulty does not reflect game mods."; } @@ -501,9 +499,9 @@ pub(crate) fn user_embed( .push(format!( "> {}", map.difficulty - .apply_mods(v.mods, info.stars as f64) + .apply_mods(v.mods, info.stars) .format_info(mode, v.mods, &map) - .replace("\n", "\n> ") + .replace('\n', "\n> ") )) .build(), false, diff --git a/youmubot-osu/src/discord/hook.rs b/youmubot-osu/src/discord/hook.rs index 0e6ae3d..a579cc0 100644 --- a/youmubot-osu/src/discord/hook.rs +++ b/youmubot-osu/src/discord/hook.rs @@ -60,7 +60,7 @@ pub fn dot_osu_hook<'a>( } }) .collect::>() - .filter_map(|v| future::ready(v)) + .filter_map(future::ready) .collect::>() .await; @@ -96,14 +96,14 @@ pub fn dot_osu_hook<'a>( } }) .collect::>() - .filter_map(|v| future::ready(v)) - .filter(|v| future::ready(v.len() > 0)) + .filter_map(future::ready) + .filter(|v| future::ready(!v.is_empty())) .collect::>() .await .concat(); osu_embeds.extend(osz_embeds); - if osu_embeds.len() > 0 { + if !osu_embeds.is_empty() { msg.channel_id .send_message(ctx, |f| { f.reference_message(msg) @@ -129,7 +129,7 @@ pub fn hook<'a>( let (old_links, new_links, short_links) = ( handle_old_links(ctx, &msg.content), handle_new_links(ctx, &msg.content), - handle_short_links(ctx, &msg, &msg.content), + handle_short_links(ctx, msg, &msg.content), ); stream::select(old_links, stream::select(new_links, short_links)) .then(|l| async move { @@ -139,7 +139,7 @@ pub fn hook<'a>( .await .pls_ok(); let mode = l.mode.unwrap_or(b.mode); - let bm = super::BeatmapWithMode(b, mode); + let bm = super::BeatmapWithMode(*b, mode); crate::discord::cache::save_beatmap( &*ctx.data.read().await, msg.channel_id, @@ -163,7 +163,7 @@ pub fn hook<'a>( } enum EmbedType { - Beatmap(Beatmap, BeatmapInfoWithPP, Mods), + Beatmap(Box, BeatmapInfoWithPP, Mods), Beatmapset(Vec), } @@ -210,12 +210,11 @@ fn handle_old_links<'a>( } let r: Result<_> = Ok(match req_type { "b" => { - let b = beatmaps.into_iter().next().unwrap(); + let b = Box::new(beatmaps.into_iter().next().unwrap()); // collect beatmap info let mods = capture .name("mods") - .map(|v| Mods::from_str(v.as_str()).pls_ok()) - .flatten() + .and_then(|v| Mods::from_str(v.as_str()).pls_ok()) .unwrap_or(Mods::NOMOD); let info = { let mode = mode.unwrap_or(b.mode); @@ -280,7 +279,7 @@ fn handle_new_links<'a>( } let r: Result<_> = Ok(match capture.name("beatmap_id") { Some(_) => { - let beatmap = beatmaps.into_iter().next().unwrap(); + let beatmap = Box::new(beatmaps.into_iter().next().unwrap()); // collect beatmap info let mods = capture .name("mods") @@ -359,7 +358,7 @@ fn handle_short_links<'a>( .and_then(|b| b.get_possible_pp_with(mode, mods))? }; let r: Result<_> = Ok(ToPrint { - embed: EmbedType::Beatmap(beatmap, info, mods), + embed: EmbedType::Beatmap(Box::new(beatmap), info, mods), link: capture.name("main").unwrap().as_str(), mode, }); @@ -410,7 +409,7 @@ async fn handle_beatmapset<'a, 'b>( reply_to: &Message, ) -> Result<()> { crate::discord::display::display_beatmapset( - &ctx, + ctx, beatmaps, mode, None, diff --git a/youmubot-osu/src/discord/mod.rs b/youmubot-osu/src/discord/mod.rs index 56cef4c..5331511 100644 --- a/youmubot-osu/src/discord/mod.rs +++ b/youmubot-osu/src/discord/mod.rs @@ -207,7 +207,7 @@ pub async fn save(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult .await?; return Ok(()); } - add_user(msg.author.id, u.id, &*data).await?; + add_user(msg.author.id, u.id, &data).await?; msg.reply( &ctx, MessageBuilder::new() @@ -239,7 +239,7 @@ pub async fn forcesave(ctx: &Context, msg: &Message, mut args: Args) -> CommandR let user: Option = osu.user(UserID::Auto(user), |f| f).await?; match user { Some(u) => { - add_user(target, u.id, &*data).await?; + add_user(target, u.id, &data).await?; msg.reply( &ctx, MessageBuilder::new() @@ -335,7 +335,7 @@ pub async fn recent(ctx: &Context, msg: &Message, mut args: Args) -> CommandResu let mode = args.single::().unwrap_or(ModeArg(Mode::Std)).0; let user = to_user_id_query( args.quoted().trimmed().single::().ok(), - &*data, + &data, msg, ) .await?; @@ -370,7 +370,7 @@ pub async fn recent(ctx: &Context, msg: &Message, mut args: Args) -> CommandResu .await?; // Save the beatmap... - cache::save_beatmap(&*data, msg.channel_id, &beatmap_mode).await?; + cache::save_beatmap(&data, msg.channel_id, &beatmap_mode).await?; } Nth::All => { let plays = osu @@ -409,7 +409,7 @@ pub(crate) async fn load_beatmap( replied.embeds.iter().find_map(|e| { e.description .as_ref() - .and_then(|v| SHORT_LINK_REGEX.captures(&v)) + .and_then(|v| SHORT_LINK_REGEX.captures(v)) .or_else(|| { e.fields .iter() @@ -432,10 +432,10 @@ pub(crate) async fn load_beatmap( .ok() .and_then(|v| v.into_iter().next()); if let Some(beatmap) = bms { - let bm_mode = beatmap.mode.clone(); + let bm_mode = beatmap.mode; let bm = BeatmapWithMode(beatmap, mode.unwrap_or(bm_mode)); // Store the beatmap in history - cache::save_beatmap(&*data, msg.channel_id, &bm) + cache::save_beatmap(&data, msg.channel_id, &bm) .await .pls_ok(); @@ -444,7 +444,7 @@ pub(crate) async fn load_beatmap( } } - let b = cache::get_beatmap(&*data, msg.channel_id) + let b = cache::get_beatmap(&data, msg.channel_id) .await .ok() .flatten(); @@ -529,7 +529,7 @@ pub async fn check(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul None => Some(msg.author.id), _ => None, }; - let user = to_user_id_query(username_arg, &*data, msg).await?; + let user = to_user_id_query(username_arg, &data, msg).await?; let osu = data.get::().unwrap(); @@ -581,7 +581,7 @@ pub async fn top(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult .map(|ModeArg(t)| t) .unwrap_or(Mode::Std); - let user = to_user_id_query(args.single::().ok(), &*data, msg).await?; + let user = to_user_id_query(args.single::().ok(), &data, msg).await?; let meta_cache = data.get::().unwrap(); let osu = data.get::().unwrap(); @@ -622,7 +622,7 @@ pub async fn top(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult .await?; // Save the beatmap... - cache::save_beatmap(&*data, msg.channel_id, &beatmap).await?; + cache::save_beatmap(&data, msg.channel_id, &beatmap).await?; } Nth::All => { let plays = osu @@ -636,7 +636,7 @@ pub async fn top(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult async fn get_user(ctx: &Context, msg: &Message, mut args: Args, mode: Mode) -> CommandResult { let data = ctx.data.read().await; - let user = to_user_id_query(args.single::().ok(), &*data, msg).await?; + let user = to_user_id_query(args.single::().ok(), &data, msg).await?; let osu = data.get::().unwrap(); let cache = data.get::().unwrap(); let user = osu.user(user, |f| f.mode(mode)).await?; diff --git a/youmubot-osu/src/discord/oppai_cache.rs b/youmubot-osu/src/discord/oppai_cache.rs index 978c5b1..6720d20 100644 --- a/youmubot-osu/src/discord/oppai_cache.rs +++ b/youmubot-osu/src/discord/oppai_cache.rs @@ -42,9 +42,9 @@ pub enum Accuracy { ByValue(f64, u64), } -impl Into for Accuracy { - fn into(self) -> f64 { - match self { +impl From for f64 { + fn from(val: Accuracy) -> Self { + match val { Accuracy::ByValue(v, _) => v, Accuracy::ByCount(n300, n100, n50, nmiss) => { 100.0 * ((6 * n300 + 2 * n100 + n50) as f64) @@ -396,10 +396,10 @@ impl BeatmapCache { } async fn get_beatmap_db(&self, id: u64) -> Result> { - Ok(models::CachedBeatmapContent::by_id(id as i64, &self.pool) + models::CachedBeatmapContent::by_id(id as i64, &self.pool) .await? .map(|v| Self::parse_beatmap(String::from_utf8(v.content)?)) - .transpose()?) + .transpose() } /// Get a beatmap from the cache. diff --git a/youmubot-osu/src/discord/server_rank.rs b/youmubot-osu/src/discord/server_rank.rs index cbcf681..ce6e672 100644 --- a/youmubot-osu/src/discord/server_rank.rs +++ b/youmubot-osu/src/discord/server_rank.rs @@ -367,7 +367,7 @@ async fn show_leaderboard( return Box::pin(future::ready(Ok(false))); } let total_len = scores.len(); - let scores = (&scores[start..end]).to_vec(); + let scores = scores[start..end].to_vec(); let bm = (bm.0.clone(), bm.1); Box::pin(async move { // username width diff --git a/youmubot-osu/src/lib.rs b/youmubot-osu/src/lib.rs index 7122a57..1e7df16 100644 --- a/youmubot-osu/src/lib.rs +++ b/youmubot-osu/src/lib.rs @@ -58,7 +58,7 @@ impl Client { ) -> Result> { let mut r = BeatmapRequestBuilder::new(kind); f(&mut r); - let res: Vec = r.build(&self).await?.json().await?; + let res: Vec = r.build(self).await?.json().await?; Ok(vec_try_into(res)?) } @@ -69,7 +69,7 @@ impl Client { ) -> Result, Error> { let mut r = UserRequestBuilder::new(user); f(&mut r); - let res: Vec = r.build(&self).await?.json().await?; + let res: Vec = r.build(self).await?.json().await?; let res = vec_try_into(res)?; Ok(res.into_iter().next()) } @@ -81,7 +81,7 @@ impl Client { ) -> Result, Error> { let mut r = ScoreRequestBuilder::new(beatmap_id); f(&mut r); - let res: Vec = r.build(&self).await?.json().await?; + let res: Vec = r.build(self).await?.json().await?; let mut res: Vec = vec_try_into(res)?; // with a scores request you need to fill the beatmap ids yourself @@ -115,7 +115,7 @@ impl Client { ) -> Result, Error> { let mut r = UserScoreRequestBuilder::new(u, user); f(&mut r); - let res: Vec = r.build(&self).await?.json().await?; + let res: Vec = r.build(self).await?.json().await?; let res = vec_try_into(res)?; Ok(res) } diff --git a/youmubot-osu/src/models/parse.rs b/youmubot-osu/src/models/parse.rs index 40eb4f4..ca962b6 100644 --- a/youmubot-osu/src/models/parse.rs +++ b/youmubot-osu/src/models/parse.rs @@ -279,7 +279,7 @@ fn parse_date(date: impl AsRef) -> ParseResult> { parse( &mut parsed, date.as_ref(), - (&[ + [ Item::Numeric(Numeric::Year, Pad::Zero), Item::Literal("-"), Item::Numeric(Numeric::Month, Pad::Zero), @@ -291,7 +291,7 @@ fn parse_date(date: impl AsRef) -> ParseResult> { Item::Numeric(Numeric::Minute, Pad::Zero), Item::Literal(":"), Item::Numeric(Numeric::Second, Pad::Zero), - ]) + ] .iter(), ) .map_err(ParseError::DateParseError)?; diff --git a/youmubot-osu/src/test.rs b/youmubot-osu/src/test.rs index 304f200..908aa78 100644 --- a/youmubot-osu/src/test.rs +++ b/youmubot-osu/src/test.rs @@ -9,7 +9,7 @@ fn parse_beatmaps() { parse_str::>(INPUT) .unwrap() .into_iter() - .map(|v| Beatmap::try_from(v)) + .map(Beatmap::try_from) .collect::, _>>() .unwrap(); } diff --git a/youmubot-prelude/src/announcer.rs b/youmubot-prelude/src/announcer.rs index 7c96710..6a5229e 100644 --- a/youmubot-prelude/src/announcer.rs +++ b/youmubot-prelude/src/announcer.rs @@ -159,7 +159,7 @@ impl AnnouncerHandler { let after = tokio::time::sleep_until(tokio::time::Instant::now() + cooldown); join_all(self.announcers.iter().map(|(key, announcer)| { eprintln!(" - scanning key `{}`", key); - Self::announce(self.data.clone(), self.cache_http.clone(), *key, announcer).map( + Self::announce(self.data.clone(), self.cache_http.clone(), key, announcer).map( move |v| { if let Err(e) = v { eprintln!(" - key `{}`: {:?}", *key, e) @@ -241,9 +241,9 @@ pub async fn register_announcer(ctx: &Context, m: &Message, mut args: Args) -> C .await?; return Ok(()); } - let guild = m.guild(&ctx).expect("Guild-only command"); + let guild = m.guild(ctx).expect("Guild-only command"); let channel = m.channel_id.to_channel(&ctx).await?; - AnnouncerChannels::open(&*data) + AnnouncerChannels::open(&data) .borrow_mut()? .entry(key.clone()) .or_default() @@ -284,8 +284,8 @@ pub async fn remove_announcer(ctx: &Context, m: &Message, mut args: Args) -> Com .await?; return Ok(()); } - let guild = m.guild(&ctx).expect("Guild-only command"); - AnnouncerChannels::open(&*data) + let guild = m.guild(ctx).expect("Guild-only command"); + AnnouncerChannels::open(&data) .borrow_mut()? .entry(key.clone()) .and_modify(|m| { diff --git a/youmubot-prelude/src/args.rs b/youmubot-prelude/src/args.rs index 69181ac..f4a02e0 100644 --- a/youmubot-prelude/src/args.rs +++ b/youmubot-prelude/src/args.rs @@ -138,12 +138,12 @@ mod duration { let tests = [ ( "2D2h1m", - StdDuration::from_secs(2 * 60 * 60 * 24 + 2 * 60 * 60 + 1 * 60), + StdDuration::from_secs(2 * 60 * 60 * 24 + 2 * 60 * 60 + 60), ), ( "1W2D3h4m5s", StdDuration::from_secs( - 1 * 7 * 24 * 60 * 60 + // 1W + 7 * 24 * 60 * 60 + // 1W 2 * 24 * 60 * 60 + // 2D 3 * 60 * 60 + // 3h 4 * 60 + // 4m @@ -153,7 +153,7 @@ mod duration { ( "1W2D3h4m5s6W", StdDuration::from_secs( - 1 * 7 * 24 * 60 * 60 + // 1W + 7 * 24 * 60 * 60 + // 1W 2 * 24 * 60 * 60 + // 2D 3 * 60 * 60 + // 3h 4 * 60 + // 4m diff --git a/youmubot-prelude/src/flags.rs b/youmubot-prelude/src/flags.rs index b6000b4..0048134 100644 --- a/youmubot-prelude/src/flags.rs +++ b/youmubot-prelude/src/flags.rs @@ -23,7 +23,7 @@ impl Flags { pub fn collect_from(args: &mut Args) -> Flags { let mut set = Set::new(); loop { - if let Some(Flag(s)) = args.find().ok() { + if let Ok(Flag(s)) = args.find() { set.insert(s); } else { break Flags(set); diff --git a/youmubot-prelude/src/pagination.rs b/youmubot-prelude/src/pagination.rs index ee1cef7..d37381c 100644 --- a/youmubot-prelude/src/pagination.rs +++ b/youmubot-prelude/src/pagination.rs @@ -102,7 +102,7 @@ async fn paginate_with_first_message( mut message: Message, timeout: std::time::Duration, ) -> Result<()> { - pager.prerender(&ctx, &mut message).await?; + pager.prerender(ctx, &mut message).await?; pager.render(0, ctx, &mut message).await?; // Just quit if there is only one page if pager.len().filter(|&v| v == 1).is_some() { @@ -127,7 +127,7 @@ async fn paginate_with_first_message( .await?; } // Build a reaction collector - let mut reaction_collector = message.await_reactions(&ctx).removed(true).build(); + let mut reaction_collector = message.await_reactions(ctx).removed(true).build(); let mut page = 0; // Loop the handler function. diff --git a/youmubot/src/main.rs b/youmubot/src/main.rs index fa3add0..80c1b44 100644 --- a/youmubot/src/main.rs +++ b/youmubot/src/main.rs @@ -61,7 +61,7 @@ impl EventHandler for Handler { async fn is_not_channel_mod(ctx: &Context, msg: &Message) -> bool { match msg.channel_id.to_channel(&ctx).await { Ok(Channel::Guild(gc)) => gc - .permissions_for_user(&ctx, msg.author.id) + .permissions_for_user(ctx, msg.author.id) .map(|perms| !perms.contains(Permissions::MANAGE_MESSAGES)) .unwrap_or(true), _ => true, @@ -173,7 +173,7 @@ async fn setup_framework(token: &str) -> StandardFramework { c.with_whitespace(false) .prefixes( var("PREFIX") - .map(|v| v.split(",").map(|v| v.trim().to_owned()).collect()) + .map(|v| v.split(',').map(|v| v.trim().to_owned()).collect()) .unwrap_or_else(|_| vec!["y!".to_owned(), "y2!".to_owned()]), ) .delimiters(vec![" / ", "/ ", " /", "/"])