From dcab39a41c0a403db38860c22426075e6ae9f25d Mon Sep 17 00:00:00 2001 From: Petteri Aimonen Date: Thu, 18 Oct 2012 19:45:28 +0300 Subject: Remove the "buf = NULL" => skip requirement from pb_istream_t callbacks. Rationale: it's easy to implement the callback wrong. Doing so introduces io errors when unknown fields are present in the input. If code is not tested with unknown fields, these bugs can remain hidden for long time. Added a special case for the memory buffer stream, where it gives a small speed benefit. Added testcase for skipping fields with test_decode2 implementation. Update issue 37 Status: FixedInGit --- pb_decode.c | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) (limited to 'pb_decode.c') diff --git a/pb_decode.c b/pb_decode.c index 86dec4b..8e01fd7 100644 --- a/pb_decode.c +++ b/pb_decode.c @@ -36,26 +36,41 @@ static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = { * pb_istream * **************/ -bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count) +static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count) { - if (stream->bytes_left < count) - PB_RETURN_ERROR(stream, "end-of-stream"); + uint8_t *source = (uint8_t*)stream->state; - if (!stream->callback(stream, buf, count)) - PB_RETURN_ERROR(stream, "io error"); + if (buf != NULL) + memcpy(buf, source, count); - stream->bytes_left -= count; + stream->state = source + count; return true; } -static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count) +bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count) { - uint8_t *source = (uint8_t*)stream->state; + if (buf == NULL && stream->callback != buf_read) + { + /* Skip input bytes */ + uint8_t tmp[16]; + while (count > 16) + { + if (!pb_read(stream, tmp, 16)) + return false; + + count -= 16; + } + + return pb_read(stream, tmp, count); + } + + if (stream->bytes_left < count) + PB_RETURN_ERROR(stream, "end-of-stream"); - if (buf != NULL) - memcpy(buf, source, count); + if (!stream->callback(stream, buf, count)) + PB_RETURN_ERROR(stream, "io error"); - stream->state = source + count; + stream->bytes_left -= count; return true; } -- cgit 1.2.3-korg