]> git.lizzy.rs Git - dragonstd.git/blob - list.c
refactoring + documentation + testing + added Map and Refcount
[dragonstd.git] / list.c
1 #include <stdlib.h> // for malloc, free
2 #include <string.h> // for strcmp
3 #include "bits/wrappers.h"
4 #include "list.h"
5
6 #define ITER_REFS node = &list->fst; *node != NULL; node = &(*node)->nxt
7
8 void list_ini(List *list)
9 {
10         list->fst = NULL;
11         list->end = &list->fst;
12 }
13
14 WRAP_NODE_FUNCTIONS(List, list_)
15
16 void list_apd(List *list, void *dat)
17 {
18         list_nmk(list, list->end, dat);
19 }
20
21 ListNode **list_nfd(List *list, void *key, Comparator cmp)
22 {
23         ListNode **node;
24
25         for (ITER_REFS)
26                 if (cmp((*node)->dat, key) == 0)
27                         return node;
28
29         return node;
30 }
31
32 void list_nmk(List *list, ListNode **node, void *dat)
33 {
34         *node = malloc(sizeof **node);
35         (*node)->dat = dat;
36         (*node)->nxt = NULL;
37
38         if (list->end == node)
39                 list->end = &(*node)->nxt;
40 }
41
42 void list_nrm(List *list, ListNode **node)
43 {
44         ListNode *old = *node;
45         *node = old->nxt;
46
47         if (list->end == &old->nxt)
48                 list->end = node;
49
50         free(old);
51 }
52
53 void list_itr(List *list, Iterator func, void *arg)
54 {
55         LIST_ITERATE(list, node)
56                 func(node->dat, arg);
57 }
58
59 void list_clr(List *list, Iterator func, void *arg)
60 {
61         for (ListNode *node = list->fst; node != NULL;) {
62                 ListNode *next = node->nxt;
63
64                 if (func)
65                         func(node->dat, arg);
66
67                 free(node);
68                 node = next;
69         }
70
71         list_ini(list);
72 }