-
Notifications
You must be signed in to change notification settings - Fork 21
/
pool.c
81 lines (63 loc) · 1.44 KB
/
pool.c
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
#include <string.h>
#include <stdlib.h>
#include "pool.h"
#ifndef max
#define max(a,b) ((a)<(b)?(b):(a))
#endif
void poolInitialize(pool *p, const uint32_t elementSize, const uint32_t blockSize)
{
uint32_t i;
p->elementSize = max(elementSize, sizeof(poolFreed));
p->blockSize = blockSize;
poolFreeAll(p);
p->blocksUsed = POOL_BLOCKS_INITIAL;
p->blocks = malloc(sizeof(uint8_t*)* p->blocksUsed);
for(i = 0; i < p->blocksUsed; ++i)
p->blocks[i] = NULL;
}
void poolFreePool(pool *p)
{
uint32_t i;
for(i = 0; i < p->blocksUsed; ++i) {
if(p->blocks[i] == NULL)
break;
else
free(p->blocks[i]);
}
free(p->blocks);
}
#ifndef DISABLE_MEMORY_POOLING
void *poolMalloc(pool *p)
{
if(p->freed != NULL) {
void *recycle = p->freed;
p->freed = p->freed->nextFree;
return recycle;
}
if(++p->used == p->blockSize) {
p->used = 0;
if(++p->block == (int32_t)p->blocksUsed) {
uint32_t i;
p->blocksUsed <<= 1;
p->blocks = realloc(p->blocks, sizeof(uint8_t*)* p->blocksUsed);
for(i = p->blocksUsed >> 1; i < p->blocksUsed; ++i)
p->blocks[i] = NULL;
}
if(p->blocks[p->block] == NULL)
p->blocks[p->block] = malloc(p->elementSize * p->blockSize);
}
return p->blocks[p->block] + p->used * p->elementSize;
}
void poolFree(pool *p, void *ptr)
{
poolFreed *pFreed = p->freed;
p->freed = ptr;
p->freed->nextFree = pFreed;
}
#endif
void poolFreeAll(pool *p)
{
p->used = p->blockSize - 1;
p->block = -1;
p->freed = NULL;
}