From 98a26c71f3a0cc16a39caf7040cf33d628e3e910 Mon Sep 17 00:00:00 2001 From: fredrikr79 Date: Wed, 2 Apr 2025 12:31:05 +0200 Subject: [PATCH] utils: implement integer vector --- src/utils/vector.c | 80 ++++++++++++++++++++++++++++++++++++++++++++++ src/utils/vector.h | 26 +++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 src/utils/vector.c create mode 100644 src/utils/vector.h diff --git a/src/utils/vector.c b/src/utils/vector.c new file mode 100644 index 0000000..3a751d3 --- /dev/null +++ b/src/utils/vector.c @@ -0,0 +1,80 @@ +#include "vector.h" +#include +#include + +void vector_init(Vector **v, int capacity) { + *v = malloc(sizeof(Vector)); + if (!*v) { + printf("vector_init: failed to allocate vector pointer\n"); + return; + } + (*v)->data = malloc(capacity * sizeof(int)); + if (!(*v)->data) { + printf("vector_init: failed to allocate data\n"); + return; + } + (*v)->size = 0; + (*v)->_capacity = capacity; +} + +Vector *vector_new(void) { + Vector *v; + vector_init(&v, VEC_MIN); + return v; +} + +void vector_grow(Vector *v) { + v->_capacity <<= 1; + v->data = realloc(v->data, sizeof(int) * v->_capacity); + if (!v->data) { + printf("vector_grow: failed to allocate data\n"); + return; + } +} + +void vector_push(Vector *v, int val) { + if (v->size >= v->_capacity) { + vector_grow(v); + } + v->data[v->size] = val; + v->size++; +} + +void vector_pusha(Vector *v, int *vals, int n) { + for (int i = 0; i < n; i++) { + int val = vals[i]; + vector_push(v, val); + } +} + +int vector_pop(Vector *v) { + int val = v->data[v->size - 1]; + v->size--; + return val; +} + +void vector_free(Vector *v) { + free(v->data); + v->size = 0; + v->_capacity = 0; + free(v); +} + +void vector_print(Vector v) { + printf("vector_print: "); + for (int i = 0; i < v.size; i++) { + printf("%d ", v.data[i]); + } + printf("\n"); +} + +int main(int argc, char *argv[]) { + Vector *v = vector_new(); + vector_push(v, 20); + vector_pusha(v, (int[]){1, 2, 3}, 3); + vector_print(*v); + printf("oops, i removed %d\n", vector_pop(v)); + vector_print(*v); + vector_free(v); + return 0; +} diff --git a/src/utils/vector.h b/src/utils/vector.h new file mode 100644 index 0000000..2bb21a0 --- /dev/null +++ b/src/utils/vector.h @@ -0,0 +1,26 @@ +#ifndef VECTOR_H +#define VECTOR_H + +#define VEC_MIN 8 + +typedef struct { + int *data; + int size; + int _capacity; +} Vector; + +void vector_init(Vector **v, int capacity); + +Vector *vector_new(void); + +void vector_grow(Vector *v); + +void vector_push(Vector *v, int val); + +int vector_pop(Vector *v); + +void vector_free(Vector *v); + +void vector_print(Vector v); + +#endif // VECTOR_H