moka/lib/vec.c

67 lines
1.2 KiB
C

#include "vec.h"
void vec_init(struct vec* self)
{
assert(self);
self->capacity = 0;
self->size = 0;
self->data = NULL;
}
void vec_free_elements(struct vec* self, void (*func)(void*))
{
assert(self);
for (size_t i=0; i<self->size; i++)
{
if (func != NULL)
{
func(self->data[i]);
}
free(self->data[i]);
}
}
void vec_free(struct vec* self)
{
assert(self);
free(self->data);
self->data = NULL;
self->size = 0;
self->capacity = 0;
}
void vec_push(struct vec* self, void* element)
{
assert(self);
if (self->capacity == 0)
{
self->capacity = 1;
self->data = calloc(self->capacity, sizeof(void*));
}
else if (self->size + 1 >= self->capacity)
{
self->capacity *= 2;
void** data = realloc(
self->data,
self->capacity * sizeof(void*)
);
assert(data);
self->data = data;
}
self->data[self->size] = element;
self->size++;
}
void* vec_pop(struct vec* self)
{
assert(self);
assert(self->size > 0);
void* element = self->data[self->size - 1];
self->size--;
return element;
}