Skip to content

Commit d2c1898

Browse files
committed
varint: make it available outside the context of pack
Signed-off-by: Junio C Hamano <[email protected]>
1 parent e5056c0 commit d2c1898

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,7 @@ LIB_H += tree-walk.h
627627
LIB_H += unpack-trees.h
628628
LIB_H += userdiff.h
629629
LIB_H += utf8.h
630+
LIB_H += varint.h
630631
LIB_H += xdiff-interface.h
631632
LIB_H += xdiff/xdiff.h
632633

@@ -752,6 +753,7 @@ LIB_OBJS += url.o
752753
LIB_OBJS += usage.o
753754
LIB_OBJS += userdiff.o
754755
LIB_OBJS += utf8.o
756+
LIB_OBJS += varint.o
755757
LIB_OBJS += walker.o
756758
LIB_OBJS += wrapper.o
757759
LIB_OBJS += write_or_die.o

varint.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include "varint.h"
2+
3+
uintmax_t decode_varint(const unsigned char **bufp)
4+
{
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);
14+
}
15+
*bufp = buf;
16+
return val;
17+
}
18+
19+
int encode_varint(uintmax_t value, unsigned char *buf)
20+
{
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;
29+
}

varint.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#ifndef VARINT_H
2+
#define VARINT_H
3+
4+
#include "git-compat-util.h"
5+
6+
extern int encode_varint(uintmax_t, unsigned char *);
7+
extern uintmax_t decode_varint(const unsigned char **);
8+
9+
#endif /* VARINT_H */

0 commit comments

Comments
 (0)