diff options
-rw-r--r-- | pb_encode.c | 11 | ||||
-rw-r--r-- | pb_encode.h | 4 | ||||
-rw-r--r-- | tests/encode_unittests/encode_unittests.c | 9 |
3 files changed, 24 insertions, 0 deletions
diff --git a/pb_encode.c b/pb_encode.c index 1eb9473..dc5a273 100644 --- a/pb_encode.c +++ b/pb_encode.c @@ -378,6 +378,17 @@ bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const return pb_encode_submessage(stream, fields, src_struct); } +bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct) +{ + pb_ostream_t stream = PB_OSTREAM_SIZING; + + if (!pb_encode(&stream, fields, src_struct)) + return false; + + *size = stream.bytes_written; + return true; +} + /******************** * Helper functions * ********************/ diff --git a/pb_encode.h b/pb_encode.h index 900994a..f82bac8 100644 --- a/pb_encode.h +++ b/pb_encode.h @@ -71,6 +71,10 @@ bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_ */ bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); +/* Encode the message to get the size of the encoded data, but do not store + * the data. */ +bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct); + /************************************** * Functions for manipulating streams * **************************************/ diff --git a/tests/encode_unittests/encode_unittests.c b/tests/encode_unittests/encode_unittests.c index edbc10a..06935f9 100644 --- a/tests/encode_unittests/encode_unittests.c +++ b/tests/encode_unittests/encode_unittests.c @@ -281,6 +281,15 @@ int main() TEST(WRITES(pb_encode_delimited(&s, IntegerContainer_fields, &msg), "\x09\x0A\x07\x0A\x05\x01\x02\x03\x04\x05")) } + + { + IntegerContainer msg = {{5, {1,2,3,4,5}}}; + size_t size; + + COMMENT("Test pb_get_encoded_size.") + TEST(pb_get_encoded_size(&size, IntegerContainer_fields, &msg) && + size == 9); + } { uint8_t buffer[10]; |