view src/lib/numpack.c @ 18137:3009a1a6f6d5

global: freshen copyright Robomatically: git ls-files | xargs perl -p -i -e 's/(\d+)-201[0-4]/$1-2015/g;s/ (201[0-4]) Dovecot/ $1-2015 Dovecot/' Happy 2015 everyone! Signed-off-by: Phil Carmody <phil@dovecot.fi>
author Phil Carmody <phil@dovecot.fi>
date Mon, 05 Jan 2015 22:20:10 +0200
parents 1c276f2e59a5
children 1c275f718758
line wrap: on
line source

/* Copyright (c) 2013-2015 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "buffer.h"
#include "numpack.h"

void numpack_encode(buffer_t *buf, uint64_t num)
{
	/* number continues as long as the highest bit is set */
	while (num >= 0x80) {
		buffer_append_c(buf, (num & 0x7f) | 0x80);
		num >>= 7;
	}

	buffer_append_c(buf, num);
}

int numpack_decode(const uint8_t **p, const uint8_t *end, uint64_t *num_r)
{
	const uint8_t *c = *p;
	uint64_t value = 0;
	unsigned int bits = 0;

	while (bits < 64) {
		if (c == end)
			return -1;

		value |= (uint64_t)(*c & 0x7f) << bits;
		if (*c < 0x80)
			break;

		bits += 7;
		c++;
	}

	bits += bits_required8(*c);
	if (bits > 64) /* overflow */
		return -1;

	*p = c + 1;
	*num_r = value;
	return 0;
}