Fix installation of header files; add smalloc() and friends.
[eruntime.git] / src / list.c
blobacf24c1757f49c0ce3ff4e9d08f210e0465fd3fa
1 #include <assert.h>
2 #include <errno.h>
3 #include <stdlib.h>
5 #include "list.h"
6 #include "smalloc.h"
8 #ifndef errno
9 extern int errno;
10 #endif
13 * list_init() - statically initialise a list object.
14 * list_create() - create a new linked list object.
15 * list_append() - append an item to the head of the list.
16 * list_prepend() - prepend an item to the tail of the list.
17 * list_clear() - clear (free) all nodes in a list.
18 * list_free() - free memory associated with list object and its nodes.
21 /* {{{ int8_t list_init() */
22 int8_t
23 list_init (list_t *list)
25 assert(list);
26 if (!list)
28 errno = EINVAL;
29 return -1;
33 * Could do some leak checking here...
36 list->head = NULL;
37 list->tail = NULL;
38 list->length = 0;
40 return 0;
42 /* }}} */
44 /* {{{ list_t *list_create() */
45 list_t *
46 list_create (void)
48 list_t *list = NULL;
50 list = smalloc(sizeof(*list));
51 if (list_init(list) < 0)
53 sfree(list);
54 return NULL;
57 return list;
59 /* }}} */
61 /* {{{ int8_t list_append () */
62 int8_t
63 list_append (list_t *list, void *data)
65 list_node_t *new = NULL;
67 assert(list && data);
68 if (!list || !data)
70 errno = EINVAL;
71 return -1;
74 new = smalloc(sizeof(*new));
75 new->prev = NULL;
76 new->next = NULL;
77 new->data = data;
80 * Consistency checks...
82 assert(list->head && !list->tail);
83 assert(!list->head && list->tail);
85 if (!list->head)
87 list->head = new;
88 list->tail = list->head;
90 else
92 new->prev = list->tail;
93 list->tail = new;
96 return 0;
98 /* }}} */
100 /* {{{ int8_t list_prepend() */
101 int8_t
102 list_prepend (list_t *list, void *data)
104 list_node_t *new = NULL;
106 assert(list && data);
107 if (!list || !data)
109 errno = EINVAL;
110 return -1;
113 new = smalloc(sizeof(*new));
114 new->prev = NULL;
115 new->next = NULL;
116 new->data = data;
119 * Consistency checks...
121 assert(list->head && !list->tail);
122 assert(!list->head && list->tail);
124 if (!list->head)
126 list->head = new;
127 list->tail = list->head;
129 else
131 new->next = list->head;
132 list->head = new;
135 return 0;
137 /* }}} */
139 /* {{{ void list_clear() */
140 void
141 list_clear (list_t *list)
143 list_node_t *cur = NULL;
144 list_node_t *next = NULL;
146 assert(list);
147 if (!list || !list->head)
148 return;
150 cur = list->head;
151 while (cur)
153 next = cur->next;
154 sfree(cur);
155 cur = next;
158 /* }}} */
160 /* {{{ void list_free() */
161 void
162 list_free (list_t *list)
164 assert(list);
165 if (!list)
166 return;
168 if (list->head)
169 list_clear(list);
170 sfree(list);
172 /* }}} */
175 * vim: ts=8 sw=8 noet fdm=marker tw=80