File tree 1 file changed +8
-3
lines changed
1 file changed +8
-3
lines changed Original file line number Diff line number Diff line change @@ -270,7 +270,6 @@ impl str {
270
270
#[ inline]
271
271
pub fn replace < P : Pattern > ( & self , from : P , to : & str ) -> String {
272
272
// Fast path for ASCII to ASCII case.
273
-
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| ascii_char. to_u8 ( ) ) ,
@@ -280,8 +279,14 @@ 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
+ 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. len_utf8 ( ) <= to_len => self . len ( ) ,
287
+ _ => 0 ,
288
+ } ;
289
+ let mut result = String :: with_capacity ( default_capacity) ;
285
290
let mut last_end = 0 ;
286
291
for ( start, part) in self . match_indices ( from) {
287
292
result. push_str ( unsafe { self . get_unchecked ( last_end..start) } ) ;
You can’t perform that action at this time.
0 commit comments