Consider the following code:
fn main() {
let mut vec: Vec<u8> = Vec::new();
vec.push(0);
vec.push(1);
vec.push(2);
vec.push(3);
vec.push(4);
vec.push(5);
vec.push(6);
vec.push(7);
vec.push(8);
}
When Vec::new() is called, Rust doesn't know how much to allocate, and each time it needs to allocate more space for a vector, it calls malloc with the new size and then clones all the data from the old location in the heap to the new, right?
What is Rust's strategy for knowing the new size to allocate?
For example, does Rust allocate each time something is pushed onto the vector, like this?
[]
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
etc...
That seems inefficient. Maybe Rust does something like this:
[]
[0, <empty>]
[0, 1]
[0, 1, 2, <empty>, <empty>, <empty>, <empty>, <empty>]
[0, 1, 2, 3, <empty>, <empty>, <empty>, <empty>]
[0, 1, 2, 3, 4, <empty>, <empty>, <empty>]
etc...