@@ -2071,35 +2071,55 @@ impl str {
2071
2071
return String :: new ( ) ;
2072
2072
}
2073
2073
2074
- // n = 2^j + k (2^j > k)
2075
-
2076
- // 2^j:
2077
- let mut s = Vec :: with_capacity ( self . len ( ) * n) ;
2078
- s. extend ( self . as_bytes ( ) ) ;
2079
- let mut m = n >> 1 ;
2080
- while m > 0 {
2081
- let len = s. len ( ) ;
2082
- unsafe {
2083
- ptr:: copy_nonoverlapping ( s. as_ptr ( ) , ( s. as_mut_ptr ( ) as * mut u8 ) . add ( len) , len) ;
2084
- s. set_len ( len * 2 ) ;
2074
+ // If `n` is larger than zero, it can be split as
2075
+ // `n = 2^expn + rem (2^expn > rem, expn >= 0, rem >= 0)`.
2076
+ // `2^expn` is the number represented by the leftmost '1' bit of `n`,
2077
+ // and `rem` is the remaining part of `n`.
2078
+
2079
+ // Using `Vec` to access `set_len()`.
2080
+ let mut buf = Vec :: with_capacity ( self . len ( ) * n) ;
2081
+
2082
+ // `2^expn` repetition is done by doubling `buf` `expn`-times.
2083
+ buf. extend ( self . as_bytes ( ) ) ;
2084
+ {
2085
+ let mut m = n >> 1 ;
2086
+ // If `m > 0`, there are remaining bits up to the leftmost '1'.
2087
+ while m > 0 {
2088
+ // `buf.extend(buf)`:
2089
+ unsafe {
2090
+ ptr:: copy_nonoverlapping (
2091
+ buf. as_ptr ( ) ,
2092
+ ( buf. as_mut_ptr ( ) as * mut u8 ) . add ( buf. len ( ) ) ,
2093
+ buf. len ( ) ,
2094
+ ) ;
2095
+ // `buf` has capacity of `self.len() * n`.
2096
+ let buf_len = buf. len ( ) ;
2097
+ buf. set_len ( buf_len * 2 ) ;
2098
+ }
2099
+
2100
+ m >>= 1 ;
2085
2101
}
2086
- m >>= 1 ;
2087
2102
}
2088
2103
2089
- // k:
2090
- let res_len = n * self . len ( ) ;
2091
- if res_len > s. len ( ) {
2104
+ // `rem` (`= n - 2^expn`) repetition is done by copying
2105
+ // first `rem` repetitions from `buf` itself.
2106
+ let rem_len = self . len ( ) * n - buf. len ( ) ; // `self.len() * rem`
2107
+ if rem_len > 0 {
2108
+ // `buf.extend(buf[0 .. rem_len])`:
2092
2109
unsafe {
2110
+ // This is non-overlapping since `2^expn > rem`.
2093
2111
ptr:: copy_nonoverlapping (
2094
- s . as_ptr ( ) ,
2095
- ( s . as_mut_ptr ( ) as * mut u8 ) . add ( s . len ( ) ) ,
2096
- res_len - s . len ( ) ,
2112
+ buf . as_ptr ( ) ,
2113
+ ( buf . as_mut_ptr ( ) as * mut u8 ) . add ( buf . len ( ) ) ,
2114
+ rem_len ,
2097
2115
) ;
2098
- s. set_len ( res_len) ;
2116
+ // `buf.len() + rem_len` equals to `buf.capacity()` (`self.len() * n`).
2117
+ let buf_len = buf. len ( ) ;
2118
+ buf. set_len ( buf_len + rem_len) ;
2099
2119
}
2100
2120
}
2101
2121
2102
- unsafe { String :: from_utf8_unchecked ( s ) }
2122
+ unsafe { String :: from_utf8_unchecked ( buf ) }
2103
2123
}
2104
2124
2105
2125
/// Checks if all characters in this string are within the ASCII range.
0 commit comments