aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--array.c75
-rw-r--r--array.h31
2 files changed, 106 insertions, 0 deletions
diff --git a/array.c b/array.c
new file mode 100644
index 0000000..7689b2e
--- /dev/null
+++ b/array.c
@@ -0,0 +1,75 @@
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include "array.h"
+#include "util.h"
+
+#define ARRAY_SIZE 16
+
+void array_init(Array *arr) {
+ memset(arr, 0, sizeof *arr);
+}
+
+bool array_reserve(Array *arr, size_t count) {
+ if (count < ARRAY_SIZE)
+ count = ARRAY_SIZE;
+ if (arr->count < count) {
+ count = MAX(count, arr->count*2);
+ void **items = realloc(arr->items, count * sizeof(void*));
+ if (!items)
+ return false;
+ arr->count = count;
+ arr->items = items;
+ }
+ return true;
+}
+
+void array_release(Array *arr) {
+ if (!arr)
+ return;
+ free(arr->items);
+ array_init(arr);
+}
+
+void array_release_full(Array *arr) {
+ if (!arr)
+ return;
+ for (size_t i = 0; i < arr->len; i++)
+ free(arr->items[i]);
+ array_release(arr);
+}
+
+void array_clear(Array *arr) {
+ arr->len = 0;
+ if (arr->items)
+ memset(arr->items, 0, arr->count * sizeof(void*));
+}
+
+void *array_get(Array *arr, size_t idx) {
+ if (idx >= arr->len) {
+ errno = EINVAL;
+ return NULL;
+ }
+ return arr->items[idx];
+}
+
+bool array_set(Array *arr, size_t idx, void *item) {
+ if (idx >= arr->len) {
+ errno = EINVAL;
+ return false;
+ }
+ arr->items[idx] = item;
+ return true;
+}
+
+bool array_add(Array *arr, void *item) {
+ if (!array_reserve(arr, arr->len+1))
+ return false;
+ arr->items[arr->len++] = item;;
+ return true;
+}
+
+size_t array_length(Array *arr) {
+ return arr->len;
+}
diff --git a/array.h b/array.h
new file mode 100644
index 0000000..2d9c123
--- /dev/null
+++ b/array.h
@@ -0,0 +1,31 @@
+#ifndef ARRAY_H
+#define ARRAY_H
+
+#include <stddef.h>
+#include <stdbool.h>
+
+typedef struct { /* a dynamically growing array */
+ void **items; /* NULL if empty */
+ size_t len; /* number of currently stored items */
+ size_t count; /* maximal capacity of the array */
+} Array;
+
+/* initalize a (stack allocated) Array instance */
+void array_init(Array*);
+/* release/free the storage space used to hold items, reset size to zero */
+void array_release(Array*);
+/* like above but also call free(3) for each stored pointer */
+void array_release_full(Array*);
+/* remove all elements, set array length to zero, keep allocated memory */
+void array_clear(Array*);
+/* reserve space to store at least `count' elements in this aray */
+bool array_reserve(Array*, size_t count);
+/* get/set the i-th (zero based) element of the array */
+void *array_get(Array*, size_t idx);
+bool array_set(Array*, size_t idx, void *item);
+/* add a new element to the end of the array */
+bool array_add(Array*, void *item);
+/* return the number of elements currently stored in the array */
+size_t array_length(Array*);
+
+#endif