diff options
Diffstat (limited to 'src/vector.c')
-rw-r--r-- | src/vector.c | 45 |
1 files changed, 33 insertions, 12 deletions
diff --git a/src/vector.c b/src/vector.c index 46a65e5..536fd33 100644 --- a/src/vector.c +++ b/src/vector.c @@ -1,23 +1,44 @@ -#include <stdlib.h> #include "vector.h" +#include <stdlib.h> +#include <stdbool.h> + +static bool +vector_grow(struct vector *vec) +{ + vec->cap *= VECTOR_GROW_RATE; + vec->values = realloc(vec->values, sizeof(*vec->values) * vec->cap); + if (vec->values == NULL) { + return false; + } + + return true; +} + /* create a new vector of the given capacity */ -struct vector* vector_new(int cap) { - struct vector *l = malloc(sizeof *l); - l->size = 0; - l->cap = cap; - l->values = malloc(l->cap * sizeof *l->values); - return l; +struct vector * +vector_new(size_t cap) +{ + struct vector *vec = malloc(sizeof *vec); + vec->size = 0; + vec->cap = cap; + vec->values = malloc(vec->cap * sizeof *vec->values); + return vec; } /* push a new value to the end of the vector's memory */ -int vector_push(struct vector *vec, void *value) { +size_t +vector_push(struct vector *vec, void *value) +{ + if (vec->size == vec->cap) vector_grow(vec); vec->values[vec->size++] = value; return vec->size - 1; } /* free vector related memory */ -void vector_free(struct vector *l) { - free(l->values); - free(l); -}
\ No newline at end of file +void +vector_free(struct vector *vec) +{ + free(vec->values); + free(vec); +} |