-
Notifications
You must be signed in to change notification settings - Fork 0
/
mempool.h
99 lines (82 loc) · 1.71 KB
/
mempool.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#ifndef __MEMPOOL_H_
#define __MEMPOOL_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <string.h>
struct mempool
{
unsigned int count;
void **blocks;
char *memory;
};
/**
* Initialize a memory pool
*
* @param pool the pool
* @param size the size of a memory block
* @param count the count of memory blocks
* @return 1 on success, 0 otherwise
*/
static int mempool_init(struct mempool *pool, unsigned int size,
unsigned int count)
{
memset(pool, 0, sizeof(struct mempool));
if (!size || !count) {
return 0;
}
char *memory = (char *)malloc(size * count);
void **blocks = (void **)malloc(sizeof(void *) * count);
if (!memory || !blocks) {
free(memory);
free(blocks);
return 0;
}
pool->memory = memory;
pool->blocks = blocks;
memory -= size;
while (count--) {
pool->blocks[pool->count] = memory + size;
pool->count++;
memory += size;
}
return 1;
}
/**
* Finalize a memory pool
*
* @param pool the pool
*/
static void mempool_term(struct mempool *pool)
{
free(pool->blocks);
free(pool->memory);
memset(pool, 0, sizeof(struct mempool));
}
/**
* Get a memory block from the pool
*
* @param pool the pool
* @return a pointer to memory block on success, NULL on failure
*/
static inline void * mempool_alloc(struct mempool *pool)
{
return pool->count ? pool->blocks[--pool->count] : NULL;
}
/**
* Free a memory block
*
* @param pool the pool
* @param block the block
*/
static inline void mempool_free(struct mempool *pool, void *block)
{
if (block) {
pool->blocks[pool->count++] = block;
}
}
#ifdef __cplusplus
}
#endif
#endif /* __MEMPOOL_H_ */