Add some helpers for resizing dynamic arrays to allow them to both not grow if they're at capacity or shrink if significantly below capacity.

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@3902 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
2022-06-17 21:18:10 +00:00
parent 4e3bf99327
commit e1ca715c64
4 changed files with 38 additions and 5 deletions

View File

@ -154,6 +154,32 @@ char* tf_strdup(const char* string)
return buffer;
}
void* tf_resize_vec(void* ptr, size_t size)
{
void* alloc_ptr = ptr ? (void*)((intptr_t)ptr - sizeof(size_t)) : NULL;
size_t alloc_size = 0;
if (alloc_ptr)
{
memcpy(&alloc_size, alloc_ptr, sizeof(size_t));
}
if (alloc_size >= 16 * size + sizeof(size_t))
{
/* If we've dropped significantly in size, resize down. */
return tf_realloc(ptr, size);
}
else if (alloc_size >= size + sizeof(size_t))
{
/* Otherwise, if we're big enough, stay the same size. */
return ptr;
}
else
{
/* If we need to grow, overallocate 2x to give room to continue growing. */
return tf_realloc(ptr, size * 2);
}
}
size_t tf_mem_get_tf_malloc_size()
{
return s_tf_malloc_size;