/*
* Copyright 2021 Jeisson Hidalgo-Cespedes - Universidad de Costa Rica
*/
#include <assert.h>
#include <stdlib.h>
#include "array.h"
int array_increase_capacity(array_t* array);
int array_init(array_t* array) {
assert(array);
array->capacity = 10;
array->count = 0;
array->elements = calloc(array->capacity, sizeof(data_t));
return array->elements == NULL;
}
void array_destroy(array_t* array) {
assert(array);
array->capacity = 0;
array->count = 0;
free(array->elements);
array->elements = NULL;
}
int array_append(array_t* array, data_t data) {
assert(array);
int error = EXIT_SUCCESS;
if (array->count == array->capacity) {
error = array_increase_capacity(array);
}
if (error == EXIT_SUCCESS) {
array->elements[array->count++] = data;
}
return error;
}
int array_increase_capacity(array_t* array) {
assert(array);
int error = EXIT_SUCCESS;
size_t new_capacity = 10 * array->capacity;
data_t* new_array = realloc(array->elements, new_capacity * sizeof(data_t));
if (new_array) {
array->capacity = new_capacity;
array->elements = new_array;
} else {
error = EXIT_FAILURE;
}
return error;
}