Search code examples
rustvectorheap-memoryallocator

How does std::vec::shrink_to_fit work in Rust?


Does std::vec::shrink_to_fit allocate a new, smaller vec.len() buffer of data, copy to it, and destruct the old buffer, or does it somehow indicate to the memory allocator that the uninitialised part of the buffer can be de-allocated, and simply release that part of the memory? Is that even possible? Does that depend on the memory allocator?

And a tangential question which I apologise to ask here, but if that's possible, why don't we, for example, implement popping from the front of a vector as a simple "release std::mem::size_of<T>() amount of memory from the start of the buffer, and increment our pointer by one", rather than shifting all our elements by one?


Solution

  • The Vec::shrink_to_fit() uses the Allocator::shrink() method to shrink the allocation (via the internal RawVec::shrink_to_fit(), method which may simply resize the existing allocation in-place without moving the data, or it might return a different memory block.

    You can't pop from the front of a vector by re-sizing it, because memory allocations can't have their start address changed, only their length.