Line Flow Count Block(s) Source
1 - /*
2 - * Copyright (C) the libgit2 contributors. All rights reserved.
3 - *
4 - * This file is part of libgit2, distributed under the GNU GPL v2 with
5 - * a Linking Exception. For full terms see the included COPYING file.
6 - */
7 -
8 - #include "varint.h"
9 -
10 21 2 uintmax_t git_decode_varint(const unsigned char *bufp, size_t *varint_len)
11 - {
12 21 2 const unsigned char *buf = bufp;
13 21 2 unsigned char c = *buf++;
14 21 2 uintmax_t val = c & 127;
15 37 2,7 while (c & 128) {
16 17 3 val += 1;
17 17 3,4 if (!val || MSB(val, 7)) {
18 - /* This is not a valid varint_len, so it signals
19 - the error */
20 1 5 *varint_len = 0;
21 1 5 return 0; /* overflow */
22 - }
23 16 6 c = *buf++;
24 16 6 val = (val << 7) + (c & 127);
25 - }
26 20 8 *varint_len = buf - bufp;
27 20 8 return val;
28 - }
29 -
30 1329 2 int git_encode_varint(unsigned char *buf, size_t bufsize, uintmax_t value)
31 - {
32 - unsigned char varint[16];
33 1329 2 unsigned pos = sizeof(varint) - 1;
34 1329 2 varint[pos] = value & 127;
35 1344 2,4 while (value >>= 7)
36 15 3 varint[--pos] = 128 | (--value & 127);
37 1329 5 if (buf) {
38 667 6 if (bufsize < (sizeof(varint) - pos))
39 1 7 return -1;
40 666 8 memcpy(buf, varint + pos, sizeof(varint) - pos);
41 - }
42 1328 9 return sizeof(varint) - pos;
43 - }