OSDN Git Service

9b6c29504f8618749d839e1729a1bc054da45f40
[android-x86/external-toybox.git] / lib / llist.c
1 /* llist.c - Linked list functions
2  *
3  * Linked list structures have a next pointer as their first element.
4  */
5
6 #include "toys.h"
7
8 // Call a function (such as free()) on each element of a linked list.
9 void llist_traverse(void *list, void (*using)(void *data))
10 {
11   while (list) {
12     void *pop = llist_pop(&list);
13     using(pop);
14
15     // End doubly linked list too.
16     if (list==pop) break;
17   }
18 }
19
20 // Return the first item from the list, advancing the list (which must be called
21 // as &list)
22 void *llist_pop(void *list)
23 {
24   // I'd use a void ** for the argument, and even accept the typecast in all
25   // callers as documentation you need the &, except the stupid compiler
26   // would then scream about type-punned pointers.  Screw it.
27   void **llist = (void **)list;
28   void **next = (void **)*llist;
29   *llist = *next;
30
31   return (void *)next;
32 }
33
34 void dlist_add_nomalloc(struct double_list **list, struct double_list *new)
35 {
36   if (*list) {
37     new->next = *list;
38     new->prev = (*list)->prev;
39     (*list)->prev->next = new;
40     (*list)->prev = new;
41   } else *list = new->next = new->prev = new;
42 }
43
44
45 // Add an entry to the end of a doubly linked list
46 struct double_list *dlist_add(struct double_list **list, char *data)
47 {
48   struct double_list *new = xmalloc(sizeof(struct double_list));
49
50   new->data = data;
51   dlist_add_nomalloc(list, new);
52
53   return new;
54 }