89 lines
1.4 KiB
C
89 lines
1.4 KiB
C
#include "vec.h"
|
|
|
|
void vec_init(vec_t* self)
|
|
{
|
|
assert(self);
|
|
self->size = 0;
|
|
self->capacity = 0;
|
|
self->data = NULL;
|
|
}
|
|
|
|
void vec_free_elements(vec_t* self, void (*free_fun)(void*))
|
|
{
|
|
assert(self);
|
|
|
|
for (size_t i=0; i<self->size; i++)
|
|
{
|
|
if (free_fun)
|
|
{
|
|
free_fun(self->data[i]);
|
|
}
|
|
|
|
free(self->data[i]);
|
|
}
|
|
}
|
|
|
|
void vec_free(vec_t* self)
|
|
{
|
|
assert(self);
|
|
|
|
free(self->data);
|
|
self->data = NULL;
|
|
self->size = 0;
|
|
self->capacity = 0;
|
|
}
|
|
|
|
void vec_push(vec_t* self, void* value)
|
|
{
|
|
assert(self);
|
|
if (self->capacity == 0)
|
|
{
|
|
self->capacity = 2;
|
|
self->data = calloc(self->capacity, sizeof(void*));
|
|
}
|
|
|
|
if (self->size + 1 >= self->capacity)
|
|
{
|
|
self->capacity *= 2;
|
|
|
|
void** v = realloc(
|
|
self->data,
|
|
self->capacity * sizeof(void*)
|
|
);
|
|
|
|
assert(v);
|
|
|
|
self->data = v;
|
|
}
|
|
|
|
self->data[self->size] = value;
|
|
self->size++;
|
|
}
|
|
|
|
void* vec_pop(vec_t* self)
|
|
{
|
|
assert(self);
|
|
assert(self->size > 0);
|
|
|
|
void* value = self->data[self->size - 1];
|
|
self->size--;
|
|
return value;
|
|
}
|
|
|
|
void vec_remove(vec_t* self, size_t idx, void (*free_fun)(void*))
|
|
{
|
|
if (free_fun)
|
|
{
|
|
free_fun(self->data[idx]);
|
|
}
|
|
|
|
free(self->data[idx]);
|
|
|
|
for (ssize_t i=idx; i<((ssize_t)self->size) - 1; i++)
|
|
{
|
|
self->data[i] = self->data[i + 1];
|
|
}
|
|
|
|
vec_pop(self);
|
|
}
|