2017-01-21 01:20:00 -08:00
|
|
|
#include "sprs.h"
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
void sprs_init(sprs* sprs){
|
|
|
|
sprs->capacity = 0;
|
|
|
|
sprs->size = 0;
|
|
|
|
sprs->dense = NULL;
|
|
|
|
sprs->sparse = NULL;
|
|
|
|
}
|
2017-07-20 21:32:36 -07:00
|
|
|
libds_result sprs_setup(sprs* sprs, size_t size){
|
2017-01-21 01:20:00 -08:00
|
|
|
libds_result result = LIBDS_SUCCESS;
|
|
|
|
sprs->sparse = malloc(sizeof(*(sprs->sparse)) * size);
|
|
|
|
sprs->dense = malloc(sizeof(*(sprs->dense)) * size);
|
|
|
|
if(sprs->sparse == NULL || sprs->dense == NULL){
|
|
|
|
free(sprs->sparse);
|
|
|
|
free(sprs->dense);
|
2017-05-05 19:48:23 -07:00
|
|
|
sprs->sparse = NULL;
|
|
|
|
sprs->dense = NULL;
|
2017-01-21 01:20:00 -08:00
|
|
|
result = LIBDS_MALLOC;
|
|
|
|
} else {
|
|
|
|
sprs->capacity = size;
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
void sprs_free(sprs* sprs){
|
|
|
|
free(sprs->sparse);
|
|
|
|
free(sprs->dense);
|
|
|
|
sprs->capacity = 0;
|
|
|
|
sprs->size = 0;
|
|
|
|
sprs->dense = NULL;
|
|
|
|
sprs->sparse = NULL;
|
|
|
|
}
|
2017-07-21 17:45:04 -07:00
|
|
|
void sprs_put(sprs* sprs, size_t index, void* data){
|
2017-01-21 01:20:00 -08:00
|
|
|
if(index < sprs->capacity && sprs->size < sprs->capacity){
|
|
|
|
sprs->dense[sprs->size++] = index;
|
|
|
|
sprs->sparse[index].index = sprs->size - 1;
|
|
|
|
sprs->sparse[index].data = data;
|
|
|
|
}
|
|
|
|
}
|
2017-07-21 17:45:04 -07:00
|
|
|
int sprs_contains(sprs* sprs, size_t index){
|
|
|
|
return sprs->sparse[index].index < sprs->size && sprs->dense[sprs->sparse[index].index] == index;
|
2017-01-21 01:20:00 -08:00
|
|
|
}
|
2017-07-21 17:45:04 -07:00
|
|
|
void* sprs_get(sprs* sprs, size_t index){
|
2017-01-21 01:20:00 -08:00
|
|
|
void* data = NULL;
|
|
|
|
if(sprs_contains(sprs, index)){
|
|
|
|
data = sprs->sparse[index].data;
|
|
|
|
}
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
void* sprs_find(sprs* sprs, void* data, compare_func compare){
|
|
|
|
int index = 0;
|
|
|
|
void* to_return = NULL;
|
|
|
|
for(; index < sprs->size && to_return == NULL; index++){
|
|
|
|
if(compare(data, sprs->sparse[sprs->dense[index]].data)) {
|
|
|
|
to_return = sprs->sparse[sprs->dense[index]].data;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return to_return;
|
|
|
|
}
|
|
|
|
int sprs_foreach(sprs* sprs, void* data, compare_func compare, foreach_func foreach, ...){
|
|
|
|
int index = 0;
|
|
|
|
int return_code = 0;
|
|
|
|
va_list args;
|
|
|
|
for(; index < sprs->size && return_code == 0; index++){
|
|
|
|
if(compare(data, sprs->sparse[sprs->dense[index]].data)) {
|
|
|
|
va_start(args, foreach);
|
|
|
|
return_code = foreach(sprs->sparse[sprs->dense[index]].data, args);
|
|
|
|
va_end(args);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return return_code;
|
|
|
|
}
|