From 7113b53caa314b143c25623acd92827bcb9380b2 Mon Sep 17 00:00:00 2001 From: lisk77 Date: Wed, 27 Aug 2025 01:22:18 +0200 Subject: [PATCH] feat(utilities): added the List struct for a general purpose dynamic array --- include/utilities.h | 11 +++++++++++ src/utilities.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/include/utilities.h b/include/utilities.h index de18086..a48d0ba 100644 --- a/include/utilities.h +++ b/include/utilities.h @@ -18,6 +18,8 @@ #define GREEN_BG "\033[42m" #define BLACK_FG "\033[30m" +#define LIST_INIT_CAPACITY 4 + typedef enum { PT_NOEXIST, PT_FILE, @@ -26,6 +28,15 @@ typedef enum { PT_ERROR } PathType; +typedef struct { + void** items; + size_t len; + size_t capacity; + size_t item_size; +} List; + +List* list_new(size_t); +int list_push(List*, void*); PathType get_path_type(const char*); void visualize_diff(File*, File*, ActionList*); void cut_path(char* base, char* path); diff --git a/src/utilities.c b/src/utilities.c index 686feaa..24c2f89 100644 --- a/src/utilities.c +++ b/src/utilities.c @@ -1,5 +1,37 @@ #include "utilities.h" +List* list_new(size_t item_size) { + List* list = calloc(1, sizeof(List)); + if (!list) { perror("ERROR: memory allocation in new_list failed!"); return NULL; } + + list->items = calloc(LIST_INIT_CAPACITY, item_size); + if (!list->items) { perror("ERROR: memory allocation in new_list failed!"); free(list); return NULL; } + + list->len = 0; + list->capacity = LIST_INIT_CAPACITY; + list->item_size = item_size; + return list; +} + +int list_push(List* list, void* item) { + if (!list || !item) return 0; + + if (list->len == list->capacity) { + size_t new_capacity = list->capacity * 2; + void* new_items = realloc(list->items, new_capacity * list->item_size); + if (!new_items) { perror("ERROR: memory reallocation failed in list_push!"); return 0; } + + list->items = new_items; + list->capacity = new_capacity; + } + + char* dest = (char*)list->items + (list->len * list->item_size); + memcpy(dest, item, list->item_size); + list->len++; + + return 1; +} + PathType get_path_type(const char* path) { struct stat st; int rc = stat(path, &st);