rewrite to union type, much better
[ccc.git] / util.c
diff --git a/util.c b/util.c
index 1a89f94..4b77f53 100644 (file)
--- a/util.c
+++ b/util.c
@@ -3,6 +3,53 @@
 #include <stdio.h>
 #include <string.h>
 
+#include "util.h"
+
+struct list *list_cons(void *el, struct list *tail)
+{
+       struct list *res = safe_malloc(sizeof(struct list));
+       res->el = el;
+       res->tail = tail;
+       return res;
+}
+
+void list_free(struct list *head, void (*freefun)(void *))
+{
+       while (head != NULL) {
+               freefun(head->el);
+               head = head->tail;
+       }
+}
+
+void **list_to_array(struct list *list, int *num, bool reverse)
+{
+       int i = list_length(list);
+       *num = i;
+       void **ptr = safe_malloc(i*sizeof(void *));
+
+       struct list *r = list;
+       while(i > 0) {
+               if (reverse)
+                       ptr[--i] = r->el;
+               else
+                       ptr[*num-(--i)] = r->el;
+               struct list *t = r;
+               r = r->tail;
+               free(t);
+       }
+       return ptr;
+}
+
+int list_length(struct list *r)
+{
+       int i = 0;
+       while(r != NULL) {
+               i++;
+               r = r->tail;
+       }
+       return i;
+}
+
 void pdie(const char *msg)
 {
        perror(msg);