libgit2/tests/core/encoding.c
Patrick Steinhardt 8a5e7aaecf varint: fix computation for remaining buffer space
When encoding varints to a buffer, we want to remain sure that the
required buffer space does not exceed what is actually available. Our
current check does not do the right thing, though, in that it does not
honor that our `pos` variable counts the position down instead of up. As
such, we will require too much memory for small varints and not enough
memory for big varints.

Fix the issue by correctly calculating the required size as
`(sizeof(varint) - pos)`. Add a test which failed before.
2017-06-06 09:33:53 +02:00

43 lines
1.1 KiB
C

#include "clar_libgit2.h"
#include "varint.h"
void test_core_encoding__decode(void)
{
const unsigned char *buf = (unsigned char *)"AB";
size_t size;
cl_assert(git_decode_varint(buf, &size) == 65);
cl_assert(size == 1);
buf = (unsigned char *)"\xfe\xdc\xbaXY";
cl_assert(git_decode_varint(buf, &size) == 267869656);
cl_assert(size == 4);
buf = (unsigned char *)"\xaa\xaa\xfe\xdc\xbaXY";
cl_assert(git_decode_varint(buf, &size) == 1489279344088ULL);
cl_assert(size == 6);
buf = (unsigned char *)"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xfe\xdc\xbaXY";
cl_assert(git_decode_varint(buf, &size) == 0);
cl_assert(size == 0);
}
void test_core_encoding__encode(void)
{
unsigned char buf[100];
cl_assert(git_encode_varint(buf, 100, 65) == 1);
cl_assert(buf[0] == 'A');
cl_assert(git_encode_varint(buf, 1, 1) == 1);
cl_assert(!memcmp(buf, "\x01", 1));
cl_assert(git_encode_varint(buf, 100, 267869656) == 4);
cl_assert(!memcmp(buf, "\xfe\xdc\xbaX", 4));
cl_assert(git_encode_varint(buf, 100, 1489279344088ULL) == 6);
cl_assert(!memcmp(buf, "\xaa\xaa\xfe\xdc\xbaX", 6));
cl_assert(git_encode_varint(buf, 1, 1489279344088ULL) == -1);
}