]> begriffs open source - libderp/blob - src/list.c
Start list stuff
[libderp] / src / list.c
1 #include "list.h"
2
3 #include <assert.h>
4 #include <stdlib.h>
5
6 #ifdef NDEBUG
7         #define CHECK(x) (void)(x)
8 #else
9         #define CHECK(x) _check(x)
10 #endif
11
12 struct list
13 {
14         list_item *head, *tail;
15         void (*elt_dtor)(void *);
16         size_t length;
17 };
18
19 static void
20 _check(const list *l)
21 {
22         assert(l);
23         assert( (!l->head && l->length == 0) ||
24                 ( l->head && l->length != 0) );
25         assert( (!l->head && !l->tail) ||
26                 ( l->head &&  l->tail) );
27 }
28
29 list *
30 l_new(void (*elt_dtor)(void *))
31 {
32         list *l = malloc(sizeof *l);
33         if (!l)
34                 return NULL;
35         *l = (list){.elt_dtor = elt_dtor};
36         CHECK(l);
37         return l;
38 }
39
40 void
41 l_free(list *l)
42 {
43         if (!l)
44                 return;
45         l_clear(l);
46         free(l);
47 }
48
49 size_t
50 l_length(const list *l)
51 {
52         return l ? l->length : 0;
53 }
54
55 bool
56 l_is_empty(const list *l)
57 {
58         return !l || !l->head;
59 }
60
61 list_item *
62 l_first(const list *l)
63 {
64         return l ? l->head : NULL;
65 }
66
67 list_item *
68 l_last(const list *l)
69 {
70         return l ? l->tail : NULL;
71 }
72