100 lines
1.9 KiB
C
100 lines
1.9 KiB
C
#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);
|
|
}
|
|
}
|
|
|
|
size_t list_size(list_t *list) { return list->capacity; }
|
|
|
|
void list_deinit(list_t *list) {
|
|
free(list->data);
|
|
free(list);
|
|
}
|