feat: added list implementation(not tested yet)
This commit is contained in:
parent
49799466a1
commit
23869d0e8f
3 changed files with 129 additions and 0 deletions
98
core/src/list.c
Normal file
98
core/src/list.c
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
#include "list.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
list_t *list_init(size_t type_size, size_t capacity) {
|
||||
list_t *list;
|
||||
|
||||
list = calloc(1, sizeof(list_t));
|
||||
if (!list) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
list->real_capacity = capacity * 2;
|
||||
|
||||
list->data = calloc(1, sizeof(type_size * list->real_capacity));
|
||||
if (!list) {
|
||||
free(list);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
list->capacity = capacity;
|
||||
list->type_size = type_size;
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
list_error_e list_get_last_error(list_t *list) {
|
||||
list_error_e error = list->error;
|
||||
|
||||
list->error = LIST_NONE;
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
void list_resize(list_t *list, size_t new_capacity) {
|
||||
void *new_data = calloc(new_capacity * 2, list->type_size);
|
||||
|
||||
if (!new_data) {
|
||||
list->error = LIST_MEM;
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(new_data, list->data, list->type_size * list->capacity);
|
||||
free(list->data);
|
||||
list->data = new_data;
|
||||
}
|
||||
|
||||
void list_append(list_t *list, void *value) {
|
||||
if (list->capacity + 1 > list->real_capacity) {
|
||||
list_resize(list, list->real_capacity * 2);
|
||||
}
|
||||
|
||||
list->capacity++;
|
||||
list_set(list, list->capacity, value);
|
||||
}
|
||||
|
||||
void list_set(list_t *list, size_t idx, void *value) {
|
||||
if (idx > list->capacity) {
|
||||
list->error = LIST_OOR;
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(list->data + (idx * list->type_size), value, list->type_size);
|
||||
}
|
||||
|
||||
void *list_get(list_t *list, size_t idx) {
|
||||
if (idx <= list->capacity) {
|
||||
return &list->data[idx];
|
||||
}
|
||||
|
||||
list->error = LIST_OOR;
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void list_remove(list_t *list, size_t idx) {
|
||||
if (idx > list->capacity) {
|
||||
list->error = LIST_OOR;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (idx == list->capacity) {
|
||||
list->capacity -= 1;
|
||||
}
|
||||
|
||||
if (idx < list->capacity) {
|
||||
memcpy(list->data + (idx * list->type_size),
|
||||
list->data + ((idx + 1) * list->type_size),
|
||||
(list->capacity - idx) * list->type_size);
|
||||
}
|
||||
}
|
||||
|
||||
void list_deinit(list_t *list) {
|
||||
free(list->data);
|
||||
free(list);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue