]> mj.ucw.cz Git - libucw.git/blob - lib/eltpool.h
795a45e997dc7957519fd5118ffb852b2ad93b07
[libucw.git] / lib / eltpool.h
1 /*
2  *      UCW Library -- Fast Allocator for Fixed-Size Elements
3  *
4  *      (c) 2007 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 #ifndef _UCW_ELTPOOL_H
11 #define _UCW_ELTPOOL_H
12
13 struct eltpool {
14   struct eltpool_chunk *first_chunk;
15   struct eltpool_free *first_free;
16   uns elt_size;
17   uns chunk_size;
18   uns elts_per_chunk;
19   uns num_allocated;            // Just for debugging
20   uns num_chunks;
21 };
22
23 struct eltpool_chunk {
24   struct eltpool_chunk *next;
25   /* Chunk data continue here */
26 };
27
28 struct eltpool_free {
29   struct eltpool_free *next;
30 };
31
32 struct eltpool *ep_new(uns elt_size, uns elts_per_chunk);
33 void ep_delete(struct eltpool *pool);
34 void *ep_alloc_slow(struct eltpool *pool);
35 u64 ep_total_size(struct eltpool *pool);
36
37 static inline void *
38 ep_alloc(struct eltpool *pool)
39 {
40   pool->num_allocated++;
41 #ifdef CONFIG_FAKE_ELTPOOL
42   return xmalloc(pool->elt_size);
43 #else
44   struct eltpool_free *elt;
45   if (elt = pool->first_free)
46     pool->first_free = elt->next;
47   else
48     elt = ep_alloc_slow(pool);
49   return elt;
50 #endif
51 }
52
53 static inline void
54 ep_free(struct eltpool *pool, void *p)
55 {
56   pool->num_allocated--;
57 #ifdef CONFIG_FAKE_ELTPOOL
58   (void) pool;
59   xfree(p);
60 #else
61   struct eltpool_free *elt = p;
62   elt->next = pool->first_free;
63   pool->first_free = elt;
64 #endif
65 }
66
67 #endif