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
141
142
143
144
145
146
147
148
149
150
|
/*
* Copyright (C) Igor Sysoev
* Copyright (C) NGINX, Inc.
*/
#include <nxt_main.h>
nxt_array_t *
nxt_array_create(nxt_mp_t *mp, nxt_uint_t n, size_t size)
{
nxt_array_t *array;
array = nxt_mp_alloc(mp, sizeof(nxt_array_t) + n * size);
if (nxt_slow_path(array == NULL)) {
return NULL;
}
array->elts = nxt_pointer_to(array, sizeof(nxt_array_t));
array->nelts = 0;
array->size = size;
array->nalloc = n;
array->mem_pool = mp;
return array;
}
void
nxt_array_destroy(nxt_array_t *array)
{
if (array->elts != nxt_pointer_to(array, sizeof(nxt_array_t))) {
nxt_mp_free(array->mem_pool, array->elts);
}
nxt_mp_free(array->mem_pool, array);
}
void *
nxt_array_add(nxt_array_t *array)
{
void *p;
uint32_t nalloc, new_alloc;
nalloc = array->nalloc;
if (array->nelts == nalloc) {
if (nalloc < 16) {
/* Allocate new array twice larger than current. */
new_alloc = (nalloc == 0) ? 4 : nalloc * 2;
} else {
/* Allocate new array 1.5 times larger than current. */
new_alloc = nalloc + nalloc / 2;
}
p = nxt_mp_alloc(array->mem_pool, array->size * new_alloc);
if (nxt_slow_path(p == NULL)) {
return NULL;
}
nxt_memcpy(p, array->elts, array->size * nalloc);
if (array->elts != nxt_pointer_to(array, sizeof(nxt_array_t))) {
nxt_mp_free(array->mem_pool, array->elts);
}
array->elts = p;
array->nalloc = new_alloc;
}
p = nxt_pointer_to(array->elts, array->size * array->nelts);
array->nelts++;
return p;
}
void *
nxt_array_zero_add(nxt_array_t *array)
{
void *p;
p = nxt_array_add(array);
if (nxt_fast_path(p != NULL)) {
nxt_memzero(p, array->size);
}
return p;
}
void
nxt_array_remove(nxt_array_t *array, void *elt)
{
void *last;
last = nxt_array_last(array);
if (elt != last) {
nxt_memcpy(elt, last, array->size);
}
array->nelts--;
}
nxt_array_t *
nxt_array_copy(nxt_mp_t *mp, nxt_array_t *dst, nxt_array_t *src)
{
void *data;
uint32_t i, size;
size = src->size;
if (dst == NULL) {
dst = nxt_array_create(mp, src->nelts, size);
if (nxt_slow_path(dst == NULL)) {
return NULL;
}
}
nxt_assert(size == dst->size);
if (dst->nalloc >= src->nelts) {
nxt_memcpy(dst->elts, src->elts, src->nelts * size);
} else {
nxt_memcpy(dst->elts, src->elts, dst->nelts * size);
for (i = dst->nelts; i < src->nelts; i++) {
data = nxt_array_add(dst);
if (nxt_slow_path(data == NULL)) {
return NULL;
}
nxt_memcpy(data, src->elts + (i * size), size);
}
}
dst->nelts = src->nelts;
return dst;
}
|