Add BytesMut::try_shrink_to_fit and BytesMut::try_shrink_to_capacity#834
Open
tsharp wants to merge 4 commits into
Open
Add BytesMut::try_shrink_to_fit and BytesMut::try_shrink_to_capacity#834tsharp wants to merge 4 commits into
tsharp wants to merge 4 commits into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes
BytesMut::try_shrink_to_fitwhen theBytesMutis an offset view into its backing allocation.Previously, the implementation called
Vec::shrink_to_fitwhile preserving the current offset into the allocation. That caused incorrect behavior for split/advanced buffers, including:truewhile leaving capacity larger than the current lengthThe fix normalizes the live byte range to the start of the backing
Vecbefore shrinking, then updates the handle to point at the new base allocation.Tests
Added coverage for:
split_offadvanceBytesMutand frozenBytesreferencesValidated with:
Why
While using
tokio-postgreswithdeadpool, we noticed increased memory usage from buffer allocations in these libraries. These buffers are pre-allocated when a connection is created and live until that connection is closed.For applications with only a few connections, or with consistently small result sets, this usually is not a problem. However, applications with many long-lived connections can accumulate a large amount of retained buffer capacity. If some of those connections occasionally handle large reads or writes, the associated
BytesMutbuffers can remain inflated for the rest of the connection lifetime, leading to significant memory overuse, sometimes multiple gigabytes depending on the application.Adding
try_shrink_to_fitandtry_shrink_to_capacityinstead of creating a new BytesMut for each request/response ideal over adding potentially significant churn in downstream codebases.References: