1 /* $OpenBSD: pool.h,v 1.2 2017/08/11 14:58:56 jasper Exp $ */
2
3 /*
4 * Copyright (c) 2017 Martin Pieuchot
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #ifndef _POOL_H_
20 #define _POOL_H_
21
22 #ifndef NOPOOL
23
24 struct pool {
25 SIMPLEQ_ENTRY(pool) pr_list; /* list of all pools */
26 const char *pr_name; /* identifier */
27 SLIST_HEAD(, pool_item) pr_free; /* free list */
28 size_t pr_nmemb; /* # of items per allocation */
29 size_t pr_size; /* size of an item */
30 size_t pr_nitems; /* # of available items */
31 size_t pr_nfree; /* # items on the free list */
32 };
33
34 void pool_init(struct pool *, const char *, size_t, size_t);
35 void *pool_get(struct pool *);
36 void pool_put(struct pool *, void *);
37 void pool_dump(void);
38
39 static inline void *
pmalloc(struct pool * pp,size_t sz)40 pmalloc(struct pool *pp, size_t sz)
41 {
42 return pool_get(pp);
43 }
44
45 static inline void *
pzalloc(struct pool * pp,size_t sz)46 pzalloc(struct pool *pp, size_t sz)
47 {
48 char *p;
49
50 p = pool_get(pp);
51 memset(p, 0, sz);
52
53 return p;
54 }
55
56 static inline void
pfree(struct pool * pp,void * p)57 pfree(struct pool *pp, void *p)
58 {
59 pool_put(pp, p);
60 }
61
62 #else /* !NOPOOL */
63 #define pmalloc(a, b) malloc(b)
64 #define pzalloc(a, b) calloc(1, b)
65 #define pfree(a, b) free(b)
66 #endif /* NOPOOL */
67
68 #endif /* _POOL_H_ */
69