2 * UCW Library -- A simple growing array of an arbitrary type
4 * (c) 2010--2014 Martin Mares <mj@ucw.cz>
15 gary_init(size_t elt_size, size_t num_elts, struct gary_allocator *allocator)
17 DBG("GARY: Init to %zd elements", num_elts);
18 struct gary_hdr *h = allocator->alloc(allocator, GARY_HDR_SIZE + elt_size * num_elts);
19 h->num_elts = h->have_space = num_elts;
20 h->elt_size = elt_size;
21 h->allocator = allocator;
25 static struct gary_hdr *
26 gary_realloc(struct gary_hdr *h, size_t n)
28 size_t old_size = h->have_space;
29 if (n > 2*h->have_space)
33 DBG("GARY: Resize from %zd to %zd elements (need %zd)", old_size, h->have_space, n);
34 return h->allocator->realloc(h->allocator, h, GARY_HDR_SIZE + old_size * h->elt_size, GARY_HDR_SIZE + h->have_space * h->elt_size);
38 gary_set_size(void *array, size_t n)
40 struct gary_hdr *h = GARY_HDR(array);
42 if (n <= h->have_space)
45 h = gary_realloc(h, n);
50 gary_push_helper(void *array, size_t n, byte **cptr)
52 struct gary_hdr *h = GARY_HDR(array);
53 h = gary_realloc(h, h->num_elts);
54 *cptr = GARY_BODY(h) + (h->num_elts - n) * h->elt_size;
61 struct gary_hdr *h = GARY_HDR(array);
62 if (h->num_elts != h->have_space)
64 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);
65 h->have_space = h->num_elts;
70 /* Default allocator */
72 static void *gary_default_alloc(struct gary_allocator *a UNUSED, size_t size)
77 static void *gary_default_realloc(struct gary_allocator *a UNUSED, void *ptr, size_t old_size UNUSED, size_t new_size)
79 return xrealloc(ptr, new_size);
82 static void gary_default_free(struct gary_allocator *a UNUSED, void *ptr)
87 struct gary_allocator gary_allocator_default = {
88 .alloc = gary_default_alloc,
89 .realloc = gary_default_realloc,
90 .free = gary_default_free,
93 /* Zeroing allocator */
95 static void *gary_zeroed_alloc(struct gary_allocator *a UNUSED, size_t size)
97 return xmalloc_zero(size);
100 static void *gary_zeroed_realloc(struct gary_allocator *a UNUSED, void *ptr, size_t old_size, size_t new_size)
102 ptr = xrealloc(ptr, new_size);
103 if (old_size < new_size)
104 bzero((byte *) ptr + old_size, new_size - old_size);
108 struct gary_allocator gary_allocator_zeroed = {
109 .alloc = gary_zeroed_alloc,
110 .realloc = gary_zeroed_realloc,
111 .free = gary_default_free,
121 GARY_INIT_ZERO(a, 5);
123 for (int i=0; i<5; i++)
136 for (int i=0; i<(int)GARY_SIZE(a); i++)
137 printf("%d\n", a[i]);