1
1
mirror of https://github.com/theoludwig/libcproject.git synced 2024-12-11 21:13:00 +01:00

perf: allow to init array_list with initial capacity

Fixes #8
This commit is contained in:
Théo LUDWIG 2024-09-25 14:34:33 +02:00
parent 51d7123c8d
commit 1be12c2a97
Signed by: theoludwig
GPG Key ID: ADFE5A563D718F3B
2 changed files with 16 additions and 4 deletions

View File

@ -1,25 +1,30 @@
#include "array_list.h"
struct array_list* array_list_initialization() {
return array_list_initialization_with_capacity(ARRAY_LIST_INITIAL_CAPACITY);
}
struct array_list* array_list_initialization_with_capacity(size_t capacity) {
struct array_list* list = malloc(sizeof(struct array_list));
if (list == NULL) {
perror("Error (array_list_initialization)");
exit(EXIT_FAILURE);
}
list->data = malloc(sizeof(void*) * ARRAY_LIST_INITIAL_CAPACITY);
list->size = 0;
list->capacity = capacity;
list->capacity_step = capacity;
list->data = malloc(sizeof(void*) * list->capacity);
if (list->data == NULL) {
perror("Error (array_list_initialization)");
exit(EXIT_FAILURE);
}
list->size = 0;
list->capacity = ARRAY_LIST_INITIAL_CAPACITY;
return list;
}
void array_list_add(struct array_list* list, void* element) {
if (list->size >= list->capacity) {
size_t previous_capacity = list->capacity;
list->capacity += ARRAY_LIST_INITIAL_CAPACITY;
list->capacity += list->capacity_step;
list->data = realloc(list->data, sizeof(void*) * list->capacity);
if (list->data == NULL) {
perror("Error (array_list_add)");

View File

@ -18,6 +18,7 @@ struct array_list {
void** data;
size_t size;
size_t capacity;
size_t capacity_step;
};
/**
@ -26,6 +27,12 @@ struct array_list {
*/
struct array_list* array_list_initialization();
/**
* @brief Initializes a new array list with a capacity.
* @since v5.0.0
*/
struct array_list* array_list_initialization_with_capacity(size_t capacity);
/**
* @brief Adds an element to the end of the array list.
*