Skip to content

Commit

Permalink
Auto merge of #131929 - LaihoE:replace_default_capacity, r=<try>
Browse files Browse the repository at this point in the history
better default capacity for str::replace

Adds smarter capacity for str::replace in cases where we know that the output will be at least as long as the original string.
  • Loading branch information
bors committed Oct 19, 2024
2 parents c926476 + f4ae7ee commit e7f57a1
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions library/alloc/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,6 @@ impl str {
#[inline]
pub fn replace<P: Pattern>(&self, from: P, to: &str) -> String {
// Fast path for ASCII to ASCII case.

if let Some(from_byte) = match from.as_utf8_pattern() {
Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte),
Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char| ascii_char.to_u8()),
Expand All @@ -280,8 +279,16 @@ impl str {
return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) };
}
}

let mut result = String::new();
let to_len = to.as_bytes().len();
// Set result capacity to self.len() when from.len() <= to.len()
let default_capacity = match from.as_utf8_pattern() {
Some(Utf8Pattern::StringPattern(s)) if s.len() <= to_len => self.len(),
Some(Utf8Pattern::CharPattern(c)) if c.encode_utf8(&mut [0; 4]).len() <= to_len => {
self.len()
}
_ => 0,
};
let mut result = String::with_capacity(default_capacity);
let mut last_end = 0;
for (start, part) in self.match_indices(from) {
result.push_str(unsafe { self.get_unchecked(last_end..start) });
Expand Down

0 comments on commit e7f57a1

Please sign in to comment.