summaryrefslogtreecommitdiff
path: root/src/util/darray.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/util/darray.c')
-rw-r--r--src/util/darray.c39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/util/darray.c b/src/util/darray.c
new file mode 100644
index 0000000..f117ccf
--- /dev/null
+++ b/src/util/darray.c
@@ -0,0 +1,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;
+ }
+}