]> mj.ucw.cz Git - libucw.git/blob - lib/mempool.h
Unaligned access functions (formerly macros) work in native, big and little endian.
[libucw.git] / lib / mempool.h
1 /*
2  *      UCW Library -- Memory Pools
3  *
4  *      (c) 1997--2005 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_POOLS_H
11 #define _UCW_POOLS_H
12
13 #ifndef POOL_ALIGN
14 #define POOL_ALIGN CPU_STRUCT_ALIGN
15 #endif
16
17 struct mempool {
18   byte *free, *last;
19   struct memchunk *first, *current, **plast;
20   struct memchunk *first_large;
21   uns chunk_size, threshold;
22 };
23
24 struct mempool *mp_new(uns);
25 void mp_delete(struct mempool *);
26 void mp_flush(struct mempool *);
27 void *mp_alloc(struct mempool *, uns) LIKE_MALLOC;
28 void *mp_alloc_zero(struct mempool *, uns) LIKE_MALLOC;
29
30 static inline void * LIKE_MALLOC
31 mp_alloc_fast(struct mempool *p, uns l)
32 {
33   byte *f = (void *) (((uintptr_t) p->free + POOL_ALIGN - 1) & ~(uintptr_t)(POOL_ALIGN - 1));
34   byte *ee = f + l;
35   if (ee > p->last)
36     return mp_alloc(p, l);
37   p->free = ee;
38   return f;
39 }
40
41 static inline void * LIKE_MALLOC mp_alloc_fast_noalign(struct mempool *p, uns l)
42 {
43   byte *f = p->free;
44   byte *ee = f + l;
45   if (ee > p->last)
46     return mp_alloc(p, l);
47   p->free = ee;
48   return f;
49 }
50
51 static inline void *
52 mp_start_string(struct mempool *p, uns l)
53 {
54   ASSERT(l <= p->chunk_size);
55   return mp_alloc(p, l);
56 }
57
58 static inline void
59 mp_end_string(struct mempool *p, void *stop)
60 {
61   p->free = stop;
62 }
63
64 /* mempool-str.c */
65
66 char *mp_strdup(struct mempool *, char *) LIKE_MALLOC;
67 void *mp_memdup(struct mempool *, void *, uns) LIKE_MALLOC;
68 char *mp_multicat(struct mempool *, ...) LIKE_MALLOC SENTINEL_CHECK;
69 static inline char * LIKE_MALLOC
70 mp_strcat(struct mempool *mp, char *x, char *y)
71 {
72   return mp_multicat(mp, x, y, NULL);
73 }
74 char *mp_strjoin(struct mempool *p, char **a, uns n, uns sep) LIKE_MALLOC;
75
76 /* mempool-fmt.c */
77
78 char *mp_printf(struct mempool *p, char *fmt, ...) FORMAT_CHECK(printf,2,3) LIKE_MALLOC;
79 char *mp_vprintf(struct mempool *p, char *fmt, va_list args) LIKE_MALLOC;
80
81 #endif