summaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/util')
-rw-r--r--src/util/CMakeLists.txt10
-rw-r--r--src/util/util.c23
-rw-r--r--src/util/util.h6
-rw-r--r--src/util/util.test.c61
4 files changed, 100 insertions, 0 deletions
diff --git a/src/util/CMakeLists.txt b/src/util/CMakeLists.txt
new file mode 100644
index 0000000..dc18b39
--- /dev/null
+++ b/src/util/CMakeLists.txt
@@ -0,0 +1,10 @@
+project(kalmia)
+
+target_sources(kalmia PUBLIC util.c)
+
+if (KALMIA_BUILD_TESTS)
+ target_sources(
+ kalmia-tests PUBLIC
+ util.test.c
+ )
+endif()
diff --git a/src/util/util.c b/src/util/util.c
new file mode 100644
index 0000000..c77b3f4
--- /dev/null
+++ b/src/util/util.c
@@ -0,0 +1,23 @@
+#include <kalmia.h>
+#include <stdint.h>
+#include <stdio.h>
+
+
+void *kai_expand_array(void **array, size_t *count, size_t element_size)
+{
+ size_t new_count = *count + 1;
+ size_t new_size = element_size * new_count;
+ /* cast to uint8_t so we can do pointer arithmetic */
+ uint8_t *new_array = realloc(*array, new_size);
+ if (new_array == NULL) {
+ fprintf(stderr, "[kalmia] ERROR: failed to add %ul bytes to %ul-byte array!\n",
+ element_size, element_size * *count);
+ return NULL;
+ }
+
+ void *new_element = new_array + (*count * element_size);
+
+ *array = new_array;
+ *count = new_count;
+ return new_element;
+}
diff --git a/src/util/util.h b/src/util/util.h
new file mode 100644
index 0000000..c2f01eb
--- /dev/null
+++ b/src/util/util.h
@@ -0,0 +1,6 @@
+#ifndef KALMIA_UTIL_H
+#define KALMIA_UTIL_H
+
+void * kai_expand_array(void **array, size_t *len, size_t element_size);
+
+#endif
diff --git a/src/util/util.test.c b/src/util/util.test.c
new file mode 100644
index 0000000..9f64085
--- /dev/null
+++ b/src/util/util.test.c
@@ -0,0 +1,61 @@
+#include <test/test.h>
+#include "util.h"
+
+LILY_FILE_BEGIN(util_suite)
+
+
+LILY_TEST("expand NULL array")
+{
+ size_t count = 0;
+ int *array = NULL;
+
+ int *first = kai_expand_array((void**) &array, &count, sizeof(int));
+
+ CHECK_NEQ(first, NULL, "%p");
+ CHECK_NEQ(array, NULL, "%p");
+ CHECK_EQ(first, array, "%p");
+ CHECK_EQ(count, 1, "%d");
+
+ int *second = kai_expand_array((void**) &array, &count, sizeof(int));
+
+ CHECK_NEQ(second, NULL, "%p");
+ CHECK_EQ(second, array+1, "%p");
+ CHECK_EQ(count, 2, "%d");
+
+ free(array);
+}
+#include LILY_PUSH_TEST()
+
+
+struct test100 {
+ int value;
+ const char *str;
+};
+
+LILY_TEST("expand array 100 times")
+{
+ size_t count = 0;
+ struct test100 *array = NULL;
+
+ const char *str = "hello, world!";
+
+ for (int i=0; i<100; i++) {
+ struct test100 *element = kai_expand_array((void**) &array, &count, sizeof(struct test100));
+ element->value = i;
+ element->str = str;
+ }
+
+ CHECK_EQ(count, 100, "%ul");
+
+ for (int i=0; i<100; i++) {
+ CHECK_EQ(array[i].value, i, "%d");
+ CHECK_EQ(array[i].str, str, "%p");
+ }
+
+ free(array);
+}
+#include LILY_PUSH_TEST()
+
+
+#define LILY_FILE_END
+#include LILY_REGISTER_TESTS()