2 * UCW Library -- A simple growing array of an arbitrary type
4 * (c) 2010--2012 Martin Mares <mj@ucw.cz>
15 gary_init(size_t elt_size, size_t num_elts, int zeroed)
17 DBG("GARY: Init to %zd elements", num_elts);
18 struct gary_hdr *h = xmalloc(GARY_HDR_SIZE + elt_size * num_elts);
19 h->num_elts = h->have_space = num_elts;
20 h->elt_size = elt_size;
23 bzero(GARY_BODY(h), elt_size * num_elts);
28 gary_free(void *array)
30 xfree(GARY_HDR(array));
33 static struct gary_hdr *
34 gary_realloc(struct gary_hdr *h, size_t n)
36 size_t old_size = h->have_space;
37 if (n > 2*h->have_space)
41 DBG("GARY: Resize from %zd to %zd elements (need %zd)", old_size, h->have_space, n);
42 h = xrealloc(h, GARY_HDR_SIZE + h->have_space * h->elt_size);
44 bzero(GARY_BODY(h) + h->elt_size * old_size, h->elt_size * (h->have_space - old_size));
49 gary_set_size(void *array, size_t n)
51 struct gary_hdr *h = GARY_HDR(array);
53 if (n <= h->have_space)
56 h = gary_realloc(h, n);
61 gary_push_helper(void *array, size_t n, byte **cptr)
63 struct gary_hdr *h = GARY_HDR(array);
64 h = gary_realloc(h, h->num_elts);
65 *cptr = GARY_BODY(h) + (h->num_elts - n) * h->elt_size;
72 struct gary_hdr *h = GARY_HDR(array);
73 if (h->num_elts != h->have_space)
75 h = xrealloc(h, GARY_HDR_SIZE + h->num_elts * h->elt_size);
76 h->have_space = h->num_elts;
90 for (int i=0; i<5; i++)
97 *GARY_PUSH(a, 1) = 10;
98 *GARY_PUSH(a, 1) = 20;
99 *GARY_PUSH(a, 1) = 30;
103 for (int i=0; i<(int)GARY_SIZE(a); i++)
104 printf("%d\n", a[i]);