X-Git-Url: http://pileus.org/git/?a=blobdiff_plain;f=util.c;h=18f98dc4f17859e5c5724a8d25ed39271ba89e70;hb=ebb648622191195e3e216c103b83549f97cf28d4;hp=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391;hpb=58936d6ab733acf784cf8b1a8f6839b7a75bfe7a;p=wmpus diff --git a/util.c b/util.c index e69de29..18f98dc 100644 --- a/util.c +++ b/util.c @@ -0,0 +1,86 @@ +#include +#include +#include + +#include "util.h" + +list_t *list_insert(list_t *next, void *data) +{ + list_t *node = new0(list_t); + node->data = data; + node->next = next; + node->prev = next ? next->prev : NULL; + if (node->next) node->next->prev = node; + if (node->prev) node->prev->next = node; + return node; +} + +void list_insert_after(list_t *prev, void *data) +{ + // prev must be valid, + // as we cannot return the original list head + list_t *node = new0(list_t); + node->data = data; + node->prev = prev; + node->next = prev->next; + prev->next = node; + if (node->next) node->next->prev = node; +} + +list_t *list_append(list_t *head, void *data) +{ + list_t *last = head; + while (last && last->next) + last = last->next; + list_t *node = new0(list_t); + node->data = data; + node->prev = last; + if (last) last->next = node; + return last ? head : node; +} + +list_t *list_remove(list_t *head, list_t *node) +{ + list_t *next = node->next; + list_t *prev = node->prev; + if (next) next->prev = prev; + if (prev) prev->next = next; + free(node); + return head == node ? next : head; +} + +int list_length(list_t *node) +{ + int len = 0; + for (; node; node = node->next) + len++; + return len; +} + +list_t *list_last(list_t *list) +{ + while (list && list->next) + list = list->next; + return list; +} + +list_t *list_find(list_t *list, void *data) +{ + for (list_t *cur = list; cur; cur = cur->next) + if (cur->data == data) + return cur; + return NULL; +} + +/* Misc */ +int error(char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + fprintf(stderr, "Error: "); + vfprintf(stderr, fmt, ap); + fprintf(stderr, "\n"); + va_end(ap); + exit(1); + return 0; +}