]> mj.ucw.cz Git - libucw.git/blob - ucw/gary.c
Gary: GARY_PUSH and GARY_POP have lost the 2nd argument
[libucw.git] / ucw / gary.c
1 /*
2  *      UCW Library -- A simple growing array of an arbitrary type
3  *
4  *      (c) 2010--2012 Martin Mares <mj@ucw.cz>
5  */
6
7 #undef LOCAL_DEBUG
8
9 #include <ucw/lib.h>
10 #include <ucw/gary.h>
11
12 #include <string.h>
13
14 void *
15 gary_init(size_t elt_size, size_t num_elts, int zeroed)
16 {
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;
21   h->zeroed = zeroed;
22   if (zeroed)
23     bzero(GARY_BODY(h), elt_size * num_elts);
24   return GARY_BODY(h);
25 }
26
27 static struct gary_hdr *
28 gary_realloc(struct gary_hdr *h, size_t n)
29 {
30   size_t old_size = h->have_space;
31   if (n > 2*h->have_space)
32     h->have_space = n;
33   else
34     h->have_space *= 2;
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);
37   if (h->zeroed)
38     bzero(GARY_BODY(h) + h->elt_size * old_size, h->elt_size * (h->have_space - old_size));
39   return h;
40 }
41
42 void *
43 gary_set_size(void *array, size_t n)
44 {
45   struct gary_hdr *h = GARY_HDR(array);
46   h->num_elts = n;
47   if (n <= h->have_space)
48     return array;
49
50   h = gary_realloc(h, n);
51   return GARY_BODY(h);
52 }
53
54 void *
55 gary_push_helper(void *array, size_t n, byte **cptr)
56 {
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;
60   return GARY_BODY(h);
61 }
62
63 void *
64 gary_fix(void *array)
65 {
66   struct gary_hdr *h = GARY_HDR(array);
67   if (h->num_elts != h->have_space)
68     {
69       h = xrealloc(h, GARY_HDR_SIZE + h->num_elts * h->elt_size);
70       h->have_space = h->num_elts;
71     }
72   return GARY_BODY(h);
73 }
74
75 #ifdef TEST
76
77 #include <stdio.h>
78
79 int main(void)
80 {
81   int *a;
82   GARY_INIT_ZERO(a, 5);
83
84   for (int i=0; i<5; i++)
85     {
86       ASSERT(!a[i]);
87       a[i] = i+1;
88     }
89
90   GARY_PUSH(a);
91   *GARY_PUSH(a) = 10;
92   *GARY_PUSH(a) = 20;
93   *GARY_PUSH(a) = 30;
94   GARY_POP(a);
95   GARY_FIX(a);
96
97   for (int i=0; i<(int)GARY_SIZE(a); i++)
98     printf("%d\n", a[i]);
99
100   GARY_FREE(a);
101   return 0;
102 }
103
104 #endif