103 lines
2.3 KiB
C
103 lines
2.3 KiB
C
#include "vec.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
libds_result vec_init(vec* v) {
|
|
libds_result result = LIBDS_SUCCESS;
|
|
|
|
v->size = 0;
|
|
v->capacity = LIBDS_VEC_CAPACITY;
|
|
v->data = malloc(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 = malloc((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) {
|
|
((void**) v->data)[v->size++] = data;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
void vec_remove(vec* v, void* data) {
|
|
size_t index = 0;
|
|
void** data_array = v->data;
|
|
while (index < v->size && data_array[index]) {
|
|
size_t search_ahead = 0;
|
|
while(data_array[index + search_ahead] == data){
|
|
search_ahead++;
|
|
}
|
|
|
|
if(search_ahead){
|
|
size_t remaining_elements = v->size - (index + search_ahead);
|
|
memmove(data_array + index, data_array + index + search_ahead, remaining_elements);
|
|
v->size -= search_ahead;
|
|
}
|
|
index++;
|
|
}
|
|
}
|
|
|
|
void* vec_find(const vec* v, void* data, compare_func compare) {
|
|
size_t index = 0;
|
|
void* found = NULL;
|
|
void** data_array = v->data;
|
|
while (index < v->size && found == NULL) {
|
|
if (data_array[index] && compare(data, data_array[index])) {
|
|
found = data_array[index];
|
|
}
|
|
index++;
|
|
}
|
|
return found;
|
|
}
|
|
int vec_foreach(const vec* v, void* data, compare_func compare, foreach_func foreach,
|
|
...) {
|
|
size_t index = 0;
|
|
int return_code = 0;
|
|
void** data_array = v->data;
|
|
va_list args;
|
|
while (index < v->size && return_code == 0) {
|
|
if (data_array[index] && compare(data, data_array[index])) {
|
|
va_start(args, foreach);
|
|
return_code = foreach (data_array[index], args);
|
|
va_end(args);
|
|
}
|
|
index++;
|
|
}
|
|
return return_code;
|
|
}
|
|
|
|
void* vec_index(const vec* v, size_t index) {
|
|
void* to_return = NULL;
|
|
if (index < v->capacity) {
|
|
to_return = ((void**) v->data)[index];
|
|
}
|
|
return to_return;
|
|
}
|
|
void vec_clear(vec* vec) {
|
|
vec->size = 0;
|
|
}
|