summaryrefslogtreecommitdiff
path: root/util/arr.c
blob: 0d7ddfa3910bb2cee3c283eb1520692a1a7b4d4f (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
typedef struct {
	void *data;
	size_t len;
	size_t cap;
	size_t item_sz;
} Array;

static void arr_create(Array *arr, size_t item_sz) {
	arr->len = arr->cap = 0;
	arr->item_sz = item_sz;
	arr->data = NULL;
}

static inline void arr_reserve(Array *arr, size_t n) {
	arr->cap = n;
	arr->data = realloc(arr->data, arr->item_sz * arr->cap);

}

static inline void *arr_last(Array *arr) {
	if (arr->data)
		return (void*)((char*)arr->data + arr->item_sz * (arr->len - 1));
	else
		return NULL;
}

static void *arr_add(Array *arr) {
	if (arr->len >= arr->cap) {
		arr_reserve(arr, (arr->cap + 1) * 2);
	}
	arr->len++;
	return (void*)((char*)arr->data + arr->item_sz * (arr->len - 1));
}

static void arr_clear(Array *arr) {
	free(arr->data);
	arr->len = arr->cap = 0;
	arr->data = NULL;
}

static void arr_remove_last(Array *arr) {
	/* OPTIM (memory): Shorten array. */
	arr->len--;
	if (!arr->len) {
		arr_clear(arr);
	}
	
}

static void arr_free(Array *arr) {
	free(arr->data);
}

#define arr_foreach(arr, type, var) for (type *var = (arr)->data, *var##_foreach_last = arr_last(arr); var; var == var##_foreach_last ? var = NULL : var++)
#define arr_foreach_reverse(arr, type, var) for (type *var = arr_last(arr); var; var == (arr)->data ? var = NULL : var--)