Implement the vector functions specified in the header.

This commit is contained in:
Danila Fedorin 2016-12-20 21:22:22 -08:00
parent 6003b00e36
commit c4ee4853d5
1 changed files with 105 additions and 0 deletions

105
src/vec.c Normal file
View File

@ -0,0 +1,105 @@
#include "vec.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
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;
}