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/resource.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();
104 uns size = (rc->res_size ? : sizeof(struct resource));
105 struct resource *r = (rp->mpool ? mp_alloc_fast(rp->mpool, size) : xmalloc(size));
107 clist_add_tail(&rp->resources, &r->n);
108 r->flags = rp->default_res_flags;
113 res_drop(struct resource *r)
116 if (!r->rpool->mpool)
121 res_detach(struct resource *r)
125 if (r->rclass->detach)
126 r->rclass->detach(r);
131 res_free(struct resource *r)
141 res_dump(struct resource *r, uns indent)
143 printf("%*s%p %s %s", indent, "", r, ((r->flags & RES_FLAG_TEMP) ? "TEMP" : "PERM"), r->rclass->name);
145 r->rclass->dump(r, indent+4);
152 #include <ucw/fastbuf.h>
156 // struct mempool *mp = mp_new(4096);
157 struct respool *rp = rp_new("test", NULL);
159 struct fastbuf *f = bfdopen_shared(1, 0);
161 bputsn(f, "Hello, all worlds!");