wmail: handle allocation failures.
[dockapps.git] / wmradio / lists.c
blobad111794b4eb8dedeb9ad103d0511a8ef33121d5
1 #include "lists.h"
2 #include <string.h>
4 List *list_new_item()
6 List *item;
7 item = (List *)malloc(sizeof(List));
8 if(item) memset(item, 0, sizeof(List));
9 return item;
12 List *list_last(List *list)
14 List *item;
16 item = list;
17 if(!item) return NULL;
18 while(item->next) item = item->next;
19 return item;
22 List *list_add(List *list, List *newitem)
24 List *lastitem;
26 if(!newitem) return list;
27 if(!list) return newitem;
29 lastitem = list_last(list);
30 lastitem -> next = newitem;
31 newitem -> prev = lastitem;
33 return list;
36 List *list_add_data(List *list, void *data)
38 List *newitem;
40 newitem = list_new_item();
41 if(!newitem) return list;
42 list = list_add(list,newitem);
43 newitem -> data = data;
44 return list;
47 List *list_node_with_data(List *list, void *data)
49 List *item;
51 item = list;
52 while(item) {
53 if(item->data == data) return item;
54 item = item->next;
56 return NULL;
59 int list_length(List *list)
61 int l = 0;
62 List *item;
64 if(!list) return 0;
65 item = list;
66 while(item) {
67 l++;
68 item = item->next;
70 return l;
73 List *list_nth_node(List *list, int index)
75 List *item;
76 int i;
78 item = list;
79 i = 0;
80 while(item) {
81 if( i == index ) return item;
82 i++;
83 item = item->next;
85 return NULL;
88 List *list_remove_node(List *list, List *node)
90 List *prev,*next;
92 if(!list) return list;
93 if(!node) return list;
95 prev = node ->prev;
96 next = node ->next;
97 node -> next = NULL;
98 node -> prev = NULL;
99 if(prev) prev->next = next;
100 if(next) next->prev = prev;
101 if(prev) return list;
102 return prev;
105 List *list_delete_node(List *list, List *node)
107 list = list_remove_node(list,node);
108 free(node);
109 return list;
112 void list_for_each(List *list, list_for_each_function func, void *data)
114 List *item = list;
116 if(!list) return;
117 if(!func) return;
119 while(item) {
120 if( func(item, data) ) return;
121 item = item -> next;
125 void list_free(List *list)
127 List *item, *prev;
129 item = list_last(list);
131 while(item) {
132 prev = item->prev;
133 free(item);
134 item = prev;
138 int list_has_node(List *list, List *node)
140 List *i;
142 for(i=list; i ; i = i->next) {
143 if( i == node ) return 1;
145 return 0;