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