Skip to content

Commit

Permalink
Remove various instances of impl AsRef<T> (#2736)
Browse files Browse the repository at this point in the history
This should improve compile times even more, by compiling a lot more
methods in Serenity, instead of the user's code.
  • Loading branch information
GnomedDev committed Mar 25, 2024
1 parent 6550713 commit df4bbba
Show file tree
Hide file tree
Showing 36 changed files with 511 additions and 824 deletions.
2 changes: 1 addition & 1 deletion examples/e09_create_message_builder/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl EventHandler for Handler {
.title("This is a title")
.description("This is a description")
.image("attachment://ferris_eyes.png")
.fields(vec![
.fields([
("This is the first field", "This is a field body", true),
("This is the second field", "Both fields are inline", true),
])
Expand Down
6 changes: 3 additions & 3 deletions examples/e10_collectors/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ async fn challenge(ctx: &Context, msg: &Message, _: Args) -> CommandResult {

// There is a method implemented for some models to conveniently collect replies. They return a
// builder that can be turned into a Stream, or here, where we can await a single reply
let collector = msg.author.await_reply(&ctx.shard).timeout(Duration::from_secs(10));
let collector = msg.author.await_reply(ctx.shard.clone()).timeout(Duration::from_secs(10));
if let Some(answer) = collector.await {
if answer.content.to_lowercase() == "ferris" {
let _ = answer.reply(ctx, "That's correct!").await;
Expand All @@ -114,7 +114,7 @@ async fn challenge(ctx: &Context, msg: &Message, _: Args) -> CommandResult {

// The message model can also be turned into a Collector to collect reactions on it.
let collector = react_msg
.await_reaction(&ctx.shard)
.await_reaction(ctx.shard.clone())
.timeout(Duration::from_secs(10))
.author_id(msg.author.id);

Expand All @@ -132,7 +132,7 @@ async fn challenge(ctx: &Context, msg: &Message, _: Args) -> CommandResult {
let _ = msg.reply(ctx, "Write 5 messages in 10 seconds").await;

// We can create a collector from scratch too using this builder future.
let collector = MessageCollector::new(&ctx.shard)
let collector = MessageCollector::new(ctx.shard.clone())
// Only collect messages by this user.
.author_id(msg.author.id)
.channel_id(msg.channel_id)
Expand Down
8 changes: 5 additions & 3 deletions examples/e16_message_components/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl EventHandler for Handler {
// This uses a collector to wait for an incoming event without needing to listen for it
// manually in the EventHandler.
let interaction = match m
.await_component_interaction(&ctx.shard)
.await_component_interaction(ctx.shard.clone())
.timeout(Duration::from_secs(60 * 3))
.await
{
Expand Down Expand Up @@ -106,8 +106,10 @@ impl EventHandler for Handler {
.unwrap();

// Wait for multiple interactions
let mut interaction_stream =
m.await_component_interaction(&ctx.shard).timeout(Duration::from_secs(60 * 3)).stream();
let mut interaction_stream = m
.await_component_interaction(ctx.shard.clone())
.timeout(Duration::from_secs(60 * 3))
.stream();

while let Some(interaction) = interaction_stream.next().await {
let sound = &interaction.data.custom_id;
Expand Down
39 changes: 21 additions & 18 deletions examples/testing/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
.send_message(
&ctx,
CreateMessage::new()
.add_file(CreateAttachment::url(ctx, IMAGE_URL, "testing.png").await?),
.add_file(CreateAttachment::url(&ctx.http, IMAGE_URL, "testing.png").await?),
)
.await?;
// Pre-PR, this falsely triggered a MODEL_TYPE_CONVERT Discord error
Expand All @@ -71,14 +71,14 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
.send_message(
ctx,
CreateMessage::new()
.add_file(CreateAttachment::url(ctx, IMAGE_URL, "testing.png").await?),
.add_file(CreateAttachment::url(&ctx.http, IMAGE_URL, "testing.png").await?),
)
.await?;
msg.edit(
ctx,
EditMessage::new().attachments(
EditAttachments::keep_all(&msg)
.add(CreateAttachment::url(ctx, IMAGE_URL_2, "testing1.png").await?),
.add(CreateAttachment::url(&ctx.http, IMAGE_URL_2, "testing1.png").await?),
),
)
.await?;
Expand Down Expand Up @@ -121,7 +121,7 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
)
.await?;
let button_press = msg
.await_component_interaction(&ctx.shard)
.await_component_interaction(ctx.shard.clone())
.timeout(std::time::Duration::from_secs(10))
.await;
match button_press {
Expand All @@ -146,11 +146,11 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
}),
)
.await?;
println!("new automod rules: {:?}", guild_id.automod_rules(ctx).await?);
println!("new automod rules: {:?}", guild_id.automod_rules(&ctx.http).await?);
} else if let Some(user_id) = msg.content.strip_prefix("ban ") {
// Test if banning without a reason actually works
let user_id: UserId = user_id.trim().parse().unwrap();
guild_id.ban(ctx, user_id, 0).await?;
guild_id.ban(&ctx.http, user_id, 0).await?;
} else if msg.content == "createtags" {
channel_id
.edit(
Expand Down Expand Up @@ -199,7 +199,7 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
ctx,
CreateMessage::new()
.flags(MessageFlags::IS_VOICE_MESSAGE)
.add_file(CreateAttachment::url(ctx, audio_url, "testing.ogg").await?),
.add_file(CreateAttachment::url(&ctx.http, audio_url, "testing.ogg").await?),
)
.await?;
} else if let Some(channel) = msg.content.strip_prefix("movetorootandback") {
Expand All @@ -209,7 +209,7 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
channel.edit(ctx, EditChannel::new().category(None)).await?;
channel.edit(ctx, EditChannel::new().category(Some(parent_id))).await?;
} else if msg.content == "channelperms" {
let guild = guild_id.to_guild_cached(ctx).unwrap().clone();
let guild = guild_id.to_guild_cached(&ctx.cache).unwrap().clone();
let perms = guild.user_permissions_in(
&channel_id.to_channel(ctx).await?.guild().unwrap(),
&*guild.member(ctx, msg.author.id).await?,
Expand All @@ -233,7 +233,7 @@ async fn message(ctx: &Context, msg: Message) -> Result<(), serenity::Error> {
serenity::utils::parse_message_url(forum_post_url).unwrap();
msg.channel_id.say(ctx, format!("Deleting <#{}> in 10 seconds...", channel_id)).await?;
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
channel_id.delete(ctx).await?;
channel_id.delete(&ctx.http).await?;
} else {
return Ok(());
}
Expand All @@ -252,22 +252,23 @@ async fn interaction(
.create_response(
&ctx,
CreateInteractionResponse::Message(
CreateInteractionResponseMessage::new()
.add_file(CreateAttachment::url(ctx, IMAGE_URL, "testing.png").await?),
CreateInteractionResponseMessage::new().add_file(
CreateAttachment::url(&ctx.http, IMAGE_URL, "testing.png").await?,
),
),
)
.await?;

// We need to know the attachments' IDs in order to not lose them in the subsequent edit
let msg = interaction.get_response(ctx).await?;
let msg = interaction.get_response(&ctx.http).await?;

// Add another image
let msg = interaction
.edit_response(
&ctx,
EditInteractionResponse::new().attachments(
EditAttachments::keep_all(&msg)
.add(CreateAttachment::url(ctx, IMAGE_URL_2, "testing1.png").await?),
.add(CreateAttachment::url(&ctx.http, IMAGE_URL_2, "testing1.png").await?),
),
)
.await?;
Expand Down Expand Up @@ -307,25 +308,27 @@ async fn interaction(
.create_response(
ctx,
CreateInteractionResponse::Message(
CreateInteractionResponseMessage::new()
.add_file(CreateAttachment::url(ctx, IMAGE_URL, "testing.png").await?),
CreateInteractionResponseMessage::new().add_file(
CreateAttachment::url(&ctx.http, IMAGE_URL, "testing.png").await?,
),
),
)
.await?;

interaction
.edit_response(
ctx,
EditInteractionResponse::new()
.new_attachment(CreateAttachment::url(ctx, IMAGE_URL_2, "testing1.png").await?),
EditInteractionResponse::new().new_attachment(
CreateAttachment::url(&ctx.http, IMAGE_URL_2, "testing1.png").await?,
),
)
.await?;

interaction
.create_followup(
ctx,
CreateInteractionResponseFollowup::new()
.add_file(CreateAttachment::url(ctx, IMAGE_URL, "testing.png").await?),
.add_file(CreateAttachment::url(&ctx.http, IMAGE_URL, "testing.png").await?),
)
.await?;
} else if interaction.data.name == "editembeds" {
Expand Down
4 changes: 2 additions & 2 deletions src/builder/bot_auth_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ impl<'a> CreateBotAuthParameters<'a> {
///
/// [`HttpError::UnsuccessfulRequest`]: crate::http::HttpError::UnsuccessfulRequest
#[cfg(feature = "http")]
pub async fn auto_client_id(mut self, http: impl AsRef<Http>) -> Result<Self> {
self.client_id = http.as_ref().get_current_application_info().await.map(|v| Some(v.id))?;
pub async fn auto_client_id(mut self, http: &Http) -> Result<Self> {
self.client_id = http.get_current_application_info().await.map(|v| Some(v.id))?;
Ok(self)
}

Expand Down
28 changes: 16 additions & 12 deletions src/builder/create_attachment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,22 @@ impl<'a> CreateAttachment<'a> {
///
/// [`Error::Io`] if reading the file fails.
pub async fn path(path: impl AsRef<Path>) -> Result<Self> {
let mut file = File::open(path.as_ref()).await?;
let mut data = Vec::new();
file.read_to_end(&mut data).await?;
async fn inner(path: &Path) -> Result<CreateAttachment<'static>> {
let mut file = File::open(path).await?;
let mut data = Vec::new();
file.read_to_end(&mut data).await?;

let filename = path.file_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::Other,
"attachment path must not be a directory",
)
})?;

let filename = path.as_ref().file_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::Other,
"attachment path must not be a directory",
)
})?;
Ok(CreateAttachment::bytes(data, filename.to_string_lossy().into_owned()))
}

Ok(CreateAttachment::bytes(data, filename.to_string_lossy().into_owned()))
inner(path.as_ref()).await
}

/// Builds an [`CreateAttachment`] by reading from a file handler.
Expand All @@ -81,11 +85,11 @@ impl<'a> CreateAttachment<'a> {
/// Returns [`Error::Http`] if downloading the data fails.
#[cfg(feature = "http")]
pub async fn url(
http: impl AsRef<Http>,
http: &Http,
url: impl reqwest::IntoUrl,
filename: impl Into<Cow<'static, str>>,
) -> Result<Self> {
let response = http.as_ref().client.get(url).send().await?;
let response = http.client.get(url).send().await?;
let data = response.bytes().await?.to_vec();

Ok(CreateAttachment::bytes(data, filename))
Expand Down
4 changes: 2 additions & 2 deletions src/builder/create_interaction_response_followup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ impl Builder for CreateInteractionResponseFollowup<'_> {

let http = cache_http.http();
match ctx.0 {
Some(id) => http.as_ref().edit_followup_message(ctx.1, id, &self, files).await,
None => http.as_ref().create_followup_message(ctx.1, &self, files).await,
Some(id) => http.edit_followup_message(ctx.1, id, &self, files).await,
None => http.create_followup_message(ctx.1, &self, files).await,
}
}
}
53 changes: 0 additions & 53 deletions src/client/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,56 +322,3 @@ impl Context {
self.shard.set_presence(activity, status);
}
}

impl AsRef<Http> for Context {
fn as_ref(&self) -> &Http {
&self.http
}
}

impl AsRef<Http> for Arc<Context> {
fn as_ref(&self) -> &Http {
&self.http
}
}

impl AsRef<Arc<Http>> for Context {
fn as_ref(&self) -> &Arc<Http> {
&self.http
}
}

#[cfg(feature = "cache")]
impl AsRef<Cache> for Context {
fn as_ref(&self) -> &Cache {
&self.cache
}
}

#[cfg(feature = "cache")]
impl AsRef<Cache> for Arc<Context> {
fn as_ref(&self) -> &Cache {
&self.cache
}
}

#[cfg(feature = "cache")]
impl AsRef<Arc<Cache>> for Context {
fn as_ref(&self) -> &Arc<Cache> {
&self.cache
}
}

#[cfg(feature = "cache")]
impl AsRef<Cache> for Cache {
fn as_ref(&self) -> &Cache {
self
}
}

#[cfg(feature = "gateway")]
impl AsRef<ShardMessenger> for Context {
fn as_ref(&self) -> &ShardMessenger {
&self.shard
}
}
4 changes: 2 additions & 2 deletions src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ macro_rules! make_specific_collector {

impl $collector_type {
/// Creates a new collector without any filters configured.
pub fn new(shard: impl AsRef<ShardMessenger>) -> Self {
pub fn new(shard: ShardMessenger) -> Self {
Self {
shard: shard.as_ref().clone(),
shard,
duration: None,
filter: None,
$( $filter_name: None, )*
Expand Down
16 changes: 7 additions & 9 deletions src/framework/standard/help_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,7 @@ pub enum CustomisedHelpData<'a> {

/// Checks whether a user is member of required roles and given the required permissions.
#[cfg(feature = "cache")]
pub fn has_all_requirements(cache: impl AsRef<Cache>, cmd: &CommandOptions, msg: &Message) -> bool {
let cache = cache.as_ref();

pub fn has_all_requirements(cache: &Cache, cmd: &CommandOptions, msg: &Message) -> bool {
if let Some(guild_id) = msg.guild_id {
if let Some(member) = cache.member(guild_id, msg.author.id) {
if let Ok(permissions) = member.permissions(cache) {
Expand Down Expand Up @@ -219,7 +217,7 @@ fn starts_with_whole_word(search_on: &str, word: &str) -> bool {
// Decides how a listed help entry shall be displayed.
#[cfg(all(feature = "cache", feature = "http"))]
fn check_common_behaviour(
cache: impl AsRef<Cache>,
cache: &Cache,
msg: &Message,
options: &impl CommonOptions,
owners: &HashSet<UserId, impl std::hash::BuildHasher + Send + Sync>,
Expand All @@ -243,11 +241,11 @@ fn check_common_behaviour(
return HelpBehaviour::Nothing;
}

if !has_correct_permissions(&cache, options, msg) {
if !has_correct_permissions(cache, options, msg) {
return help_options.lacking_permissions;
}

msg.guild(cache.as_ref())
msg.guild(cache)
.and_then(|guild| {
if let Some(member) = guild.members.get(&msg.author.id) {
if !has_correct_roles(options, &guild.roles, member) {
Expand All @@ -269,7 +267,7 @@ async fn check_command_behaviour(
owners: &HashSet<UserId, impl std::hash::BuildHasher + Send + Sync>,
help_options: &HelpOptions,
) -> HelpBehaviour {
let behaviour = check_common_behaviour(ctx, msg, &options, owners, help_options);
let behaviour = check_common_behaviour(&ctx.cache, msg, &options, owners, help_options);

if behaviour == HelpBehaviour::Nothing
&& (!options.owner_privilege || !owners.contains(&msg.author.id))
Expand Down Expand Up @@ -444,7 +442,7 @@ fn nested_group_command_search<'rec, 'a: 'rec>(
for group in groups {
let group = *group;
let group_behaviour =
check_common_behaviour(ctx, msg, &group.options, owners, help_options);
check_common_behaviour(&ctx.cache, msg, &group.options, owners, help_options);

match &group_behaviour {
HelpBehaviour::Nothing => (),
Expand Down Expand Up @@ -593,7 +591,7 @@ async fn fill_eligible_commands<'a>(
} else {
std::cmp::max(
*highest_formatter,
check_common_behaviour(ctx, msg, &group.options, owners, help_options),
check_common_behaviour(&ctx.cache, msg, &group.options, owners, help_options),
)
}
};
Expand Down
Loading

0 comments on commit df4bbba

Please sign in to comment.