Revert "Merge branch 'jc/patch-id' into maint-2.46"
[git/gitster.git] / varint.c
blob409c4977a1e3a3a72dcd1452b41abdcb5a42b665
1 #include "git-compat-util.h"
2 #include "varint.h"
4 uintmax_t decode_varint(const unsigned char **bufp)
6 const unsigned char *buf = *bufp;
7 unsigned char c = *buf++;
8 uintmax_t val = c & 127;
9 while (c & 128) {
10 val += 1;
11 if (!val || MSB(val, 7))
12 return 0; /* overflow */
13 c = *buf++;
14 val = (val << 7) + (c & 127);
16 *bufp = buf;
17 return val;
20 int encode_varint(uintmax_t value, unsigned char *buf)
22 unsigned char varint[16];
23 unsigned pos = sizeof(varint) - 1;
24 varint[pos] = value & 127;
25 while (value >>= 7)
26 varint[--pos] = 128 | (--value & 127);
27 if (buf)
28 memcpy(buf, varint + pos, sizeof(varint) - pos);
29 return sizeof(varint) - pos;