File tree 2 files changed +15
-10
lines changed
2 files changed +15
-10
lines changed Original file line number Diff line number Diff line change @@ -281,17 +281,20 @@ impl<'a> Arguments<'a> {
281
281
let pieces_length: W < usize > = self . pieces . iter ( )
282
282
. map ( |x| W ( x. len ( ) ) ) . sum ( ) ;
283
283
284
- // If they are any arguments to format, the string will most likely
285
- // double in size. So we're pre-doubling it here.
286
- let multiplier = if self . args . is_empty ( ) { W ( 1 ) } else { W ( 2 ) } ;
287
-
288
- let capacity = multiplier * pieces_length;
289
- if multiplier == W ( 2 ) && ( W ( 1 ) ..W ( 8 ) ) . contains ( capacity) {
290
- // Allocations smaller than 8 don't really make sense for String.
291
- 8
284
+ if self . args . is_empty ( ) {
285
+ pieces_length. 0
286
+ } else if self . pieces [ 0 ] == "" && pieces_length < W ( 16 ) {
287
+ // If the format string starts with an argument,
288
+ // don't preallocate anything, unless length
289
+ // of pieces is significant.
290
+ 0
292
291
} else {
293
- capacity. 0
292
+ // There are some arguments, so any additional push
293
+ // will reallocate the string. To avoid that,
294
+ // we're "pre-doubling" the capacity here.
295
+ ( pieces_length * W ( 2 ) ) . 0
294
296
}
297
+
295
298
}
296
299
}
297
300
Original file line number Diff line number Diff line change @@ -31,8 +31,10 @@ fn test_pointer_formats_data_pointer() {
31
31
32
32
#[ test]
33
33
fn test_estimated_capacity ( ) {
34
+ assert_eq ! ( format_args!( "" ) . estimated_capacity( ) , 0 ) ;
34
35
assert_eq ! ( format_args!( "{}" , "" ) . estimated_capacity( ) , 0 ) ;
35
36
assert_eq ! ( format_args!( "Hello" ) . estimated_capacity( ) , 5 ) ;
36
37
assert_eq ! ( format_args!( "Hello, {}!" , "" ) . estimated_capacity( ) , 16 ) ;
37
- assert_eq ! ( format_args!( "{}, hello!" , "World" ) . estimated_capacity( ) , 16 ) ;
38
+ assert_eq ! ( format_args!( "{}, hello!" , "World" ) . estimated_capacity( ) , 0 ) ;
39
+ assert_eq ! ( format_args!( "{}. 16-bytes piece" , "World" ) . estimated_capacity( ) , 32 ) ;
38
40
}
You can’t perform that action at this time.
0 commit comments