summaryrefslogtreecommitdiff
path: root/varint.c
diff options
context:
space:
mode:
authorAnas Nashif <anas.nashif@intel.com>2012-11-05 06:38:22 -0800
committerAnas Nashif <anas.nashif@intel.com>2012-11-05 06:38:22 -0800
commit264628a2b3a5cb6c7671ea87ceecab941ec290e9 (patch)
tree1ff25b95990273abc7d5b902baf4ae0c7cbe822a /varint.c
parent189627cd588c2937de7b655595b8ed777f445c85 (diff)
downloadgit-264628a2b3a5cb6c7671ea87ceecab941ec290e9.tar.gz
git-264628a2b3a5cb6c7671ea87ceecab941ec290e9.tar.bz2
git-264628a2b3a5cb6c7671ea87ceecab941ec290e9.zip
Imported Upstream version 1.8.0upstream/1.8.0
Diffstat (limited to 'varint.c')
-rw-r--r--varint.c29
1 files changed, 29 insertions, 0 deletions
diff --git a/varint.c b/varint.c
new file mode 100644
index 00000000..4ed77294
--- /dev/null
+++ b/varint.c
@@ -0,0 +1,29 @@
+#include "varint.h"
+
+uintmax_t decode_varint(const unsigned char **bufp)
+{
+ const unsigned char *buf = *bufp;
+ unsigned char c = *buf++;
+ uintmax_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;
+}
+
+int encode_varint(uintmax_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;
+}