2 * UCW Library -- A simple growing array of an arbitrary type
4 * (c) 2010--2014 Martin Mares <mj@ucw.cz>
14 struct gary_hdr gary_empty_hdr;
17 gary_init(size_t elt_size, size_t num_elts, struct ucw_allocator *allocator)
19 DBG("GARY: Init to %zd elements", num_elts);
20 struct gary_hdr *h = allocator->alloc(allocator, GARY_HDR_SIZE + elt_size * num_elts);
21 h->num_elts = h->have_space = num_elts;
22 h->elt_size = elt_size;
23 h->allocator = allocator;
27 static struct gary_hdr *
28 gary_realloc(struct gary_hdr *h, size_t n)
30 size_t old_size = h->have_space;
31 if (n > 2*h->have_space)
35 DBG("GARY: Resize from %zd to %zd elements (need %zd)", old_size, h->have_space, n);
36 return h->allocator->realloc(h->allocator, h, GARY_HDR_SIZE + old_size * h->elt_size, GARY_HDR_SIZE + h->have_space * h->elt_size);
40 gary_set_size(void *array, size_t n)
42 struct gary_hdr *h = GARY_HDR(array);
44 if (n <= h->have_space)
47 h = gary_realloc(h, n);
52 gary_push_helper(void *array, size_t n, byte **cptr)
54 struct gary_hdr *h = GARY_HDR(array);
55 h = gary_realloc(h, h->num_elts);
56 *cptr = GARY_BODY(h) + (h->num_elts - n) * h->elt_size;
63 struct gary_hdr *h = GARY_HDR(array);
64 if (h->num_elts != h->have_space)
66 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);
67 h->have_space = h->num_elts;
74 #include <ucw/mempool.h>
78 int main(int argc, char **argv UNUSED)
81 struct mempool *mp = NULL;
88 GARY_INIT_ALLOC(a, 5, mp_get_allocator(mp));
91 for (int i=0; i<5; i++)
104 for (int i=0; i<(int)GARY_SIZE(a); i++)
105 printf("%d\n", a[i]);