feat(utilities): added the List struct for a general purpose dynamic array

This commit is contained in:
lisk77 2025-08-27 01:22:18 +02:00
parent 5b134edac6
commit 7113b53caa
2 changed files with 43 additions and 0 deletions

View file

@ -18,6 +18,8 @@
#define GREEN_BG "\033[42m" #define GREEN_BG "\033[42m"
#define BLACK_FG "\033[30m" #define BLACK_FG "\033[30m"
#define LIST_INIT_CAPACITY 4
typedef enum { typedef enum {
PT_NOEXIST, PT_NOEXIST,
PT_FILE, PT_FILE,
@ -26,6 +28,15 @@ typedef enum {
PT_ERROR PT_ERROR
} PathType; } 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*); PathType get_path_type(const char*);
void visualize_diff(File*, File*, ActionList*); void visualize_diff(File*, File*, ActionList*);
void cut_path(char* base, char* path); void cut_path(char* base, char* path);

View file

@ -1,5 +1,37 @@
#include "utilities.h" #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) { PathType get_path_type(const char* path) {
struct stat st; struct stat st;
int rc = stat(path, &st); int rc = stat(path, &st);