diff --git a/src/vec.c b/src/vec.c new file mode 100644 index 0000000..5adaf48 --- /dev/null +++ b/src/vec.c @@ -0,0 +1,105 @@ +#include "vec.h" +#include +#include +#include + +libds_result vec_init(vec* v){ + libds_result result = SUCCESS; + + v->size = 0; + v->capacity = LIBDS_VEC_CAPACITY; + v->data = calloc(LIBDS_VEC_CAPACITY, sizeof(void*)); + if(v->data == NULL){ + result = MALLOC; + } + + return result; +} +void vec_free(vec* v){ + v->size = 0; + v->capacity = 0; + if(v->data) { + free(v->data); + } + v->data = NULL; +} + +libds_result vec_add(vec* v, void* data){ + libds_result result = SUCCESS; + if(v->size >= v->capacity) { + void* new_mem = calloc(v->capacity *= 2, sizeof(void*)); + if(new_mem) { + memcpy(new_mem, v->data, sizeof(void*) * v->capacity / 2); + free(v->data); + v->data = new_mem; + } else { + result = MALLOC; + } + } + + if(result == SUCCESS) { + int index = 0; + while(index < v->capacity) { + void** data_array = v->data; + if(data_array[index] == NULL) { + data_array[index] = data; + v->size++; + break; + } + index++; + } + } + + return result; +} +void vec_remove(vec* v, void* data){ + int elements = v->size; + int index = 0; + void** data_array = v->data; + while(elements > 0) { + if(data_array[index]) { + elements--; + if(data_array[index] == data) { + data_array[index] = NULL; + v->size--; + } + } + index++; + } +} + +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; + while(elements > 0 && found == NULL){ + if(data_array[index]){ + if(compare(data, data_array[index])){ + found = data_array[index]; + } + elements--; + } + index++; + } + return found; +} +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; + while(elements > 0 && return_code == 0) { + if(data_array[index]){ + if(compare(data, data_array[index])){ + va_start(args, foreach); + return_code = foreach(data_array[index], args); + va_end(args); + } + elements--; + } + index++; + } + return return_code; +}