]> mj.ucw.cz Git - libucw.git/blob - ucw/gary-mp.c
Opt: User-defined types are specified as CT_USER, not OPT_CL_USER
[libucw.git] / ucw / gary-mp.c
1 /*
2  *      UCW Library -- Growing arrays over mempools
3  *
4  *      (c) 2014 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <ucw/lib.h>
8 #include <ucw/gary.h>
9 #include <ucw/mempool.h>
10
11 #include <string.h>
12
13 static void *gary_mp_alloc(struct gary_allocator *a, size_t size)
14 {
15   return mp_alloc(a->data, size);
16 }
17
18 static void *gary_mp_realloc(struct gary_allocator *a, void *ptr, size_t old_size, size_t new_size)
19 {
20   if (new_size <= old_size)
21     return ptr;
22
23   /*
24    *  In the future, we might want to do something like mp_realloc(),
25    *  but we have to check that it is indeed the last block in the pool.
26    */
27   void *new = mp_alloc(a->data, new_size);
28   memcpy(new, ptr, old_size);
29   return new;
30 }
31
32 static void gary_mp_free(struct gary_allocator *a UNUSED, void *ptr UNUSED)
33 {
34 }
35
36 struct gary_allocator *gary_new_allocator_mp(struct mempool *mp)
37 {
38   struct gary_allocator *a = mp_alloc(mp, sizeof(*a));
39   *a = (struct gary_allocator) {
40     .alloc = gary_mp_alloc,
41     .realloc = gary_mp_realloc,
42     .free = gary_mp_free,
43     .data = mp,
44   };
45   return a;
46 }
47
48 #ifdef TEST
49
50 #include <stdio.h>
51
52 int main(void)
53 {
54   struct mempool *mp = mp_new(4096);
55   struct gary_allocator *alloc = gary_new_allocator_mp(mp);
56   int *a;
57   GARY_INIT_ALLOC(a, 5, alloc);
58
59   for (int i=0; i<5; i++)
60     a[i] = i+1;
61
62   GARY_PUSH(a);
63   *GARY_PUSH(a) = 10;
64   *GARY_PUSH(a) = 20;
65   *GARY_PUSH(a) = 30;
66   GARY_POP(a);
67   GARY_FIX(a);
68
69   for (int i=0; i<(int)GARY_SIZE(a); i++)
70     printf("%d\n", a[i]);
71
72   GARY_FREE(a);
73   mp_delete(mp);
74   return 0;
75 }
76
77 #endif