Skip to content

Commit

Permalink
Avoid cloning member out of cache in Guild::member (serenity-rs#1934)
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev authored and arqunis committed Sep 2, 2022
1 parent 2a64777 commit b70a54a
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/model/guild/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ mod scheduled_event;
mod system_channel;
mod welcome_screen;

#[cfg(feature = "model")]
use std::borrow::Cow;

use serde::de::Error as DeError;
#[cfg(feature = "model")]
use tracing::error;
Expand Down Expand Up @@ -1644,6 +1647,9 @@ impl Guild {

/// Gets a user's [`Member`] for the guild by Id.
///
/// If the cache feature is enabled [`Self::members`] will be checked
/// first, if so, a reference to the member will be returned.
///
/// # Errors
///
/// Returns an [`Error::Http`] if the user is not in
Expand All @@ -1653,8 +1659,14 @@ impl Guild {
&self,
cache_http: impl CacheHttp,
user_id: impl Into<UserId>,
) -> Result<Member> {
self.id.member(cache_http, user_id).await
) -> Result<Cow<'_, Member>> {
let user_id = user_id.into();

if let Some(member) = self.members.get(&user_id) {
Ok(Cow::Borrowed(member))
} else {
cache_http.http().get_member(self.id.0, user_id.0).await.map(Cow::Owned)
}
}

/// Gets a list of the guild's members.
Expand Down

0 comments on commit b70a54a

Please sign in to comment.