diff options
| author | Laiho <emillaiho@hotmail.fi> | 2024-10-19 16:49:07 +0300 |
|---|---|---|
| committer | Laiho <emillaiho@hotmail.fi> | 2024-10-22 19:53:33 +0300 |
| commit | c8391802afc158759dfe234e22f665d39091ea8d (patch) | |
| tree | d2cdf1c15452e53dd898d61e7f17f0c02b60f110 /library/alloc/src | |
| parent | b27f33a4d9c42ee6b5347a75a8a990a883437da9 (diff) | |
| download | rust-c8391802afc158759dfe234e22f665d39091ea8d.tar.gz rust-c8391802afc158759dfe234e22f665d39091ea8d.zip | |
better default capacity for str::replace
Diffstat (limited to 'library/alloc/src')
| -rw-r--r-- | library/alloc/src/str.rs | 12 |
1 files changed, 8 insertions, 4 deletions
diff --git a/library/alloc/src/str.rs b/library/alloc/src/str.rs index 52ceb8b45f9..26c1ba2a5c4 100644 --- a/library/alloc/src/str.rs +++ b/library/alloc/src/str.rs @@ -269,8 +269,7 @@ impl str { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn replace<P: Pattern>(&self, from: P, to: &str) -> String { - // Fast path for ASCII to ASCII case. - + // Fast path for replacing a single ASCII character with another. 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()), @@ -280,8 +279,13 @@ impl str { return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) }; } } - - let mut result = String::new(); + // 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.len_utf8() <= 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) }); |
