aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/vector.c68
-rw-r--r--src/vector.h26
2 files changed, 94 insertions, 0 deletions
diff --git a/src/vector.c b/src/vector.c
new file mode 100644
index 0000000..ca58468
--- /dev/null
+++ b/src/vector.c
@@ -0,0 +1,68 @@
+#include "vector.h"
+#include <stdlib.h>
+
+static void vector_resize(Vector *v, size_t new_capacity);
+
+Vector *vector_new(void) {
+ Vector *v = (Vector *)malloc(sizeof(Vector));
+ if (!v)
+ return NULL;
+
+ v->data = (void **)malloc(INITAL_CAPACITY * sizeof(void *));
+ if (!v->data) {
+ free(v);
+ return NULL;
+ }
+
+ v->size = 0;
+ v->capacity = INITAL_CAPACITY;
+ return v;
+}
+
+void vector_delete(Vector *v) {
+ free(v->data);
+ free(v);
+}
+
+void vector_push(Vector *v, void *element) {
+ if (v->size >= v->capacity)
+ vector_resize(v, v->capacity * GROWTH_FACTOR);
+ v->data[++v->size] = element;
+}
+
+void *vector_pop(Vector *v) {
+ if (!v->size) return NULL;
+ return v->data[--v->size];
+}
+
+void *vector_get(Vector *v, size_t index) {
+ if (index >= v->size)
+ return NULL;
+ return v->data[index];
+}
+
+void vector_set(Vector *v, size_t index, void *element) {
+ if (index >= v->size)
+ return;
+ v->data[index] = element;
+}
+
+size_t vector_size(Vector *v) {
+ return v->size;
+}
+
+int vector_is_empty(Vector *v) {
+ return v->size == 0;
+}
+
+void vector_clear(Vector *v) {
+ v->size = 0;
+}
+
+static void vector_resize(Vector *v, size_t new_capacity) {
+ void **new_data = (void **)realloc(v->data, new_capacity * sizeof(void *));
+ if (new_data) {
+ v->data = new_data;
+ v->capacity = new_capacity;
+ }
+}
diff --git a/src/vector.h b/src/vector.h
new file mode 100644
index 0000000..b329192
--- /dev/null
+++ b/src/vector.h
@@ -0,0 +1,26 @@
+#ifndef VECTOR_H
+#define VECTOR_H
+
+#include <stddef.h>
+
+#define INITAL_CAPACITY 10
+#define GROWTH_FACTOR 2
+
+typedef struct Vector Vector;
+struct Vector {
+ void **data;
+ size_t size;
+ size_t capacity;
+};
+
+Vector *vector_new(void);
+void vector_delete(Vector *v);
+void vector_push(Vector *v, void *element);
+void *vector_pop(Vector *v);
+void *vector_get(Vector *v, size_t index);
+void vector_set(Vector *v, size_t index, void *element);
+size_t vector_size(Vector *v);
+int vector_is_empty(Vector *v);
+void vector_clear(Vector *v);
+
+#endif // !VECTOR_H