summaryrefslogtreecommitdiff
path: root/src/util/darray.c
blob: f117ccf606a39002d43be64fc8ffa73019b09a02 (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
#include "assert.h"
#include "darray.h"


int darray_size(void *darray) {
	return darray != NULL ? DARRAY_OCCUPIED(darray) : 0;
}

void darray_free(void *darray) {
	if (darray != NULL) {
		free(DARRAY_RAW_DATA(darray));
	}
}

void *darray_hold(void *darray, int count, int itemsize) {
	assert(count > 0 && itemsize > 0);
	if (darray == NULL) {
		int raw_size = sizeof(int) * 2 + itemsize * count;
		int *base = (int*)malloc(raw_size);
		base[0] = count;  /* capacity */
		base[1] = count;  /* occupied */
		return base + 2;
	}
	else if (DARRAY_OCCUPIED(darray) + count <= DARRAY_CAPACITY(darray)) {
		DARRAY_OCCUPIED(darray) += count;
		return darray;
	}
	else {
		int needed_size = DARRAY_OCCUPIED(darray) + count;
		int double_curr = DARRAY_CAPACITY(darray) * 2;
		int capacity = needed_size > double_curr ? needed_size : double_curr;
		int occupied = needed_size;
		int raw_size = sizeof(int) * 2 + itemsize * capacity;
		int *base = (int*)realloc(DARRAY_RAW_DATA(darray), raw_size);
		base[0] = capacity;
		base[1] = occupied;
		return base + 2;
	}
}