Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading