2 * Copyright (c) 2011, Andy Spencer <andy753421@gmail.com>
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
22 /* Doubly linked lists */
23 list_t *list_insert(list_t *next, void *data)
25 list_t *node = new0(list_t);
28 node->prev = next ? next->prev : NULL;
29 if (node->next) node->next->prev = node;
30 if (node->prev) node->prev->next = node;
34 void list_insert_after(list_t *prev, void *data)
36 // prev must be valid,
37 // as we cannot return the original list head
38 list_t *node = new0(list_t);
41 node->next = prev->next;
43 if (node->next) node->next->prev = node;
46 list_t *list_append(list_t *head, void *data)
49 while (last && last->next)
51 list_t *node = new0(list_t);
54 if (last) last->next = node;
55 return last ? head : node;
58 list_t *list_remove(list_t *head, list_t *node, int freedata)
60 list_t *next = node->next;
61 list_t *prev = node->prev;
62 if (next) next->prev = prev;
63 if (prev) prev->next = next;
67 return head == node ? next : head;
70 int list_length(list_t *node)
73 for (; node; node = node->next)
78 list_t *list_last(list_t *list)
80 while (list && list->next)
85 list_t *list_find(list_t *list, void *data)
87 for (list_t *cur = list; cur; cur = cur->next)
88 if (cur->data == data)
93 list_t *list_sort(list_t *list, int rev, int (*func)(void *a, void*b))
95 if (list == NULL || list->next == NULL)
99 list_t *sides[2] = {NULL, NULL};
100 for (int i = 0; list; i=(i+1)%2) {
103 head->next = sides[i];
108 sides[0] = list_sort(sides[0], !rev, func);
109 sides[1] = list_sort(sides[1], !rev, func);
112 while (sides[0] || sides[1]) {
113 int i = sides[0] == NULL ? 1 :
114 sides[1] == NULL ? 0 :
116 sides[1]->data) > 0 ? !!rev : !rev;
117 list_t *head = sides[i];
118 sides[i] = sides[i]->next;
129 int residual(float num, float *state)
131 float f = num + *state;
132 int i = (int)(f+0.5);
137 int str2num(char *str, int def)
140 int num = strtol(str, &end, 10);
141 return end && *end == '\0' ? num : def;
144 int warn(char *fmt, ...)
148 fprintf(stderr, "Warning: ");
149 vfprintf(stderr, fmt, ap);
150 fprintf(stderr, "\n");
155 int error(char *fmt, ...)
159 fprintf(stderr, "Error: ");
160 vfprintf(stderr, fmt, ap);
161 fprintf(stderr, "\n");