File tree Expand file tree Collapse file tree 1 file changed +8
-4
lines changed Expand file tree Collapse file tree 1 file changed +8
-4
lines changed Original file line number Diff line number Diff line change @@ -269,8 +269,7 @@ impl str {
269269 #[ stable( feature = "rust1" , since = "1.0.0" ) ]
270270 #[ inline]
271271 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.
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,13 @@ impl str {
280279 return unsafe { replace_ascii ( self . as_bytes ( ) , from_byte, * to_byte) } ;
281280 }
282281 }
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) ;
285289 let mut last_end = 0 ;
286290 for ( start, part) in self . match_indices ( from) {
287291 result. push_str ( unsafe { self . get_unchecked ( last_end..start) } ) ;
You can’t perform that action at this time.
0 commit comments