diff options
Diffstat (limited to 'common/list.c')
-rw-r--r-- | common/list.c | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/common/list.c b/common/list.c new file mode 100644 index 00000000..45efc16f --- /dev/null +++ b/common/list.c | |||
@@ -0,0 +1,55 @@ | |||
1 | #include "list.h" | ||
2 | #include <stdio.h> | ||
3 | #include <stdlib.h> | ||
4 | #include <string.h> | ||
5 | |||
6 | list_t *create_list(void) { | ||
7 | list_t *list = malloc(sizeof(list_t)); | ||
8 | list->capacity = 10; | ||
9 | list->length = 0; | ||
10 | list->items = malloc(sizeof(void*) * list->capacity); | ||
11 | return list; | ||
12 | } | ||
13 | |||
14 | static void list_resize(list_t *list) { | ||
15 | if (list->length == list->capacity) { | ||
16 | list->capacity += 10; | ||
17 | list->items = realloc(list->items, sizeof(void*) * list->capacity); | ||
18 | } | ||
19 | } | ||
20 | |||
21 | void list_free(list_t *list) { | ||
22 | if (list == NULL) { | ||
23 | return; | ||
24 | } | ||
25 | free(list->items); | ||
26 | free(list); | ||
27 | } | ||
28 | |||
29 | void list_add(list_t *list, void *item) { | ||
30 | list_resize(list); | ||
31 | list->items[list->length++] = item; | ||
32 | } | ||
33 | |||
34 | void list_insert(list_t *list, int index, void *item) { | ||
35 | list_resize(list); | ||
36 | memmove(&list->items[index + 1], &list->items[index], sizeof(void*) * (list->length - index)); | ||
37 | list->length++; | ||
38 | list->items[index] = item; | ||
39 | } | ||
40 | |||
41 | void list_del(list_t *list, int index) { | ||
42 | list->length--; | ||
43 | memmove(&list->items[index], &list->items[index + 1], sizeof(void*) * (list->length - index)); | ||
44 | } | ||
45 | |||
46 | void list_cat(list_t *list, list_t *source) { | ||
47 | int i; | ||
48 | for (i = 0; i < source->length; ++i) { | ||
49 | list_add(list, source->items[i]); | ||
50 | } | ||
51 | } | ||
52 | |||
53 | void list_sort(list_t *list, int compare(const void *left, const void *right)) { | ||
54 | qsort(list->items, list->length, sizeof(void *), compare); | ||
55 | } | ||