]> mj.ucw.cz Git - libucw.git/blob - ucw/respool.c
Resources for file descriptors and memory blocks.
[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     {
39       ASSERT(r->rpool == rp);
40       res_free(r);
41     }
42   if (!rp->mpool)
43     xfree(rp);
44   if (rp_current() == rp)
45     rp_switch(NULL);
46 }
47
48 void
49 rp_dump(struct respool *rp)
50 {
51   printf("Resource pool %s at %p (%s):\n", (rp->name ? : "(noname)"), rp, (rp->mpool ? "mempool-based" : "freestanding"));
52   CLIST_FOR_EACH(struct resource *, r, rp->resources)
53     res_dump(r);
54 }
55
56 struct resource *
57 res_alloc(const struct res_class *rc)
58 {
59   struct respool *rp = rp_current();
60   if (!rp)
61     return NULL;
62
63   uns size = (rc->res_size ? : sizeof(struct resource));
64   struct resource *r = (rp->mpool ? mp_alloc_fast(rp->mpool, size) : xmalloc(size));
65   r->rpool = rp;
66   clist_add_tail(&rp->resources, &r->n);
67   return r;
68 }
69
70 void
71 res_drop(struct resource *r)
72 {
73   clist_remove(&r->n);
74   if (!r->rpool->mpool)
75     xfree(r);
76 }
77
78 void
79 res_detach(struct resource *r)
80 {
81   if (r->rclass->detach)
82     r->rclass->detach(r);
83   res_drop(r);
84 }
85
86 void
87 res_free(struct resource *r)
88 {
89   if (r->rclass->free)
90     r->rclass->free(r);
91   res_drop(r);
92 }
93
94 void
95 res_dump(struct resource *r)
96 {
97   printf("\t%p %s", r, r->rclass->name);
98   if (r->rclass->dump)
99     r->rclass->dump(r);
100   putchar('\n');
101 }
102
103 #ifdef TEST
104
105 #include "ucw/fastbuf.h"
106
107 int main(void)
108 {
109   // struct mempool *mp = mp_new(4096);
110   struct respool *rp = rp_new("test", NULL);
111   rp_switch(rp);
112   struct fastbuf *f = bfdopen_shared(1, 0);
113   rp_dump(rp);
114   bputsn(f, "Hello, all worlds!");
115   bclose(f);
116   rp_delete(rp);
117   return 0;
118 }
119
120 #endif