Merge branch 'master' of git://git.kernel.org/pub/scm/git/git
[git/jnareb-git.git] / varint.c
blob4ed772949651005055dadd236cee8d5d5c8f2492
1 #include "varint.h"
3 uintmax_t decode_varint(const unsigned char **bufp)
5 const unsigned char *buf = *bufp;
6 unsigned char c = *buf++;
7 uintmax_t val = c & 127;
8 while (c & 128) {
9 val += 1;
10 if (!val || MSB(val, 7))
11 return 0; /* overflow */
12 c = *buf++;
13 val = (val << 7) + (c & 127);
15 *bufp = buf;
16 return val;
19 int encode_varint(uintmax_t value, unsigned char *buf)
21 unsigned char varint[16];
22 unsigned pos = sizeof(varint) - 1;
23 varint[pos] = value & 127;
24 while (value >>= 7)
25 varint[--pos] = 128 | (--value & 127);
26 if (buf)
27 memcpy(buf, varint + pos, sizeof(varint) - pos);
28 return sizeof(varint) - pos;