Simplify loop in REST encoding and fix an off by one bug in the allocation #4950
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.
The logic of the code was pretty much like this:
This means once the last part has been written by
func
, the returned length is larger than zero, so we run the loop once again, allocate a bigger chunk of memory, move the contents and free the old buffer, then callfunc
again to have it return a 0 immediately so we can return the buffer we already had in the previous iteration.Another effect of this logic is that the limit is effectively cut in half: the limit argument is 8K, but if the output is more than 4K and less than 8K, the loop gets into another iteration, but now alloc is more than limit, so it gets into the error state because it thinks it does not have enough space. We ran into this issue with JSON encoding (which is the most verbose output in the module) and EAP-TLS (which add a lot of virtual attributes with information about the certificate).