Skip to content

Commit

Permalink
clippy pedantic fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Jacherr committed Oct 22, 2024
1 parent c7345ed commit 13af4d1
Show file tree
Hide file tree
Showing 65 changed files with 319 additions and 367 deletions.
10 changes: 5 additions & 5 deletions assyst-cache/src/caches/guilds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use dashmap::DashSet;

/// The cache of all guilds Assyst is part of. When a shard readies up, it receives a list of all
/// guild IDs that shard is responsible for, which are all cached here. In addition, when a shard is
/// ready, it will receive GUILD_CREATE events for every guild that shard is responsible for. This
/// cache allows to differentiate between GUILD_CREATE events sent as part of this procedure (since
/// they were also part of the READY event) and legitimate GUILD_CREATEs fired as a result of Assyst
/// ready, it will receive `GUILD_CREATE` events for every guild that shard is responsible for. This
/// cache allows to differentiate between `GUILD_CREATE` events sent as part of this procedure (since
/// they were also part of the READY event) and legitimate `GUILD_CREATEs` fired as a result of Assyst
/// joining a new guild post-ready.
pub struct GuildCache {
ids: DashSet<u64, BuildHasherDefault<rustc_hash::FxHasher>>,
Expand All @@ -32,13 +32,13 @@ impl GuildCache {
new_guilds
}

/// Handles a GUILD_CREATE. This method returns a bool which states if this guild is new or not.
/// Handles a `GUILD_CREATE`. This method returns a bool which states if this guild is new or not.
/// A new guild is one that was not received during the start-up of the gateway connection.
pub fn handle_guild_create_event(&mut self, event: GuildCreateData) -> bool {
self.ids.insert(event.id)
}

/// Handles a GUILD_DELETE. This method returns a bool which states if the bot was actually
/// Handles a `GUILD_DELETE`. This method returns a bool which states if the bot was actually
/// kicked from this guild.
pub fn handle_guild_delete_event(&mut self, event: GuildDeleteData) -> bool {
!event.unavailable && self.ids.remove(&event.id).is_some()
Expand Down
12 changes: 6 additions & 6 deletions assyst-common/src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ pub type CacheJobSend = (Sender<CacheResponseSend>, CacheJob);
/// The different jobs that the cache needs to handle.
#[derive(Serialize, Deserialize, Debug)]
pub enum CacheJob {
/// Storing data from a GUILD_CREATE event.
/// Storing data from a `GUILD_CREATE` event.
HandleGuildCreate(GuildCreateData),
/// Storing data from a GUILD_DELETE event.
/// Storing data from a `GUILD_DELETE` event.
HandleGuildDelete(GuildDeleteData),
/// Storing data from a READY event.
HandleReady(ReadyData),
Expand Down Expand Up @@ -80,14 +80,14 @@ impl From<GuildDelete> for GuildDeleteData {

pub type CacheResponseSend = anyhow::Result<CacheResponse>;

/// All the responses the cache can send back. Usually it is a 1-1 relation between a CacheJob
/// variant and CacheResponse variant.
/// All the responses the cache can send back. Usually it is a 1-1 relation between a `CacheJob`
/// variant and `CacheResponse` variant.
#[derive(Serialize, Deserialize, Debug)]
pub enum CacheResponse {
/// Whether Assyst should handle a GUILD_CREATE event. False if this guild is coming back from
/// Whether Assyst should handle a `GUILD_CREATE` event. False if this guild is coming back from
/// unavailable, or if this guild has already been cached.
ShouldHandleGuildCreate(bool),
/// Whether Assyst should handle a GUILD_DELETE event. False if this guild went unavailable, or
/// Whether Assyst should handle a `GUILD_DELETE` event. False if this guild went unavailable, or
/// if it was not in the cache.
ShouldHandleGuildDelete(bool),
/// The amount of new guilds Assyst receives when a shard enters a READY state. Some guilds may
Expand Down
3 changes: 3 additions & 0 deletions assyst-common/src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,15 @@ pub struct Database {
pub port: u16,
}
impl Database {
#[must_use]
pub fn to_url(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database
)
}

#[must_use]
pub fn to_url_safe(&self) -> String {
let mut host = self.host.split('.').take(2).collect::<Vec<_>>();
host.push("###");
Expand Down Expand Up @@ -108,6 +110,7 @@ pub struct DevAttributes {
pub disable_reminder_check: bool,
pub disable_bot_list_posting: bool,
pub disable_patreon_synchronisation: bool,
pub disable_entitlement_fetching: bool,
pub dev_guild: u64,
pub dev_channel: u64,
pub dev_message: bool,
Expand Down
6 changes: 3 additions & 3 deletions assyst-common/src/pipe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub static CACHE_PIPE_PATH: &str = "/tmp/assyst2-cache-com";

static POLL_FREQUENCY: Duration = Duration::from_secs(10);

/// Pipe is a utility class that wraps a [UnixStream], providing helper functions for easy reading
/// Pipe is a utility class that wraps a [`UnixStream`], providing helper functions for easy reading
/// and writing of serde-Serializable types via Bincode.
pub struct Pipe {
pub stream: UnixStream,
Expand Down Expand Up @@ -93,7 +93,7 @@ impl Pipe {
/// able to serialize the data to the specified type.
pub async fn write_object<T: Serialize>(&mut self, obj: T) -> anyhow::Result<()> {
let buffer = serialize(&obj)?;
debug_assert!(buffer.len() <= u32::MAX as usize, "attempted to write more than 4 GB");
debug_assert!(u32::try_from(buffer.len()).is_ok(), "attempted to write more than 4 GB");
self.stream.write_u32(buffer.len() as u32).await?;
self.stream.write_all(&buffer).await?;
Ok(())
Expand All @@ -104,7 +104,7 @@ impl Pipe {
/// This function will return an Err if the stream is prematurely closed.
pub async fn write_string<T: AsRef<str>>(&mut self, obj: T) -> anyhow::Result<()> {
let obj = obj.as_ref();
debug_assert!(obj.len() <= u32::MAX as usize, "attempted to write more than 4 GB");
debug_assert!(u32::try_from(obj.len()).is_ok(), "attempted to write more than 4 GB");
self.stream.write_u32(obj.len() as u32).await?;
self.stream.write_all(obj.as_bytes()).await?;
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion assyst-common/src/pipe/pipe_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use tracing::info;

use super::Pipe;

/// PipeServer is a utility class wrapping [UnixListener] that provides utility functions
/// `PipeServer` is a utility class wrapping [`UnixListener`] that provides utility functions
/// for listening on a specific file descriptor ("pipe") and accepting a connection from it.
pub struct PipeServer {
listener: UnixListener,
Expand Down
20 changes: 10 additions & 10 deletions assyst-common/src/util/discord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub async fn get_guild_owner(http: &Client, guild_id: u64) -> anyhow::Result<u64
.get())
}

pub fn get_default_avatar_url(user: &User) -> String {
#[must_use] pub fn get_default_avatar_url(user: &User) -> String {
// Unwrapping discrim parsing is ok, it should never be out of range or non-numeric
let suffix = if user.discriminator == 0 {
// Pomelo users
Expand All @@ -33,7 +33,7 @@ pub fn get_default_avatar_url(user: &User) -> String {
format!("https://cdn.discordapp.com/embed/avatars/{suffix}.png?size=1024")
}

pub fn get_avatar_url(user: &User) -> String {
#[must_use] pub fn get_avatar_url(user: &User) -> String {
let avatar = match &user.avatar {
Some(av) => av,
None => return get_default_avatar_url(user),
Expand All @@ -51,39 +51,39 @@ pub fn get_avatar_url(user: &User) -> String {
)
}

pub fn id_from_mention(word: &str) -> Option<u64> {
#[must_use] pub fn id_from_mention(word: &str) -> Option<u64> {
USER_MENTION
.captures(word)
.and_then(|user_id_capture| user_id_capture.get(1))
.map(|id| id.as_str())
.and_then(|id| id.parse::<u64>().ok())
}

pub fn format_tag(user: &User) -> String {
#[must_use] pub fn format_tag(user: &User) -> String {
format!("{}#{}", user.name, user.discriminator)
}

/// Generates a message link
pub fn message_link(guild_id: u64, channel_id: u64, message_id: u64) -> String {
#[must_use] pub fn message_link(guild_id: u64, channel_id: u64, message_id: u64) -> String {
format!("https://discord.com/channels/{guild_id}/{channel_id}/{message_id}")
}

/// Generates a DM message link
pub fn dm_message_link(channel_id: u64, message_id: u64) -> String {
#[must_use] pub fn dm_message_link(channel_id: u64, message_id: u64) -> String {
format!("https://discord.com/channels/@me/{channel_id}/{message_id}")
}

/// Attempts to return the timestamp as a Discord timestamp,
/// and falls back to [`format_time`] if Discord were to render it as "Invalid Date"
pub fn format_discord_timestamp(input: u64) -> String {
#[must_use] pub fn format_discord_timestamp(input: u64) -> String {
if input <= MAX_TIMESTAMP {
format!("<t:{}:R>", input / 1000)
} else {
format_time(input)
}
}

pub fn user_mention_to_id(s: &str) -> Option<u64> {
#[must_use] pub fn user_mention_to_id(s: &str) -> Option<u64> {
let mention: Regex = Regex::new(r"(?:<@!?)?(\d{16,20})>?").unwrap();

mention
Expand All @@ -93,7 +93,7 @@ pub fn user_mention_to_id(s: &str) -> Option<u64> {
.and_then(|id| id.parse::<u64>().ok())
}

pub fn channel_mention_to_id(s: &str) -> Option<u64> {
#[must_use] pub fn channel_mention_to_id(s: &str) -> Option<u64> {
let mention: Regex = Regex::new(r"(?:<#)?(\d{16,20})>?").unwrap();

mention
Expand All @@ -111,7 +111,7 @@ pub async fn is_same_guild(client: &Client, channel_id: u64, guild_id: u64) -> R
.await
.unwrap();

let real_guild_id = ch.guild_id.map_or(0, |z| z.get());
let real_guild_id = ch.guild_id.map_or(0, twilight_model::id::Id::get);

Ok(real_guild_id == guild_id)
}
Expand Down
8 changes: 4 additions & 4 deletions assyst-common/src/util/filetype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub enum Type {
ZIP,
}
impl Type {
pub fn as_str(&self) -> &'static str {
#[must_use] pub fn as_str(&self) -> &'static str {
match self {
Type::GIF => "gif",
Type::JPEG => "jpeg",
Expand All @@ -25,7 +25,7 @@ impl Type {
Type::ZIP => "zip",
}
}
pub fn as_mime(&self) -> &'static str {
#[must_use] pub fn as_mime(&self) -> &'static str {
match self {
Type::GIF => "image/gif",
Type::JPEG => "image/jpeg",
Expand All @@ -37,7 +37,7 @@ impl Type {
Type::ZIP => "application/x-zip",
}
}
pub fn is_video(&self) -> bool {
#[must_use] pub fn is_video(&self) -> bool {
matches!(self, Type::MP4 | Type::WEBM)
}
}
Expand All @@ -63,7 +63,7 @@ fn check_mp4(that: &[u8]) -> bool {
sig(bytes_offset_removed, &MP4)
}

pub fn get_sig(buf: &[u8]) -> Option<Type> {
#[must_use] pub fn get_sig(buf: &[u8]) -> Option<Type> {
match buf {
[71, 73, 70, ..] => Some(Type::GIF),
[255, 216, 255, ..] => Some(Type::JPEG),
Expand Down
32 changes: 11 additions & 21 deletions assyst-common/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub fn tracing_init() {
info!("Initialised logging");
}

pub fn format_duration(duration: &Duration) -> String {
#[must_use] pub fn format_duration(duration: &Duration) -> String {
if *duration > Duration::SECOND {
let seconds = duration.as_millis() as f64 / 1000.0;
format!("{seconds:.2}s")
Expand All @@ -105,7 +105,7 @@ mod units {
}

/// Pluralizes a string
pub fn pluralize<'a>(s: &'a str, adder: &str, count: u64) -> Cow<'a, str> {
#[must_use] pub fn pluralize<'a>(s: &'a str, adder: &str, count: u64) -> Cow<'a, str> {
if count == 1 {
Cow::Borrowed(s)
} else {
Expand All @@ -114,7 +114,7 @@ pub fn pluralize<'a>(s: &'a str, adder: &str, count: u64) -> Cow<'a, str> {
}

/// Converts a timestamp to a humanly readable string
pub fn format_time(input: u64) -> String {
#[must_use] pub fn format_time(input: u64) -> String {
if input >= units::DAY {
let amount = input / units::DAY;
format!("{} {}", amount, pluralize("day", "s", amount))
Expand All @@ -136,52 +136,42 @@ pub fn format_time(input: u64) -> String {
/// It is much more efficient for valid UTF-8, but will be
/// much worse than `String::from_utf8` for invalid UTF-8, so
/// only use it if valid UTF-8 is likely!
pub fn string_from_likely_utf8(bytes: Vec<u8>) -> String {
#[must_use] pub fn string_from_likely_utf8(bytes: Vec<u8>) -> String {
String::from_utf8(bytes).unwrap_or_else(|err| {
// Unlucky, data was invalid UTF-8, so try again but use lossy decoding this time.
String::from_utf8_lossy(err.as_bytes()).into_owned()
})
}

/// Hashes a buffer. Appends a random string.
pub fn hash_buffer(buf: &[u8]) -> String {
#[must_use] pub fn hash_buffer(buf: &[u8]) -> String {
let mut body_hasher = DefaultHasher::new();
buf.hash(&mut body_hasher);
let rand = rand::thread_rng().gen::<usize>();
format!("{:x}{:x}", body_hasher.finish(), rand)
}

pub fn sanitise_filename(name: &str) -> String {
name.replace("/", "_")
.replace("<", "_")
.replace(">", "_")
.replace(":", "_")
.replace("\"", "_")
.replace("|", "_")
.replace("\\", "_")
.replace("?", "_")
.replace("*", "_")
#[must_use] pub fn sanitise_filename(name: &str) -> String {
name.replace(['/', '<', '>', ':', '"', '|', '\\', '?', '*'], "_")
}

#[inline(always)]
pub fn unix_timestamp() -> u64 {
#[must_use] pub fn unix_timestamp() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64
}

/// Normalizes custom emojis by replacing them with their names
pub fn normalize_emojis(input: &str) -> Cow<'_, str> {
#[must_use] pub fn normalize_emojis(input: &str) -> Cow<'_, str> {
CUSTOM_EMOJI.replace_all(input, |c: &Captures| c.get(1).unwrap().as_str().to_string())
}

/// Normalizes mentions by replacing them with their names
pub fn normalize_mentions<'a>(input: &'a str, mentions: &[Mention]) -> Cow<'a, str> {
#[must_use] pub fn normalize_mentions<'a>(input: &'a str, mentions: &[Mention]) -> Cow<'a, str> {
USER_MENTION.replace_all(input, |c: &Captures| {
let id = c.get(1).unwrap().as_str();
let name = mentions
.iter()
.find(|m| m.id.to_string().eq(id))
.map(|m| m.name.clone())
.unwrap_or_else(String::new);
.find(|m| m.id.to_string().eq(id)).map_or_else(String::new, |m| m.name.clone());
name
})
}
Loading

0 comments on commit 13af4d1

Please sign in to comment.