-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.c
executable file
·141 lines (115 loc) · 2.22 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/**
* @file pool.c
* @author Hightman Mar
* @editor set number ; syntax on ; set autoindent ; set tabstop=4 (vim)
* $Id$
*/
#include "pool.h"
#include <stdio.h>
#include <stdlib.h>
#ifndef WIN32
# include <unistd.h>
#endif
#include <string.h>
/** pool memory management */
static void _pool_append_clean(pool_t p, void *obj)
{
struct pclean *c;
p->size += sizeof(struct pclean);
c = (struct pclean *) malloc(sizeof(struct pclean));
c->obj = obj;
c->nxt = p->clean;
p->clean = c;
}
static void _pool_heap_new(pool_t p)
{
if (p->heap != NULL)
p->dirty += (p->heap->size - p->heap->used);
p->heap = (struct pheap *) malloc(POOL_BLK_SIZ);
p->heap->size = POOL_BLK_SIZ - sizeof(struct pheap);
p->heap->used = 0;
p->size += POOL_BLK_SIZ;
_pool_append_clean(p, (void *) p->heap);
}
pool_t pool_new()
{
pool_t p;
p = (pool_t) malloc(sizeof(pool_st));
p->size = sizeof(pool_st);
p->dirty = 0;
p->heap = NULL;
p->clean = NULL;
_pool_heap_new(p);
return p;
}
void pool_free(pool_t p)
{
struct pclean *cur, *nxt;
cur = p->clean;
while (cur != NULL)
{
free(cur->obj);
nxt = cur->nxt;
free(cur);
cur = nxt;
}
free(p);
}
void *pmalloc(pool_t p, int size)
{
void *block;
/* big request */
if (size > (p->heap->size / 4))
{
block = malloc(size);
p->size += size;
_pool_append_clean(p, block);
return block;
}
/* memory align (>=4) */
if (size & 0x04)
{
while (p->heap->used & 0x03)
{
p->dirty++;
p->heap->used++;
}
}
/* not enough? */
if (size > (p->heap->size - p->heap->used))
_pool_heap_new(p);
block = (void *)((char *) p->heap->block + p->heap->used);
p->heap->used += size;
return block;
}
void *pmalloc_x(pool_t p, int size, char c)
{
void *result = pmalloc(p, size);
memset(result, c, size);
return result;
}
void *pmalloc_z(pool_t p, int size)
{
return pmalloc_x(p, size, 0);
}
char *pstrdup(pool_t p, const char *src)
{
char *dst;
int len;
if (src == NULL)
return NULL;
len = strlen(src) + 1;
dst = (char *) pmalloc(p, len);
memcpy(dst, src, len);
return dst;
}
char *pstrndup(pool_t p, const char *src, int len)
{
char *dst;
if (src == NULL)
return NULL;
dst = (char *) pmalloc(p, len + 1);
memcpy(dst, src, len);
dst[len] = '\0';
return dst;
}