Skip to content

Commit

Permalink
Make cs_varint_decode only return valid data
Browse files Browse the repository at this point in the history
PUBLISHED_FROM=726d015857ed29cec877e5bc82041f75db3e02bf
  • Loading branch information
Deomid Ryabkov authored and cesantabot committed Feb 8, 2018
1 parent 8c2428f commit 30aa0f8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
9 changes: 6 additions & 3 deletions common/cs_varint.c
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,26 @@ size_t cs_varint_encode(uint64_t num, uint8_t *buf, size_t buf_size) {
bool cs_varint_decode(const uint8_t *buf, size_t buf_size, uint64_t *num,
size_t *llen) {
size_t i = 0, shift = 0;
*num = 0;
uint64_t n = 0;

do {
if (i == buf_size || i == (8 * sizeof(*num) / 7 + 1)) return false;
/*
* Each byte of varint contains 7 bits, in little endian order.
* MSB is a continuation bit: it tells whether next byte is used.
*/
*num |= ((uint64_t)(buf[i] & 0x7f)) << shift;
n |= ((uint64_t)(buf[i] & 0x7f)) << shift;
/*
* First we increment i, then check whether it is within boundary and
* whether decoded byte had continuation bit set.
*/
*llen = ++i;
i++;
shift += 7;
} while (shift < sizeof(uint64_t) * 8 && (buf[i - 1] & 0x80));

*num = n;
*llen = i;

return true;
}

Expand Down
9 changes: 6 additions & 3 deletions mjs.c
Original file line number Diff line number Diff line change
Expand Up @@ -4877,23 +4877,26 @@ size_t cs_varint_encode(uint64_t num, uint8_t *buf, size_t buf_size) {
bool cs_varint_decode(const uint8_t *buf, size_t buf_size, uint64_t *num,
size_t *llen) {
size_t i = 0, shift = 0;
*num = 0;
uint64_t n = 0;

do {
if (i == buf_size || i == (8 * sizeof(*num) / 7 + 1)) return false;
/*
* Each byte of varint contains 7 bits, in little endian order.
* MSB is a continuation bit: it tells whether next byte is used.
*/
*num |= ((uint64_t)(buf[i] & 0x7f)) << shift;
n |= ((uint64_t)(buf[i] & 0x7f)) << shift;
/*
* First we increment i, then check whether it is within boundary and
* whether decoded byte had continuation bit set.
*/
*llen = ++i;
i++;
shift += 7;
} while (shift < sizeof(uint64_t) * 8 && (buf[i - 1] & 0x80));

*num = n;
*llen = i;

return true;
}

Expand Down

0 comments on commit 30aa0f8

Please sign in to comment.