Skip to content

Commit

Permalink
Auto merge of rust-lang#35871 - bluss:cstring-new, r=alexcrichton
Browse files Browse the repository at this point in the history
cstring: avoid excessive growth just to 0-terminate

Based on following what happens in CString::new("string literal"):

1. Using `Into<Vec<u8>>`, a Vec is allocated with capacity exactly equal
   to the string's input length.
2. By `v.push(0)`, the Vec is grown to twice capacity, since it was full.
3. By `v.into_boxed_slice()`, the Vec capacity is shrunk to fit the length again.

If we use `.reserve_exact(1)` just before the push, then we avoid the
capacity doubling that we're going to have to shrink anyway.

Growing by just 1 byte means that the step (2) is less likely to have to
move the memory to a larger allocation chunk, and that the step (3) does
not have to reallocate.

Addresses part of rust-lang#35838
  • Loading branch information
bors authored Aug 22, 2016
2 parents 57a1f68 + 876c02c commit 3c5a0fa
Showing 1 changed file with 1 addition and 0 deletions.
1 change: 1 addition & 0 deletions src/libstd/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ impl CString {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
v.reserve_exact(1);
v.push(0);
CString { inner: v.into_boxed_slice() }
}
Expand Down

0 comments on commit 3c5a0fa

Please sign in to comment.