update stack_allocator to support 0 size allocations

This commit is contained in:
Mokhtar Naamani 2016-11-17 14:32:25 +02:00 committed by Arvid Norberg
parent c1224f72c3
commit f81e09fe05
2 changed files with 20 additions and 2 deletions

View File

@ -62,6 +62,7 @@ namespace libtorrent { namespace aux
int copy_buffer(char const* buf, int size)
{
int ret = int(m_storage.size());
if (size < 1) return -1;
m_storage.resize(ret + size);
memcpy(&m_storage[ret], buf, size);
return ret;
@ -69,6 +70,7 @@ namespace libtorrent { namespace aux
int allocate(int bytes)
{
if (bytes < 1) return -1;
int ret = int(m_storage.size());
m_storage.resize(ret + bytes);
return ret;
@ -76,14 +78,14 @@ namespace libtorrent { namespace aux
char* ptr(int idx)
{
TORRENT_ASSERT(idx >= 0);
if(idx < 0) return NULL;
TORRENT_ASSERT(idx < int(m_storage.size()));
return &m_storage[idx];
}
char const* ptr(int idx) const
{
TORRENT_ASSERT(idx >= 0);
if(idx < 0) return NULL;
TORRENT_ASSERT(idx < int(m_storage.size()));
return &m_storage[idx];
}

View File

@ -59,6 +59,14 @@ TORRENT_TEST(copy_buffer)
a.allocate(100000);
TEST_CHECK(strcmp(a.ptr(idx1), "testing") == 0);
// attempt zero size allocation
int const idx2 = a.copy_buffer("nothing", 0);
TEST_CHECK(idx2 == -1);
// attempt to get a pointer after zero allocation
char* ptr = a.ptr(idx2);
TEST_CHECK(ptr == NULL);
}
TORRENT_TEST(allocate)
@ -75,6 +83,14 @@ TORRENT_TEST(allocate)
ptr = a.ptr(idx1);
for (int i = 0; i < 100; ++i)
TEST_CHECK(ptr[i] == char(i % 256));
// attempt zero size allocation
int const idx2 = a.allocate(0);
TEST_CHECK(idx2 == -1);
// attempt to get a pointer after zero allocation
ptr = a.ptr(idx2);
TEST_CHECK(ptr == NULL);
}
TORRENT_TEST(swap)