Skip to content

Commit e7f57a1

Browse files
committed
Auto merge of #131929 - LaihoE:replace_default_capacity, r=<try>
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.
2 parents c926476 + f4ae7ee commit e7f57a1

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

library/alloc/src/str.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,6 @@ impl str {
270270
#[inline]
271271
pub fn replace<P: Pattern>(&self, from: P, to: &str) -> String {
272272
// Fast path for ASCII to ASCII case.
273-
274273
if let Some(from_byte) = match from.as_utf8_pattern() {
275274
Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte),
276275
Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char| ascii_char.to_u8()),
@@ -280,8 +279,16 @@ impl str {
280279
return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) };
281280
}
282281
}
283-
284-
let mut result = String::new();
282+
let to_len = to.as_bytes().len();
283+
// Set result capacity to self.len() when from.len() <= to.len()
284+
let default_capacity = match from.as_utf8_pattern() {
285+
Some(Utf8Pattern::StringPattern(s)) if s.len() <= to_len => self.len(),
286+
Some(Utf8Pattern::CharPattern(c)) if c.encode_utf8(&mut [0; 4]).len() <= to_len => {
287+
self.len()
288+
}
289+
_ => 0,
290+
};
291+
let mut result = String::with_capacity(default_capacity);
285292
let mut last_end = 0;
286293
for (start, part) in self.match_indices(from) {
287294
result.push_str(unsafe { self.get_unchecked(last_end..start) });

0 commit comments

Comments
 (0)