MINOR: lua: simplify hlua_alloc() to only rely on realloc()

The function really has the semantics of a realloc() except that it
also passes the old size to help with accounting. No need to special
case the free or malloc, realloc does everything we need.
This commit is contained in:
Willy Tarreau 2020-12-02 12:26:29 +01:00
parent fdabf49548
commit d36c7fa5ec

View File

@ -8229,37 +8229,22 @@ int hlua_post_init()
/* The memory allocator used by the Lua stack. <ud> is a pointer to the /* The memory allocator used by the Lua stack. <ud> is a pointer to the
* allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize> * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
* is the previously allocated size or the kind of object in case of a new * is the previously allocated size or the kind of object in case of a new
* allocation. <nsize> is the requested new size. * allocation. <nsize> is the requested new size. A new allocation is
* indicated by <ptr> being NULL. A free is indicated by <nsize> being
* zero.
*/ */
static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize) static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
{ {
struct hlua_mem_allocator *zone = ud; struct hlua_mem_allocator *zone = ud;
if (nsize == 0) { if (!ptr)
/* it's a free */ osize = 0;
if (ptr)
zone->allocated -= osize;
free(ptr);
return NULL;
}
if (!ptr) {
/* it's a new allocation */
if (zone->limit && zone->allocated + nsize > zone->limit)
return NULL;
ptr = malloc(nsize);
if (ptr)
zone->allocated += nsize;
return ptr;
}
/* it's a realloc */
if (zone->limit && zone->allocated + nsize - osize > zone->limit) if (zone->limit && zone->allocated + nsize - osize > zone->limit)
return NULL; return NULL;
ptr = realloc(ptr, nsize); ptr = realloc(ptr, nsize);
if (ptr) if (ptr || !nsize)
zone->allocated += nsize - osize; zone->allocated += nsize - osize;
return ptr; return ptr;
} }