libds/src/vec.c

116 lines
2.4 KiB
C
Raw Normal View History

#include "vec.h"
#include <stdio.h>
2016-12-21 14:50:32 -08:00
#include <stdlib.h>
#include <string.h>
2016-12-21 14:50:32 -08:00
libds_result vec_init(vec* v) {
libds_result result = LIBDS_SUCCESS;
2016-12-21 14:50:32 -08:00
v->size = 0;
v->capacity = LIBDS_VEC_CAPACITY;
v->data = calloc(LIBDS_VEC_CAPACITY, sizeof(void*));
2016-12-21 14:50:32 -08:00
if (v->data == NULL) {
result = LIBDS_MALLOC;
}
return result;
}
2016-12-21 14:50:32 -08:00
void vec_free(vec* v) {
v->size = 0;
v->capacity = 0;
2016-12-21 14:50:32 -08:00
if (v->data) {
free(v->data);
}
v->data = NULL;
}
2016-12-21 14:50:32 -08:00
libds_result vec_add(vec* v, void* data) {
libds_result result = LIBDS_SUCCESS;
2016-12-21 14:50:32 -08:00
if (v->size >= v->capacity) {
void* new_mem = calloc(v->capacity *= 2, sizeof(void*));
2016-12-21 14:50:32 -08:00
if (new_mem) {
memcpy(new_mem, v->data, sizeof(void*) * v->capacity / 2);
free(v->data);
v->data = new_mem;
} else {
result = LIBDS_MALLOC;
}
}
if (result == LIBDS_SUCCESS) {
int index = 0;
2016-12-21 14:50:32 -08:00
while (index < v->capacity) {
void** data_array = v->data;
2016-12-21 14:50:32 -08:00
if (data_array[index] == NULL) {
data_array[index] = data;
2016-12-21 14:50:32 -08:00
v->size++;
break;
}
index++;
}
}
return result;
}
2016-12-21 14:50:32 -08:00
void vec_remove(vec* v, void* data) {
int elements = v->size;
int index = 0;
void** data_array = v->data;
2016-12-21 14:50:32 -08:00
while (elements > 0) {
if (data_array[index]) {
elements--;
2016-12-21 14:50:32 -08:00
if (data_array[index] == data) {
data_array[index] = NULL;
2016-12-21 14:50:32 -08:00
v->size--;
}
}
index++;
}
}
2016-12-21 14:50:32 -08:00
void* vec_find(vec* v, void* data, compare_func compare) {
int elements = v->size;
int index = 0;
void* found = NULL;
void** data_array = v->data;
2016-12-21 14:50:32 -08:00
while (elements > 0 && found == NULL) {
if (data_array[index]) {
if (compare(data, data_array[index])) {
found = data_array[index];
}
2016-12-21 14:50:32 -08:00
elements--;
}
index++;
}
return found;
}
2016-12-21 14:50:32 -08:00
int vec_foreach(vec* v, void* data, compare_func compare, foreach_func foreach,
...) {
int elements = v->size;
int index = 0;
int return_code = 0;
void** data_array = v->data;
va_list args;
2016-12-21 14:50:32 -08:00
while (elements > 0 && return_code == 0) {
if (data_array[index]) {
if (compare(data, data_array[index])) {
va_start(args, foreach);
2016-12-21 14:50:32 -08:00
return_code = foreach (data_array[index], args);
va_end(args);
}
elements--;
}
index++;
}
return return_code;
}
2016-12-21 14:50:32 -08:00
void* vec_index(vec* v, int index) {
void* to_return = NULL;
2016-12-21 14:50:32 -08:00
if (index < v->capacity && index >= 0) {
void** data_array = v->data;
to_return = data_array[index];
}
return to_return;
}