#include "vec.h" #include #include #include libds_result vec_init(vec* v) { libds_result result = LIBDS_SUCCESS; v->size = 0; v->capacity = LIBDS_VEC_CAPACITY; v->data = calloc(LIBDS_VEC_CAPACITY, sizeof(void*)); if (v->data == NULL) { result = LIBDS_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 = LIBDS_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 = LIBDS_MALLOC; } } if (result == LIBDS_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; } void* vec_index(vec* v, int index) { void* to_return = NULL; if (index < v->capacity && index >= 0) { void** data_array = v->data; to_return = data_array[index]; } return to_return; }