aboutsummaryrefslogtreecommitdiffstats
path: root/vector.c
diff options
context:
space:
mode:
authorLars Hjemli <hjemli@gmail.com>2010-11-09 19:57:18 +0100
committerLars Hjemli <hjemli@gmail.com>2010-11-10 00:22:41 +0100
commit958a95b37891098133369e835a2ab687e0dfa9dc (patch)
tree31bcd62973d381b072b91da15528c48c6fc14a41 /vector.c
parent52558a6d39d52e2b2968b622534b0ffa4da285cb (diff)
Add vector utility functions
Signed-off-by: Lars Hjemli <hjemli@gmail.com>
Diffstat (limited to '')
-rw-r--r--vector.c38
1 files changed, 38 insertions, 0 deletions
diff --git a/vector.c b/vector.c
new file mode 100644
index 0000000..0863908
--- /dev/null
+++ b/vector.c
@@ -0,0 +1,38 @@
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include "vector.h"
+
+static int grow(struct vector *vec, int gently)
+{
+ size_t new_alloc;
+ void *new_data;
+
+ new_alloc = vec->alloc * 3 / 2;
+ if (!new_alloc)
+ new_alloc = 8;
+ new_data = realloc(vec->data, new_alloc * vec->size);
+ if (!new_data) {
+ if (gently)
+ return ENOMEM;
+ perror("vector.c:grow()");
+ exit(1);
+ }
+ vec->data = new_data;
+ vec->alloc = new_alloc;
+ return 0;
+}
+
+int vector_push(struct vector *vec, const void *data, int gently)
+{
+ int rc;
+
+ if (vec->count == vec->alloc && (rc = grow(vec, gently)))
+ return rc;
+ if (data)
+ memmove(vec->data + vec->count * vec->size, data, vec->size);
+ else
+ memset(vec->data + vec->count * vec->size, 0, vec->size);
+ vec->count++;
+ return 0;
+}