Blame src/varint.c

Packit Service 20376f
/*
Packit Service 20376f
 * Copyright (C) the libgit2 contributors. All rights reserved.
Packit Service 20376f
 *
Packit Service 20376f
 * This file is part of libgit2, distributed under the GNU GPL v2 with
Packit Service 20376f
 * a Linking Exception. For full terms see the included COPYING file.
Packit Service 20376f
 */
Packit Service 20376f
Packit Service 20376f
#include "common.h"
Packit Service 20376f
#include "varint.h"
Packit Service 20376f
Packit Service 20376f
uintmax_t git_decode_varint(const unsigned char *bufp, size_t *varint_len)
Packit Service 20376f
{
Packit Service 20376f
	const unsigned char *buf = bufp;
Packit Service 20376f
	unsigned char c = *buf++;
Packit Service 20376f
	uintmax_t val = c & 127;
Packit Service 20376f
	while (c & 128) {
Packit Service 20376f
		val += 1;
Packit Service 20376f
		if (!val || MSB(val, 7)) {
Packit Service 20376f
			/* This is not a valid varint_len, so it signals
Packit Service 20376f
			   the error */
Packit Service 20376f
			*varint_len = 0;
Packit Service 20376f
			return 0; /* overflow */
Packit Service 20376f
		}
Packit Service 20376f
		c = *buf++;
Packit Service 20376f
		val = (val << 7) + (c & 127);
Packit Service 20376f
	}
Packit Service 20376f
	*varint_len = buf - bufp;
Packit Service 20376f
	return val;
Packit Service 20376f
}
Packit Service 20376f
Packit Service 20376f
int git_encode_varint(unsigned char *buf, size_t bufsize, uintmax_t value)
Packit Service 20376f
{
Packit Service 20376f
	unsigned char varint[16];
Packit Service 20376f
	unsigned pos = sizeof(varint) - 1;
Packit Service 20376f
	varint[pos] = value & 127;
Packit Service 20376f
	while (value >>= 7)
Packit Service 20376f
		varint[--pos] = 128 | (--value & 127);
Packit Service 20376f
	if (buf) {
Packit Service 20376f
		if (bufsize < (sizeof(varint) - pos))
Packit Service 20376f
			return -1;
Packit Service 20376f
		memcpy(buf, varint + pos, sizeof(varint) - pos);
Packit Service 20376f
	}
Packit Service 20376f
	return sizeof(varint) - pos;
Packit Service 20376f
}