1
2
3
4
5
6#include "toys.h"
7
8
9
10void llist_free_arg(void *node)
11{
12 struct arg_list *d = node;
13
14 free(d->arg);
15 free(d);
16}
17
18void llist_free_double(void *node)
19{
20 struct double_list *d = node;
21
22 free(d->data);
23 free(d);
24}
25
26
27void llist_traverse(void *list, void (*using)(void *node))
28{
29 void *old = list;
30
31 while (list) {
32 void *pop = llist_pop(&list);
33 using(pop);
34
35
36 if (old == list) break;
37 }
38}
39
40
41
42void *llist_pop(void *list)
43{
44
45
46
47 void **llist = (void **)list;
48 void **next = (void **)*llist;
49 *llist = *next;
50
51 return (void *)next;
52}
53
54
55void *dlist_pop(void *list)
56{
57 struct double_list **pdlist = (struct double_list **)list, *dlist = *pdlist;
58
59 if (!dlist) return 0;
60 if (dlist->next == dlist) *pdlist = 0;
61 else {
62 if (dlist->next) dlist->next->prev = dlist->prev;
63 if (dlist->prev) dlist->prev->next = dlist->next;
64 *pdlist = dlist->next;
65 }
66
67 return dlist;
68}
69
70
71void *dlist_lpop(void *list)
72{
73 struct double_list *dl = *(struct double_list **)list;
74 void *v = 0;
75
76 if (dl) {
77 dl = dl->prev;
78 v = dlist_pop(&dl);
79 if (!dl) *(void **)list = 0;
80 }
81
82 return v;
83}
84
85
86void dlist_add_nomalloc(struct double_list **list, struct double_list *new)
87{
88 if (*list) {
89 new->next = *list;
90 new->prev = (*list)->prev;
91 (*list)->prev->next = new;
92 (*list)->prev = new;
93 } else *list = new->next = new->prev = new;
94}
95
96
97struct double_list *dlist_add(struct double_list **list, char *data)
98{
99 struct double_list *new = xmalloc(sizeof(struct double_list));
100
101 new->data = data;
102 dlist_add_nomalloc(list, new);
103
104 return new;
105}
106
107
108void *dlist_terminate(void *list)
109{
110 struct double_list *end = list;
111
112 if (!end || !end->prev) return 0;
113
114 end = end->prev;
115 end->next->prev = 0;
116 end->next = 0;
117
118 return end;
119}
120
121
122struct num_cache *get_num_cache(struct num_cache *cache, long long num)
123{
124 while (cache) {
125 if (num==cache->num) return cache;
126 cache = cache->next;
127 }
128
129 return 0;
130}
131
132
133
134struct num_cache *add_num_cache(struct num_cache **cache, long long num,
135 void *data, int len)
136{
137 struct num_cache *old = get_num_cache(*cache, num);
138
139 if (old) return old;
140
141 old = xzalloc(sizeof(struct num_cache)+len);
142 old->next = *cache;
143 old->num = num;
144 memcpy(old->data, data, len);
145 *cache = old;
146
147 return 0;
148}
149