2 * The UCW Library -- Resource Pools
4 * (c) 2008--2011 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include "ucw/respool.h"
12 #include "ucw/mempool.h"
17 rp_new(const char *name, struct mempool *mp)
23 rp = mp_alloc_zero(mp, sizeof(*rp));
27 rp = xmalloc_zero(sizeof(*rp));
28 clist_init(&rp->resources);
30 rp->default_res_flags = RES_FLAG_TEMP;
35 rp_free(struct respool *rp)
38 res_detach(rp->subpool_of);
41 if (rp_current() == rp)
46 rp_delete(struct respool *rp)
49 while (r = clist_tail(&rp->resources))
51 ASSERT(r->rpool == rp);
58 rp_detach(struct respool *rp)
61 while (r = clist_head(&rp->resources))
63 ASSERT(r->rpool == rp);
70 rp_commit(struct respool *rp)
73 while (r = clist_head(&rp->resources))
75 ASSERT(r->rpool == rp);
76 if (r->flags & RES_FLAG_TEMP)
85 rp_dump(struct respool *rp, uns indent)
87 printf("%*sResource pool %s at %p (%s)%s:\n",
89 (rp->name ? : "(noname)"),
91 (rp->mpool ? "mempool-based" : "freestanding"),
92 (rp->subpool_of ? " (subpool)" : "")
94 CLIST_FOR_EACH(struct resource *, r, rp->resources)
95 res_dump(r, indent+4);
99 res_alloc(const struct res_class *rc)
101 struct respool *rp = rp_current();
105 uns size = (rc->res_size ? : sizeof(struct resource));
106 struct resource *r = (rp->mpool ? mp_alloc_fast(rp->mpool, size) : xmalloc(size));
108 clist_add_tail(&rp->resources, &r->n);
109 r->flags = rp->default_res_flags;
114 res_drop(struct resource *r)
117 if (!r->rpool->mpool)
122 res_detach(struct resource *r)
126 if (r->rclass->detach)
127 r->rclass->detach(r);
132 res_free(struct resource *r)
142 res_dump(struct resource *r, uns indent)
144 printf("%*s%p %s %s", indent, "", r, ((r->flags & RES_FLAG_TEMP) ? "TEMP" : "PERM"), r->rclass->name);
146 r->rclass->dump(r, indent+4);
153 #include "ucw/fastbuf.h"
157 // struct mempool *mp = mp_new(4096);
158 struct respool *rp = rp_new("test", NULL);
160 struct fastbuf *f = bfdopen_shared(1, 0);
162 bputsn(f, "Hello, all worlds!");