]> mj.ucw.cz Git - libucw.git/blob - ucw/respool.c
More work on resource pools.
[libucw.git] / ucw / respool.c
1 /*
2  *      The UCW Library -- Resource Pools
3  *
4  *      (c) 2008 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "ucw/lib.h"
11 #include "ucw/respool.h"
12 #include "ucw/mempool.h"
13
14 #include <stdio.h>
15
16 struct respool *
17 rp_new(const char *name, struct mempool *mp)
18 {
19   struct respool *rp;
20
21   if (mp)
22     {
23       rp = mp_alloc_zero(mp, sizeof(*rp));
24       rp->mpool = mp;
25     }
26   else
27     rp = xmalloc_zero(sizeof(*rp));
28   clist_init(&rp->resources);
29   rp->name = name;
30   return rp;
31 }
32
33 void
34 rp_delete(struct respool *rp)
35 {
36   struct resource *r;
37   while (r = clist_tail(&rp->resources))
38     res_free(r);
39   if (!rp->mpool)
40     xfree(rp);
41 }
42
43 void
44 rp_dump(struct respool *rp)
45 {
46   printf("Resource pool %s at %p (%s):\n", (rp->name ? : "(noname)"), rp, (rp->mpool ? "mempool-based" : "freestanding"));
47   CLIST_FOR_EACH(struct resource *, r, rp->resources)
48     res_dump(r);
49 }
50
51 struct resource *
52 res_alloc(void)
53 {
54   struct respool *rp = rp_current();
55   if (!rp)
56     return NULL;
57
58   struct resource *r = (rp->mpool ? mp_alloc_fast(rp->mpool, sizeof(*r)) : xmalloc(sizeof(*r)));
59   clist_add_tail(&rp->resources, &r->n);
60   return r;
61 }
62
63 static inline void
64 res_do_free(struct resource *r)
65 {
66   clist_remove(&r->n);
67   if (!r->rpool->mpool)
68     xfree(r);
69 }
70
71 void
72 res_detach(struct resource *r)
73 {
74   if (r->rclass->detach)
75     r->rclass->detach(r);
76   res_do_free(r);
77 }
78
79 void
80 res_free(struct resource *r)
81 {
82   if (r->rclass->free)
83     r->rclass->free(r);
84   res_do_free(r);
85 }
86
87 void
88 res_dump(struct resource *r)
89 {
90   printf("\t%p %s", r, r->rclass->name);
91   if (r->rclass->dump)
92     r->rclass->dump(r);
93   putchar('\n');
94 }
95
96 #ifdef TEST
97
98 int main(void)
99 {
100   struct respool *rp = rp_new("test", NULL);
101   rp_dump(rp);
102   return 0;
103 }
104
105 #endif