improved load balancing algorithm.
[l2tpns.git] / ll.c
1 // L2TPNS Linked List Stuff
2
3 #include <stdio.h>
4 #include <sys/file.h>
5 #include <sys/stat.h>
6 #include <malloc.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <time.h>
10 #include <arpa/inet.h>
11 #include <errno.h>
12 #include <unistd.h>
13 #include "ll.h"
14
15 linked_list *ll_init()
16 {
17 return (linked_list *)calloc(sizeof(linked_list), 1);
18 }
19
20 void ll_done(linked_list *l)
21 {
22 li *i = l->head, *n;
23
24 while (i)
25 {
26 n = i->next;
27 free(i);
28 i = n;
29 }
30
31 free(l);
32 }
33
34 li *ll_push(linked_list *l, void *data)
35 {
36 li *i;
37
38 if (!l) return NULL;
39 if (!(i = (li *)calloc(sizeof(li), 1))) return NULL;
40
41 i->data = data;
42 i->next = NULL;
43 if (l->end)
44 l->end->next = i;
45 else
46 l->head = i;
47 l->end = i;
48
49 return i;
50 }
51
52 void *ll_pop(linked_list *l)
53 {
54 li *i;
55 void *data;
56
57 if (!l) return NULL;
58 if (!l->head)
59 return NULL;
60
61 data = l->head->data;
62 i = l->head->next;
63 free(l->head);
64 l->head = i;
65 return data;
66 }
67
68 void ll_iterate(linked_list *l, int(*func)(void *))
69 {
70 li *i;
71 if (!l || !func) return;
72
73 for (i = l->head; i; i = i->next)
74 {
75 if (i->data && !func(i->data))
76 break;
77 }
78 }
79
80 void ll_reset(linked_list *l)
81 {
82 if (!l) return;
83 l->current = NULL;
84 }
85
86 void *ll_next(linked_list *l)
87 {
88 if (!l) return NULL;
89 if (!l->current)
90 l->current = l->head;
91 else
92 l->current = l->current->next;
93 if (!l->current)
94 return NULL;
95 return l->current->data;
96 }
97
98 void ll_delete(linked_list *l, void *data)
99 {
100 li *i = l->head, *p = NULL;
101
102 while (i)
103 {
104 if (i->data == data)
105 {
106 if (l->head == i) l->head = i->next;
107 if (l->end == i) l->end = p;
108 if (p) p->next = i->next;
109 free(i);
110 l->current = NULL;
111 return;
112 }
113 p = i;
114 i = i->next;
115 }
116 }
117
118 int ll_size(linked_list *l)
119 {
120 int count = 0;
121 li *i;
122
123 if (!l) return 0;
124
125 for (i = l->head; i; i = i->next)
126 if (i->data) count++;
127
128 return count;
129 }
130
131 int ll_contains(linked_list *l, void *search)
132 {
133 li *i;
134 for (i = l->head; i; i = i->next)
135 if (i->data == search)
136 return 1;
137 return 0;
138 }
139