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, uint 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();
103 uint size = (rc->res_size ? : sizeof(struct resource));
107 r = mp_alloc_fast(rp->mpool, size);
113 r->flags = RES_FLAG_XFREE;
120 res_add(struct resource *r)
122 struct respool *rp = rp_current();
125 clist_add_tail(&rp->resources, &r->n);
126 r->flags &= ~RES_FLAG_TEMP;
127 r->flags |= rp->default_res_flags & RES_FLAG_TEMP;
131 res_drop(struct resource *r)
134 if (r->flags & RES_FLAG_XFREE)
139 res_detach(struct resource *r)
143 if (r->rclass->detach)
144 r->rclass->detach(r);
149 res_free(struct resource *r)
159 res_dump(struct resource *r, uint indent)
161 printf("%*s%p %s %s", indent, "", r, ((r->flags & RES_FLAG_TEMP) ? "TEMP" : "PERM"), r->rclass->name);
163 r->rclass->dump(r, indent+4);
170 #include <ucw/fastbuf.h>
174 // struct mempool *mp = mp_new(4096);
175 struct respool *rp = rp_new("test", NULL);
177 struct fastbuf *f = bfdopen_shared(1, 0);
179 bputsn(f, "Hello, all worlds!");