X-Git-Url: http://pileus.org/git/?p=wmpus;a=blobdiff_plain;f=util.c;h=aeb766eaa01f32d65234e84261b97d63d503efe3;hp=2099953ddce60d2832e9fe7f6c814e82e4ebfed9;hb=43cb9b7de22dac5864d73321ec974bb937a217ff;hpb=affe32b94267ef0c1f38a7954bee255a55350cbb diff --git a/util.c b/util.c index 2099953..aeb766e 100644 --- a/util.c +++ b/util.c @@ -1,8 +1,25 @@ +/* + * Copyright (c) 2011, Andy Spencer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + */ + #include #include +#include #include "util.h" +/* Doubly linked lists */ list_t *list_insert(list_t *next, void *data) { list_t *node = new0(list_t); @@ -10,14 +27,26 @@ list_t *list_insert(list_t *next, void *data) node->next = next; node->prev = next ? next->prev : NULL; if (node->next) node->next->prev = node; - if (node->prev) node->next->next = 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->next) + while (last && last->next) last = last->next; list_t *node = new0(list_t); node->data = data; @@ -26,12 +55,14 @@ list_t *list_append(list_t *head, void *data) return last ? head : node; } -list_t *list_remove(list_t *head, list_t *node) +list_t *list_remove(list_t *head, list_t *node, int freedata) { list_t *next = node->next; list_t *prev = node->prev; if (next) next->prev = prev; if (prev) prev->next = next; + if (freedata) + free(node->data); free(node); return head == node ? next : head; } @@ -44,6 +75,30 @@ int list_length(list_t *node) return len; } -void list_move(list_t *node, int offset) +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; }