work on type inference some more
[ccc.git] / list.c
1 #include <stdlib.h>
2 #include <stdbool.h>
3
4 #include "list.h"
5 #include "util.h"
6
7 struct list *list_append(void *el, struct list *head)
8 {
9 if (head == NULL)
10 return list_cons(el, NULL);
11 struct list *tail = head;
12 while (tail->tail != NULL)
13 tail = tail->tail;
14 tail->tail = list_cons(el, NULL);
15 return head;
16 }
17
18 struct list *list_cons(void *el, struct list *tail)
19 {
20 struct list *res = safe_malloc(sizeof(struct list));
21 res->el = el;
22 res->tail = tail;
23 return res;
24 }
25
26 void list_free(struct list *head, void (*freefun)(void *))
27 {
28 while (head != NULL) {
29 struct list *t = head;
30 if (freefun != NULL)
31 freefun(head->el);
32 head = head->tail;
33 free(t);
34 }
35 }
36
37 void **list_to_array(struct list *list, int *num, bool reverse)
38 {
39 int i = list_length(list);
40 *num = i;
41 void **ptr = safe_malloc(i*sizeof(void *));
42
43 struct list *r = list;
44 while(i > 0) {
45 if (reverse)
46 ptr[--i] = r->el;
47 else
48 ptr[*num-(--i)-1] = r->el;
49 struct list *t = r;
50 r = r->tail;
51 free(t);
52 }
53 return ptr;
54 }
55
56 int list_length(struct list *r)
57 {
58 int i = 0;
59 FOREACH(e, r)
60 i++;
61 return i;
62 }