Skip to content

Commit 357010d

Browse files
authored
Optimize User::tag to return std::borrow::Cow instead of always a String (#3383)
1 parent 3009d22 commit 357010d

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

src/model/user.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,7 @@ impl User {
493493
/// # }
494494
/// ```
495495
#[must_use]
496-
pub fn tag(&self) -> String {
496+
pub fn tag(&self) -> std::borrow::Cow<'_, str> {
497497
tag(&self.name, self.discriminator)
498498
}
499499

@@ -717,17 +717,20 @@ fn banner_url(user_id: UserId, hash: Option<&ImageHash>) -> Option<String> {
717717
}
718718

719719
#[cfg(feature = "model")]
720-
fn tag(name: &str, discriminator: Option<NonZeroU16>) -> String {
720+
fn tag(name: &str, discriminator: Option<NonZeroU16>) -> std::borrow::Cow<'_, str> {
721+
let Some(discriminator) = discriminator else {
722+
return std::borrow::Cow::Borrowed(name);
723+
};
724+
721725
// 32: max length of username
722726
// 1: `#`
723727
// 4: max length of discriminator
724728
let mut tag = String::with_capacity(37);
725729
tag.push_str(name);
726-
if let Some(discriminator) = discriminator {
727-
tag.push('#');
728-
write!(tag, "{discriminator:04}").expect("writing to a string should never fail");
729-
}
730-
tag
730+
tag.push('#');
731+
write!(tag, "{discriminator:04}").expect("writing to a string should never fail");
732+
733+
std::borrow::Cow::Owned(tag)
731734
}
732735

733736
#[cfg(test)]

0 commit comments

Comments
 (0)