vis: remove __DATE__ and __TIME__ references to aid with reproducible builds
[vis.git] / array.c
blob7689b2e7ef1e1194267ed48e7517986711b5004d
1 #include <stdlib.h>
2 #include <string.h>
3 #include <errno.h>
5 #include "array.h"
6 #include "util.h"
8 #define ARRAY_SIZE 16
10 void array_init(Array *arr) {
11 memset(arr, 0, sizeof *arr);
14 bool array_reserve(Array *arr, size_t count) {
15 if (count < ARRAY_SIZE)
16 count = ARRAY_SIZE;
17 if (arr->count < count) {
18 count = MAX(count, arr->count*2);
19 void **items = realloc(arr->items, count * sizeof(void*));
20 if (!items)
21 return false;
22 arr->count = count;
23 arr->items = items;
25 return true;
28 void array_release(Array *arr) {
29 if (!arr)
30 return;
31 free(arr->items);
32 array_init(arr);
35 void array_release_full(Array *arr) {
36 if (!arr)
37 return;
38 for (size_t i = 0; i < arr->len; i++)
39 free(arr->items[i]);
40 array_release(arr);
43 void array_clear(Array *arr) {
44 arr->len = 0;
45 if (arr->items)
46 memset(arr->items, 0, arr->count * sizeof(void*));
49 void *array_get(Array *arr, size_t idx) {
50 if (idx >= arr->len) {
51 errno = EINVAL;
52 return NULL;
54 return arr->items[idx];
57 bool array_set(Array *arr, size_t idx, void *item) {
58 if (idx >= arr->len) {
59 errno = EINVAL;
60 return false;
62 arr->items[idx] = item;
63 return true;
66 bool array_add(Array *arr, void *item) {
67 if (!array_reserve(arr, arr->len+1))
68 return false;
69 arr->items[arr->len++] = item;;
70 return true;
73 size_t array_length(Array *arr) {
74 return arr->len;