@@ -269,8 +269,7 @@ impl str { |
|
|
269 |
269 |
#[stable(feature = "rust1", since = "1.0.0")] |
270 |
270 |
#[inline] |
271 |
271 |
pub fn replace<P: Pattern>(&self, from: P, to: &str) -> String { |
272 |
|
-// Fast path for ASCII to ASCII case. |
273 |
|
- |
|
272 |
+// Fast path for replacing a single ASCII character with another. |
274 |
273 |
if let Some(from_byte) = match from.as_utf8_pattern() { |
275 |
274 |
Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte), |
276 |
275 |
Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char |
@@ -280,8 +279,13 @@ impl str { |
|
|
280 |
279 |
return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) }; |
281 |
280 |
} |
282 |
281 |
} |
283 |
|
- |
284 |
|
-let mut result = String::new(); |
|
282 |
+// Set result capacity to self.len() when from.len() <= to.len() |
|
283 |
+let default_capacity = match from.as_utf8_pattern() { |
|
284 |
+Some(Utf8Pattern::StringPattern(s)) if s.len() <= to.len() => self.len(), |
|
285 |
+Some(Utf8Pattern::CharPattern(c)) if c.len_utf8() <= to.len() => self.len(), |
|
286 |
+ _ => 0, |
|
287 |
+}; |
|
288 |
+let mut result = String::with_capacity(default_capacity); |
285 |
289 |
let mut last_end = 0; |
286 |
290 |
for (start, part) in self.match_indices(from) { |
287 |
291 |
result.push_str(unsafe { self.get_unchecked(last_end..start) }); |