logging of replymsg, patch from Arne Schwabe
[libradsec.git] / list.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include "list.h"
4
5 /* allocates and initialises list structure; returns NULL if malloc fails */
6 struct list *list_create() {
7     struct list *list = malloc(sizeof(struct list));
8     if (list)
9         memset(list, 0, sizeof(struct list));
10     return list;
11 }
12
13 /* frees all memory associated with the list */
14 void list_destroy(struct list *list) {
15     struct list_node *node, *next;
16
17     if (!list)
18         return;
19     
20     for (node = list->first; node; node = next) {
21         free(node->data);
22         next = node->next;
23         free(node);
24     }
25     free(list);
26 }
27
28 /* appends entry to list; returns 1 if ok, 0 if malloc fails */
29 int list_push(struct list *list, void *data) {
30     struct list_node *node;
31
32     node = malloc(sizeof(struct list_node));
33     if (!node)
34         return 0;
35     
36     node->next = NULL;
37     node->data = data;
38
39     if (list->first)
40         list->last->next = node;
41     else
42         list->first = node;
43     list->last = node;
44     
45     return 1;
46 }
47
48 /* removes first entry from list and returns data */
49 void *list_shift(struct list *list) {
50     struct list_node *node;
51     void *data;
52     
53     if (!list || !list->first)
54         return NULL;
55     
56     node = list->first;
57     list->first = node->next;
58     if (!list->first)
59         list->last = NULL;
60     data = node->data;
61     free(node);
62     
63     return data;
64 }
65
66 /* removes first entry with matching data pointer */
67 void list_removedata(struct list *list, void *data) {
68     struct list_node *node, *t;
69     
70     if (!list->first)
71         return;
72
73     node = list->first;
74     if (node->data == data) {
75         list->first = node->next;
76         if (!list->first)
77             list->last = NULL;
78         free(node);
79         return;
80     }
81     for (; node->next; node = node->next)
82         if (node->next->data == data) {
83             t = node->next;
84             node->next = node->next->next;
85             if (!node->next) /* we removed the last one */
86                 list->last = node;
87             free(t);
88             return;
89         }
90 }
91
92 /* returns first node */
93 struct list_node *list_first(struct list *list) {
94     return list ? list->first : NULL;
95 }
96
97 /* returns the next node after the argument */
98 struct list_node *list_next(struct list_node *node) {
99     return node->next;
100 }