#include"lexlib/linkedList.h"
#include<stdlib.h>
#include<string.h>
struct LexlibLinkedList lexlibLinkedListNew(void){
return (struct LexlibLinkedList){
.head = NULL,
.count = 0,
};
}
void lexlibLinkedListDelete(struct LexlibLinkedList* list){
typeof(list->head) curr = list->head;
typeof(list->head)* all = calloc(list->count, sizeof(list->head));
for(size_t i = 0; ;i++){
if(!curr)
break;
all[i] = curr;
curr = curr->next;
}
for(size_t i = 0; i < list->count; i++){
free(all[i]);
}
free(all);
list->head = NULL;
list->count = 0;
}
void lexlibLinkedListFree(struct LexlibLinkedList* list){
LexlibLinkedNode* curr = list->head;
LexlibLinkedNode* old = list->head;
for(size_t i = 0; ;i++){
if(!curr)
break;
if(curr->data)
free(curr->data);
old = curr;
curr = curr->next;
free(old);
}
list->head = NULL;
list->count = 0;
}
uint8_t lexlibLinkedListAdd(struct LexlibLinkedList* list, void* data){
struct LexlibLinkedNode* node = malloc(sizeof(struct LexlibLinkedNode));
if(!node)
return 1;
node->data = data;
node->next = NULL;
if(list->head){
typeof(list->head) newMem = realloc(list->head, (list->count+1) * sizeof(LexlibLinkedNode*));
if(!newMem)
return 1;
list->head = newMem;
}
if(list->count == 0){
list->head = node;
} else {
struct LexlibLinkedNode* curr = list->head;
while(1){
if(curr->next == NULL){
curr->next = node;
break;
}
curr = curr->next;
}
}
list->count++;
return 0;
}
void* lexlibLinkedListGet(struct LexlibLinkedList* list, size_t index){
if(index >= list->count)
return NULL;
typeof(list->head) curr = list->head;
for(size_t i = 0; i < index; i++)
curr = curr->next;
return curr->data;
}
uint8_t lexlibLinkedListAddCopy(struct LexlibLinkedList* list, void* data, size_t dataSize){
void* newData = malloc(dataSize);
if(!newData)
return 1;
memcpy(newData, data, dataSize);
return lexlibLinkedListAdd(list, newData);
}