/*
* UCW Library -- A simple growing array of an arbitrary type
*
- * (c) 2010--2012 Martin Mares <mj@ucw.cz>
+ * (c) 2010--2014 Martin Mares <mj@ucw.cz>
*/
#undef LOCAL_DEBUG
#include <string.h>
+struct gary_hdr gary_empty_hdr;
+
void *
-gary_init(size_t elt_size, size_t num_elts, int zeroed)
+gary_init(size_t elt_size, size_t num_elts, struct ucw_allocator *allocator)
{
DBG("GARY: Init to %zd elements", num_elts);
- struct gary_hdr *h = xmalloc(GARY_HDR_SIZE + elt_size * num_elts);
+ struct gary_hdr *h = allocator->alloc(allocator, GARY_HDR_SIZE + elt_size * num_elts);
h->num_elts = h->have_space = num_elts;
h->elt_size = elt_size;
- h->zeroed = zeroed;
- if (zeroed)
- bzero(GARY_BODY(h), elt_size * num_elts);
+ h->allocator = allocator;
return GARY_BODY(h);
}
else
h->have_space *= 2;
DBG("GARY: Resize from %zd to %zd elements (need %zd)", old_size, h->have_space, n);
- h = xrealloc(h, GARY_HDR_SIZE + h->have_space * h->elt_size);
- if (h->zeroed)
- bzero(GARY_BODY(h) + h->elt_size * old_size, h->elt_size * (h->have_space - old_size));
- return h;
+ return h->allocator->realloc(h->allocator, h, GARY_HDR_SIZE + old_size * h->elt_size, GARY_HDR_SIZE + h->have_space * h->elt_size);
}
void *
struct gary_hdr *h = GARY_HDR(array);
if (h->num_elts != h->have_space)
{
- h = xrealloc(h, GARY_HDR_SIZE + h->num_elts * h->elt_size);
+ h = h->allocator->realloc(h->allocator, h, GARY_HDR_SIZE + h->have_space * h->elt_size, GARY_HDR_SIZE + h->num_elts * h->elt_size);
h->have_space = h->num_elts;
}
return GARY_BODY(h);
#ifdef TEST
+#include <ucw/mempool.h>
+
#include <stdio.h>
-int main(void)
+int main(int argc, char **argv UNUSED)
{
int *a;
- GARY_INIT_ZERO(a, 5);
+ struct mempool *mp = NULL;
+
+ if (argc < 2)
+ GARY_INIT_ZERO(a, 5);
+ else
+ {
+ mp = mp_new(4096);
+ GARY_INIT_ALLOC(a, 5, mp_get_allocator(mp));
+ }
for (int i=0; i<5; i++)
{
- ASSERT(!a[i]);
+ ASSERT(!a[i] || mp);
a[i] = i+1;
}
printf("%d\n", a[i]);
GARY_FREE(a);
+ if (mp)
+ mp_delete(mp);
return 0;
}