cvector/src/vector.c

102 lines
2.2 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "vector.h"
Vector vec_new(Destructor destructor)
{
Vector self;
self.length = 0;
self.capacity = INITIAL_CAPACITY;
self.offset = sizeof(void *);
self.elements = (void *)malloc(self.offset * INITIAL_CAPACITY);
self.destroy = destructor;
return self;
}
Vector vec_with_capacity(Destructor const t_destructor, size_t const t_capacity)
{
Vector self = vec_new(t_destructor);
free(self.elements);
self.elements = (void **)malloc(self.offset * t_capacity);
self.capacity = t_capacity;
return self;
}
void *vec_at(Vector const *const self, size_t const t_index)
{
return self->elements[t_index];
}
void *vec_safe_at(Vector const *const self, size_t const t_index)
{
return (t_index >= vec_length(self)) ? NULL : vec_at(self, t_index);
}
static void vec_maybe_destroy_element(Vector const *self, size_t const t_index)
{
void *element = vec_at(self, t_index);
if (self->destroy) {
self->destroy(element);
}
}
void *vec_last(Vector const *const self)
{
return vec_at(self, vec_length(self) - 1);
}
size_t vec_length(Vector const *const self)
{
return self->length;
}
size_t vec_capacity(Vector const *const self)
{
return self->capacity;
}
static void vec_realloc(Vector *const self)
{
self->capacity *= 2;
self->elements = realloc(self->elements, sizeof(void *) * vec_capacity(self));
if (!self->elements) {
PDEB("Could not reallocate Vectors memory, aborting...", NULL);
exit(ERR_MEM_ALLOC);
}
}
void vec_push(Vector *const self, void const *const t_element)
{
if (vec_length(self) >= vec_capacity(self)) {
vec_realloc(self);
}
self->elements[(*self).length++] = t_element;
}
void vec_pop(Vector *const self)
{
if (vec_length(self) <= 0) {
return;
}
vec_maybe_destroy_element(self, vec_length(self) - 1);
--(*self).length;
}
void vec_shrink_to_fit(Vector *const self)
{
self->capacity = self->length;
self->elements = realloc(self->elements, sizeof(void *) * vec_capacity(self));
if (!self->elements) {
PDEB("Could not reallocate Vectors memory, aborting...", NULL);
exit(ERR_MEM_ALLOC);
}
}
void vec_delete(Vector *const self)
{
if (self->destroy) {
for (size_t i = 0; i < vec_length(self); ++i) {
self->destroy(self->elements[i]);
}
}
free(self->elements);
}