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