Skip to content

Commit 08cd0a9

Browse files
authored
Save string allocation on prefix commands using non-default prefix (#120)
1 parent 698c327 commit 08cd0a9

2 files changed

Lines changed: 18 additions & 12 deletions

File tree

src/main.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,9 @@ async fn main_(start_time: std::time::SystemTime) -> Result<()> {
164164
),
165165
pre_command: analytics::pre_command,
166166
prefix_options: poise::PrefixFrameworkOptions {
167-
dynamic_prefix: Some(|ctx| Box::pin(tts_commands::get_prefix(ctx))),
167+
stripped_dynamic_prefix: Some(|ctx, message, _| {
168+
Box::pin(tts_commands::try_strip_prefix(ctx, message))
169+
}),
168170
..poise::PrefixFrameworkOptions::default()
169171
},
170172
command_check: Some(|ctx| Box::pin(tts_commands::command_check(ctx))),

tts_commands/src/lib.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use serenity::all::{self as serenity, Mentionable as _};
99
use tts_core::{
1010
constants::PREMIUM_NEUTRAL_COLOUR,
1111
opt_ext::OptionTryUnwrap as _,
12-
structs::{Command, Context, FailurePoint, PartialContext, Result},
12+
structs::{Command, Context, Data, FailurePoint, Result},
1313
traits::PoiseContextExt,
1414
};
1515

@@ -111,22 +111,26 @@ pub async fn premium_command_check(ctx: Context<'_>) -> Result<bool> {
111111
Ok(false)
112112
}
113113

114-
pub async fn get_prefix(ctx: PartialContext<'_>) -> Result<Option<Cow<'static, str>>> {
115-
let Some(guild_id) = ctx.guild_id else {
116-
return Ok(Some(Cow::Borrowed("-")));
114+
pub async fn try_strip_prefix<'a>(
115+
ctx: &serenity::Context,
116+
message: &'a serenity::Message,
117+
) -> Result<Option<(&'a str, &'a str)>> {
118+
let Some(guild_id) = message.guild_id else {
119+
if message.content.starts_with('-') {
120+
return Ok(Some(message.content.split_at("-".len())));
121+
}
122+
return Ok(None);
117123
};
118124

119-
let data = ctx.framework.user_data();
125+
let data = ctx.data_ref::<Data>();
120126
let row = data.guilds_db.get(guild_id.into()).await?;
121127

122128
let prefix = row.prefix.as_str();
123-
let prefix = if prefix == "-" {
124-
Cow::Borrowed("-")
125-
} else {
126-
Cow::Owned(String::from(prefix))
127-
};
129+
if message.content.starts_with(prefix) {
130+
return Ok(Some(message.content.split_at(prefix.len())));
131+
}
128132

129-
Ok(Some(prefix))
133+
Ok(None)
130134
}
131135

132136
#[cold]

0 commit comments

Comments
 (0)