This repository was archived by the owner on Jan 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain-helper.h
More file actions
88 lines (77 loc) · 1.78 KB
/
main-helper.h
File metadata and controls
88 lines (77 loc) · 1.78 KB
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
#ifndef MAIN_HELPER_H_
#define MAIN_HELPER_H_
struct ptr_array {
void **ptrs;
int l;
int size;
};
#define TRY_ALLOC_AT(s, a,pa,i,size) \
do { \
int old_i = s->nb_##a; \
if (s->nb_##a <= i) { \
int sz = i + 1; \
int oidx = ptr_array_get_idx(pa, s->a); \
s->a = realloc(s->a, sz * size); \
if (oidx < 0) \
ptr_array_append(pa, s->a); \
else { \
pa->ptrs[oidx] = s->a; \
s->a = pa->ptrs[oidx]; \
} \
memset(s->a + old_i, 0, size * (sz - old_i)); \
s->nb_##a = sz; \
} \
} while (0)
#define SET_NEXT(a,v,pa) do { \
int cnt; \
if (!a) { \
a = calloc(64, sizeof(v)); \
if (!a) break; \
if (ptr_array_append(pa, a) < 0) \
break; \
} \
for (cnt = 0; a[cnt]; ++cnt); \
if (cnt && (cnt % 63) == 0) { \
int idx = ptr_array_get_idx(pa, a); \
pa->ptrs[idx] = realloc(a, (cnt + 1 + 64) * sizeof(v)); \
if (!pa->ptrs[idx]) { free(a); break; } \
a = pa->ptrs[idx]; \
memset(a + cnt + 1, 0, 64 * sizeof(v)); \
} \
a[cnt] = v; \
} while (0)
static inline int ptr_array_append(struct ptr_array *pa, void *ptr)
{
if (!(pa->l & 63)) { /* need grow up */
void *old = pa->ptrs;
pa->size += 64;
pa->ptrs = realloc(old, pa->size);
if (!pa->ptrs) {
free(old);
return -1;
}
}
pa->ptrs[pa->l++] = ptr;
return 0;
}
static inline int ptr_array_get_idx(struct ptr_array *pa, void *ptr)
{
for (int i = 0; i < pa->l; ++i)
if (pa->ptrs[i] == ptr)
return i;
return -1;
}
static inline int ptr_array_free_all(struct ptr_array *pa)
{
if (pa->ptrs) {
for (int i = 0; i < pa->l; ++i) {
free(pa->ptrs[i]);
}
free(pa->ptrs);
pa->ptrs = NULL;
pa->size = 0;
pa->l = 0;
}
return 0;
}
#endif /* MAIN_HELPER_H_ */