2018-03-31 20:44:01 -07:00
|
|
|
#include "ref_vec.h"
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
libab_result libab_ref_vec_init(libab_ref_vec* vec) {
|
|
|
|
libab_result result = LIBAB_SUCCESS;
|
|
|
|
vec->capacity = LIBABACUS_REF_VEC_INITIAL_SIZE;
|
|
|
|
vec->size = 0;
|
2018-04-21 14:09:01 -07:00
|
|
|
vec->data = malloc(sizeof(*vec->data) * LIBABACUS_REF_VEC_INITIAL_SIZE);
|
|
|
|
if (vec->data == NULL) {
|
2018-03-31 20:44:01 -07:00
|
|
|
result = LIBAB_MALLOC;
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
libab_result _libab_ref_vec_try_resize(libab_ref_vec* vec) {
|
|
|
|
libab_result result = LIBAB_SUCCESS;
|
2018-04-21 14:09:01 -07:00
|
|
|
if (vec->size == vec->capacity) {
|
|
|
|
libab_ref* new_memory =
|
|
|
|
realloc(vec->data, (vec->capacity *= 2) * sizeof(*vec->data));
|
|
|
|
if (new_memory == NULL) {
|
2018-03-31 20:44:01 -07:00
|
|
|
free(vec->data);
|
|
|
|
result = LIBAB_MALLOC;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
libab_result libab_ref_vec_insert(libab_ref_vec* vec, libab_ref* data) {
|
|
|
|
libab_result result = _libab_ref_vec_try_resize(vec);
|
|
|
|
|
2018-04-21 14:09:01 -07:00
|
|
|
if (result == LIBAB_SUCCESS) {
|
2018-03-31 20:44:01 -07:00
|
|
|
libab_ref_copy(data, &vec->data[vec->size++]);
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2018-04-21 14:09:01 -07:00
|
|
|
libab_result libab_ref_vec_insert_value(libab_ref_vec* vec, void* data,
|
|
|
|
void (*free_func)(void*)) {
|
2018-03-31 20:44:01 -07:00
|
|
|
libab_result result = _libab_ref_vec_try_resize(vec);
|
|
|
|
|
2018-04-21 14:09:01 -07:00
|
|
|
if (result == LIBAB_SUCCESS) {
|
2018-03-31 20:44:01 -07:00
|
|
|
result = libab_ref_new(&vec->data[vec->size], data, free_func);
|
|
|
|
}
|
|
|
|
|
2018-04-21 14:09:01 -07:00
|
|
|
if (result == LIBAB_SUCCESS) {
|
2018-03-31 20:44:01 -07:00
|
|
|
vec->size++;
|
|
|
|
}
|
2018-04-21 14:09:01 -07:00
|
|
|
|
2018-03-31 20:44:01 -07:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
const libab_ref* libab_ref_vec_index(libab_ref_vec* vec, size_t index) {
|
|
|
|
const libab_ref* to_return = NULL;
|
2018-04-21 14:09:01 -07:00
|
|
|
if (index < vec->size) {
|
2018-03-31 20:44:01 -07:00
|
|
|
to_return = &vec->data[index];
|
|
|
|
}
|
|
|
|
return to_return;
|
|
|
|
}
|
|
|
|
|
|
|
|
void libab_ref_vec_free(libab_ref_vec* vec) {
|
|
|
|
size_t i = 0;
|
2018-04-21 14:09:01 -07:00
|
|
|
for (; i < vec->size; i++) {
|
2018-03-31 20:44:01 -07:00
|
|
|
libab_ref_free(&vec->data[i]);
|
|
|
|
}
|
|
|
|
free(vec->data);
|
|
|
|
}
|