forked from hufrea/byedpi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mpool.c
131 lines (113 loc) · 2.71 KB
/
mpool.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
#include <stdlib.h>
#include <string.h>
#include <mpool.h>
struct mphdr *mem_pool(int count)
{
struct mphdr *hdr = malloc(sizeof(struct mphdr));
if (!hdr) {
return 0;
}
hdr->inc = count;
hdr->max = count;
hdr->count = 0;
hdr->values = malloc(sizeof(*hdr->values) * count);
if (!hdr->values) {
free(hdr);
hdr = 0;
}
return hdr;
}
int mem_index(struct mphdr *hdr, char *str, int len)
{
if (!hdr->count) {
return -2;
}
int s = 0, m, i;
int e = hdr->count - 1;
while (s <= e) {
m = s + (e - s) / 2;
struct elem *val = hdr->values[m];
if (val->len != len)
i = len < val->len ? -1 : 1;
else
i = memcmp(str, val->data, len);
if (i > 0)
s = m + 1;
else if (i < 0)
e = m - 1;
else
return m;
}
return -(m + 2 + (i > 0 ? 1 : 0));
}
struct elem *mem_add(struct mphdr *hdr, char *str, int len, int pos)
{
int max = hdr->max;
if (hdr->count >= max) {
max += hdr->inc;
struct elem **new = realloc(hdr->values, sizeof(*hdr->values) * max);
if (!new) {
return 0;
}
hdr->max = max;
hdr->values = new;
}
if (pos >= 0) {
return hdr->values[pos];
}
pos = -pos - 2;
struct elem *val = malloc(sizeof(struct elem) + len);
if (!val) {
return 0;
}
memset(val, 0, sizeof(*val));
memcpy(val->data, str, len);
val->len = len;
if (pos < hdr->count) {
void *p = &hdr->values[pos];
void *n = &hdr->values[pos + 1];
void *e = &hdr->values[hdr->count];
memmove(n, p, e - p);
}
hdr->values[pos] = val;
hdr->count++;
return val;
}
void mem_delete(struct mphdr *hdr, int pos)
{
int max = hdr->max;
if (!hdr->count) {
return;
}
if (max > hdr->inc &&
(max - hdr->count) > hdr->inc * 2) {
max -= hdr->inc;
struct elem **new = realloc(hdr->values, sizeof(*hdr->values) * max);
if (new) {
hdr->max = max;
hdr->values = new;
}
}
free(hdr->values[pos]);
if (pos < hdr->count) {
void *p = &hdr->values[pos];
void *n = &hdr->values[pos + 1];
void *e = &hdr->values[hdr->count];
memmove(p, n, e - n);
}
hdr->count--;
}
void mem_destroy(struct mphdr *hdr)
{
for (int i = 0; i < hdr->count && hdr->values; i++) {
struct elem *e = hdr->values[i];
if (!e) {
continue;
}
free(e);
hdr->values[i] = 0;
}
free(hdr->values);
memset(hdr, 0, sizeof(*hdr));
free(hdr);
}