aboutsummaryrefslogtreecommitdiff
path: root/src/core/ngx_array.c
blob: 08ad5887b8a5de573976b5c2b63103e2fb8c1df1 (plain)
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
#include <ngx_config.h>

#include <ngx_alloc.h>
#include <ngx_array.h>

ngx_array_t *ngx_create_array(ngx_pool_t *p, int n, size_t size)
{
    ngx_array_t *a;

    a = ngx_palloc(p, sizeof(ngx_array_t));
    if (a == NULL)
        return NULL;

    a->elts = ngx_palloc(p, n * size);
    if (a->elts == NULL)
        return NULL;

    a->pool = p;
    a->nelts = 0;
    a->nalloc = n;
    a->size = size;

    return a;
}

void ngx_destroy_array(ngx_array_t *a)
{
    ngx_pool_t *p = a->pool;

    if (a->elts + a->size * a->nalloc == p->last)
        p->last -= a->size * a->nalloc;

    if ((char *) a + sizeof(ngx_array_t) == p->last)
        p->last = (char *) a;
}

void *ngx_push_array(ngx_array_t *a)
{
    void *elt;

    /* array is full */
    if (a->nelts == a->nalloc) {
        ngx_pool_t *p = a->pool;

        /* array allocation is the last in the pool */
        if (a->elts + a->size * a->nelts == p->last
            && (unsigned) (p->end - p->last) >= a->size)
        {
            p->last += a->size;
            a->nalloc++;

        /* allocate new array */
        } else {
            void *new = ngx_palloc(p, 2 * a->nalloc * a->size);
            if (new == NULL)
                return NULL;

            memcpy(new, a->elts, a->nalloc * a->size);
            a->elts = new;
            a->nalloc *= 2;
        }
    }

    elt = a->elts + a->size * a->nelts;
    a->nelts++;

    return elt;
}