]> mj.ucw.cz Git - libucw.git/blob - ucw/respool.h
Resources for file descriptors and memory blocks.
[libucw.git] / ucw / respool.h
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 /*
11  * FIXME:
12  *      - check other candidates for resourcification
13  *      - respool as a resource in another respool?
14  *      - unit tests
15  */
16
17 #ifndef _UCW_RESPOOL_H
18 #define _UCW_RESPOOL_H
19
20 #include "ucw/clists.h"
21 #include "ucw/threads.h"
22
23 struct respool {
24   clist resources;
25   const char *name;
26   struct mempool *mpool;                                // If set, resources are allocated from the mempool, otherwise by xmalloc()
27 };
28
29 struct resource {
30   cnode n;
31   struct respool *rpool;
32   const struct res_class *rclass;
33   void *priv;                                           // Private to the class
34 };
35
36 struct res_class {
37   const char *name;
38   void (*detach)(struct resource *r);
39   void (*free)(struct resource *r);
40   void (*dump)(struct resource *r);
41   uns res_size;                                         // Size of the resource structure (0=default)
42 };
43
44 struct respool *rp_new(const char *name, struct mempool *mp);
45 void rp_delete(struct respool *rp);
46 void rp_dump(struct respool *rp);
47
48 static inline struct respool *
49 rp_current(void)
50 {
51   return ucwlib_thread_context()->current_respool;      // May be NULL
52 }
53
54 static inline struct respool *
55 rp_switch(struct respool *rp)
56 {
57   struct ucwlib_context *ctx = ucwlib_thread_context();
58   struct respool *orp = ctx->current_respool;
59   ctx->current_respool = rp;
60   return orp;
61 }
62
63 struct resource *res_alloc(const struct res_class *rc); // Returns NULL if there is no pool active
64 void res_drop(struct resource *r);
65 void res_detach(struct resource *r);
66 void res_free(struct resource *r);
67 void res_dump(struct resource *r);
68
69 static inline struct resource *                         // Returns NULL if there is no pool active
70 res_new(const struct res_class *rc, void *priv)
71 {
72   struct resource *r = res_alloc(rc);
73   if (r)
74     {
75       r->rclass = rc;
76       r->priv = priv;
77     }
78   return r;
79 }
80
81 /* Various special types of resources */
82
83 struct resource *res_for_fd(int fd);                    // Creates a resource that closes a given file descriptor
84
85 void *res_malloc(size_t size, struct resource **ptr);   // Allocates memory and creates a resource for it
86 void *res_malloc_zero(size_t size, struct resource **ptr);      // Allocates zero-initialized memory and creates a resource for it
87 void *res_realloc(struct resource *res, size_t size);
88
89 #endif