/builds/xfbs/passgen/src/container/array.c
Line | Count | Source (jump to first uncovered line) |
1 | | #include <passgen/assert.h> |
2 | | #include <passgen/config.h> |
3 | | #include <passgen/container/array.h> |
4 | | #include <stdlib.h> |
5 | | #include <string.h> |
6 | | |
7 | 0 | #define SIZE_INITIAL 4 |
8 | | |
9 | 6 | void passgen_array_realloc(passgen_array *array, size_t capacity) { |
10 | 6 | array->data = realloc(array->data, capacity * sizeof(void *)); |
11 | 6 | array->capacity = capacity; |
12 | 6 | } |
13 | | |
14 | | // Initialize array. Optionally takes a capacity, if so, memory that is |
15 | | // sufficiently large to hold `capacity` items will be allocated. |
16 | 10.6k | void passgen_array_init(passgen_array *array, size_t capacity) { |
17 | 10.6k | memset(array, 0, sizeof(*array)); |
18 | 10.6k | |
19 | 10.6k | if(capacity) { |
20 | 5 | passgen_array_realloc(array, capacity); |
21 | 5 | } |
22 | 10.6k | } |
23 | | |
24 | | // Push an item to the back of the array. |
25 | 9 | void passgen_array_push(passgen_array *array, void *pointer) { |
26 | 9 | if(!array->data) { |
27 | 0 | passgen_array_realloc(array, SIZE_INITIAL); |
28 | 0 | } |
29 | 9 | |
30 | 9 | if(array->items == array->capacity) { |
31 | 0 | passgen_array_realloc(array, array->capacity * 2); |
32 | 0 | } |
33 | 9 | |
34 | 9 | array->data[array->items] = pointer; |
35 | 9 | array->items += 1; |
36 | 9 | } |
37 | | |
38 | | // Retrieve an item from the array. |
39 | 3 | void *passgen_array_get(passgen_array *array, size_t pos) { |
40 | 3 | #ifdef PASSGEN_DEBUG |
41 | 3 | passgen_assert(pos <= array->items); |
42 | 3 | #endif |
43 | 3 | |
44 | 3 | return array->data[pos]; |
45 | 3 | } |
46 | | |
47 | | // Frees an array. |
48 | 5 | void passgen_array_free(passgen_array *array) { |
49 | 5 | free(array->data); |
50 | 5 | memset(array, 0, sizeof(*array)); |
51 | 5 | } |
52 | | |
53 | | // Pops the last item off the array and returns it. |
54 | 4 | void *passgen_array_pop(passgen_array *array) { |
55 | 4 | if(!array->items) { |
56 | 1 | return NULL; |
57 | 1 | } |
58 | 3 | |
59 | 3 | array->items -= 1; |
60 | 3 | return array->data[array->items]; |
61 | 3 | } |