refactor: make list more generic
This commit is contained in:
65
list.h
Normal file
65
list.h
Normal file
@@ -0,0 +1,65 @@
|
||||
//
|
||||
// Created by Lennart on 02/12/2023.
|
||||
//
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef LIST_NAME
|
||||
#define LIST_NAME List
|
||||
#endif //LIST_NAME
|
||||
|
||||
#ifndef LIST_PREFIX
|
||||
#define LIST_PREFIX list
|
||||
#endif //LIST_PREFIX
|
||||
|
||||
#ifndef ELEMENT_TYPE
|
||||
#define ELEMENT_TYPE void*
|
||||
#endif //ELEMENT_TYPE
|
||||
|
||||
#define LIST_CONCAT(x, y) x ## _ ## y
|
||||
#define LIST_FN(name) LIST_CONCAT(LIST_PREFIX, name)
|
||||
|
||||
typedef struct {
|
||||
ELEMENT_TYPE *data;
|
||||
int capacity;
|
||||
int length;
|
||||
} LIST_NAME;
|
||||
|
||||
__inline LIST_NAME* LIST_FN(create)(int capacity) {
|
||||
LIST_NAME *alist = malloc(sizeof (LIST_NAME));
|
||||
alist->data = malloc(sizeof (ELEMENT_TYPE) * capacity);
|
||||
alist->capacity = capacity;
|
||||
alist->length = 0;
|
||||
return alist;
|
||||
}
|
||||
|
||||
__inline void LIST_FN(add)(LIST_NAME *alist, ELEMENT_TYPE value) {
|
||||
if(alist->length >= alist->capacity) {
|
||||
alist->data = realloc(alist->data, alist->capacity * 2);
|
||||
alist->capacity = alist->capacity * 2;
|
||||
}
|
||||
|
||||
alist->data[alist->length++] = value;
|
||||
}
|
||||
|
||||
__inline void LIST_FN(remove)(LIST_NAME *alist, int index) {
|
||||
#ifdef LIST_UNORDERED
|
||||
alist->data[index] = alist->data[--alist->length];
|
||||
#else
|
||||
memmove(&alist->data[index], &alist->data[index + 1], sizeof(ELEMENT_TYPE) * (alist->capacity - index - 1));
|
||||
alist->length--;
|
||||
#endif //LIST_UNORDERED
|
||||
}
|
||||
|
||||
__inline void LIST_FN(free)(LIST_NAME *alist) {
|
||||
free(alist->data);
|
||||
free(alist);
|
||||
}
|
||||
|
||||
#undef LIST_NAME
|
||||
#undef LIST_PREFIX
|
||||
#undef ELEMENT_TYPE
|
||||
#undef LIST_CONCAT
|
||||
#undef LIST_FN
|
||||
#undef LIST_UNORDERED
|
||||
Reference in New Issue
Block a user