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);
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 h = xrealloc(h, GARY_HDR_SIZE + h->have_space * h->elt_size);
38 bzero(GARY_BODY(h) + h->elt_size * old_size, h->elt_size * (h->have_space - old_size));
43 gary_set_size(void *array, size_t n)
45 struct gary_hdr *h = GARY_HDR(array);
47 if (n <= h->have_space)
50 h = gary_realloc(h, n);
55 gary_push_helper(void *array, size_t n, byte **cptr)
57 struct gary_hdr *h = GARY_HDR(array);
58 h = gary_realloc(h, h->num_elts);
59 *cptr = GARY_BODY(h) + (h->num_elts - n) * h->elt_size;
66 struct gary_hdr *h = GARY_HDR(array);
67 if (h->num_elts != h->have_space)
69 h = xrealloc(h, GARY_HDR_SIZE + h->num_elts * h->elt_size);
70 h->have_space = h->num_elts;
84 for (int i=0; i<5; i++)
91 *GARY_PUSH(a, 1) = 10;
92 *GARY_PUSH(a, 1) = 20;
93 *GARY_PUSH(a, 1) = 30;
97 for (int i=0; i<(int)GARY_SIZE(a); i++)