diff options
author | Igor Sysoev <igor@sysoev.ru> | 2017-01-17 20:00:00 +0300 |
---|---|---|
committer | Igor Sysoev <igor@sysoev.ru> | 2017-01-17 20:00:00 +0300 |
commit | 16cbf3c076a0aca6d47adaf3f719493674cf2363 (patch) | |
tree | e6530480020f62a2bdbf249988ec3e2a751d3927 /src/nxt_array.c | |
download | unit-16cbf3c076a0aca6d47adaf3f719493674cf2363.tar.gz unit-16cbf3c076a0aca6d47adaf3f719493674cf2363.tar.bz2 |
Initial version.
Diffstat (limited to 'src/nxt_array.c')
-rw-r--r-- | src/nxt_array.c | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/src/nxt_array.c b/src/nxt_array.c new file mode 100644 index 00000000..69e59c67 --- /dev/null +++ b/src/nxt_array.c @@ -0,0 +1,96 @@ + +/* + * Copyright (C) Igor Sysoev + * Copyright (C) NGINX, Inc. + */ + +#include <nxt_main.h> + + +nxt_array_t * +nxt_array_create(nxt_mem_pool_t *mp, nxt_uint_t n, size_t size) +{ + nxt_array_t *array; + + array = nxt_mem_alloc(mp, sizeof(nxt_array_t) + n * size); + + if (nxt_slow_path(array == NULL)) { + return NULL; + } + + array->elts = (char *) array + sizeof(nxt_array_t); + array->nelts = 0; + array->size = size; + array->nalloc = n; + array->mem_pool = mp; + + return 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 * 2; + + } else { + /* Allocate new array 1.5 times larger than current. */ + new_alloc = nalloc + nalloc / 2; + } + + p = nxt_mem_alloc(array->mem_pool, array->size * new_alloc); + + if (nxt_slow_path(p == NULL)) { + return NULL; + } + + nxt_memcpy(p, array->elts, array->size * nalloc); + + array->elts = p; + array->nalloc = new_alloc; + } + + p = (char *) 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--; +} |