mirror of
https://github.com/git/git.git
synced 2025-12-05 18:47:16 -06:00
The varint subsystem currently uses implicit widths for integers. On the one hand we use `uintmax_t` for the actual value. On the other hand, we use `int` for the length of the encoded varint. Both of these have known maximum values, as we only support at most 16 bytes when encoding varints. Thus, we know that we won't ever exceed `uint64_t` for the actual value and `uint8_t` for the prefix length. Refactor the code to use explicit widths. Besides making the logic platform-independent, it also makes our life a bit easier in the next commit, where we reimplement "varint.c" in Rust. Suggested-by: Ezekiel Newren <ezekielnewren@gmail.com> Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>
31 lines
661 B
C
31 lines
661 B
C
#include "git-compat-util.h"
|
|
#include "varint.h"
|
|
|
|
uint64_t decode_varint(const unsigned char **bufp)
|
|
{
|
|
const unsigned char *buf = *bufp;
|
|
unsigned char c = *buf++;
|
|
uint64_t val = c & 127;
|
|
while (c & 128) {
|
|
val += 1;
|
|
if (!val || MSB(val, 7))
|
|
return 0; /* overflow */
|
|
c = *buf++;
|
|
val = (val << 7) + (c & 127);
|
|
}
|
|
*bufp = buf;
|
|
return val;
|
|
}
|
|
|
|
uint8_t encode_varint(uint64_t value, unsigned char *buf)
|
|
{
|
|
unsigned char varint[16];
|
|
unsigned pos = sizeof(varint) - 1;
|
|
varint[pos] = value & 127;
|
|
while (value >>= 7)
|
|
varint[--pos] = 128 | (--value & 127);
|
|
if (buf)
|
|
memcpy(buf, varint + pos, sizeof(varint) - pos);
|
|
return sizeof(varint) - pos;
|
|
}
|