Skip to content

Commit 876c02c

Browse files
committed
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.
1 parent e25542c commit 876c02c

File tree

1 file changed

+1
-0
lines changed

1 file changed

+1
-0
lines changed

src/libstd/ffi/c_str.rs

+1
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ impl CString {
213213
/// byte vector, not anything that can be converted to one with Into.
214214
#[stable(feature = "rust1", since = "1.0.0")]
215215
pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
216+
v.reserve_exact(1);
216217
v.push(0);
217218
CString { inner: v.into_boxed_slice() }
218219
}

0 commit comments

Comments
 (0)