Skip to content

Commit 7403ee9

Browse files
committed
Adjust heuristics to better handle "{}..." format strings.
1 parent e74b55b commit 7403ee9

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

src/libcore/fmt/mod.rs

+12-9
Original file line numberDiff line numberDiff line change
@@ -281,17 +281,20 @@ impl<'a> Arguments<'a> {
281281
let pieces_length: W<usize> = self.pieces.iter()
282282
.map(|x| W(x.len())).sum();
283283

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
292291
} 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
294296
}
297+
295298
}
296299
}
297300

src/libcoretest/fmt/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,10 @@ fn test_pointer_formats_data_pointer() {
3131

3232
#[test]
3333
fn test_estimated_capacity() {
34+
assert_eq!(format_args!("").estimated_capacity(), 0);
3435
assert_eq!(format_args!("{}", "").estimated_capacity(), 0);
3536
assert_eq!(format_args!("Hello").estimated_capacity(), 5);
3637
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);
3840
}

0 commit comments

Comments
 (0)