Add implementation for computing the required bytes to encode a message #2239
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.
Summary
This commit introduces a new API which computes the required bytes to encode a message without actually serializing a message. The size is computed on the first call and memoized. By extension, this API is meant to be used as a cornerstone for implementing #2075.
Goal:
After feedback on #2082, the most critical problem we had to solve was how to
make an actual streaming protobuf without reading all to byte array first
. This API solves this problem, as we can calculate the required bytes to encode a message.By extension, this pr acts as a proof of concept, and also as a base to enable discussions for #2075.
Implementation notes
API
The API which is introduced:
Even though this API has some usage for consumers, for example see protobuf.js#162, it can also be considered as an internal API to support only encoding/decoding delimited-messages.
Tests
The main tests are written in jvm platform, because java's
serializedSize
API result is used to test against getOrComputeSerializedSize() result.Multiplatform
Native and Js implementations do not use concurrent-safe structures.
Even though the core implementation is written in common module, it is tested only in jvm. In case we decide to keep this API in common then tests should be moved in common or re-think testing strategy.
Additionally, since the goal of this API is to be used as a cornerstone for a jvm only feature, it is debatable if the API really belongs to common module.
Inspiration
The inspiration came from how the official library (google's) solved this issue, in particular java's implementation. That being said, it is to be noted that many byte operations were "rented" from google's impl (some with minor modifications, some not). This is done to avoid re-inventing the wheel, and because i'm not so experienced to create them by myself.