Add EncodedSize trait to calculate encoded sizes #609
Closed
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.
Related issue: #539
Hi bincode developers. This is the first in a series of 3 PRs that would allow us to replace our current use of Abomonation with bincode, without a noticeable performance hit. We'd like these to be adopted upstream, and hope they are useful for other users of bincode also.
For some storage back-ends it's necessary to know the size of the buffer to pre-allocate before encoding. This is true of our cache back-end, which is C++ code that we communicate with over FFI. The bincode 1.0 version had
bincode::serialized_size
, which would tell you the serialized size of data, but for bincode 2.0 this is not implemented.One suggestion is to implement a
SizeOnlyWriter
which adds up the sizes of the slices it's been given, however this effectively requires serializing the data twice, as it doesn't allow types to efficiently compute the size when it is possible to do so without performing the actual serialization steps.In this PR, we add a new
EncodedSize
trait which accomplishes this objective, and implement that for all types. Implementations for custom structs and enums can be derived using#[derive(bincode::EncodedSize)]
.