]> Pileus Git - wmpus/blob - util.c
Add multi-monitor support to wm-wmii
[wmpus] / util.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4
5 #include "util.h"
6
7 list_t *list_insert(list_t *next, void *data)
8 {
9         list_t *node = new0(list_t);
10         node->data = data;
11         node->next = next;
12         node->prev = next ? next->prev : NULL;
13         if (node->next) node->next->prev = node;
14         if (node->prev) node->prev->next = node;
15         return node;
16 }
17
18 void list_insert_after(list_t *prev, void *data)
19 {
20         // prev must be valid,
21         // as we cannot return the original list head
22         list_t *node = new0(list_t);
23         node->data = data;
24         node->prev = prev;
25         node->next = prev->next;
26         prev->next = node;
27         if (node->next) node->next->prev = node;
28 }
29
30 list_t *list_append(list_t *head, void *data)
31 {
32         list_t *last = head;
33         while (last && last->next)
34                 last = last->next;
35         list_t *node = new0(list_t);
36         node->data = data;
37         node->prev = last;
38         if (last) last->next = node;
39         return last ? head : node;
40 }
41
42 list_t *list_remove(list_t *head, list_t *node)
43 {
44         list_t *next = node->next;
45         list_t *prev = node->prev;
46         if (next) next->prev = prev;
47         if (prev) prev->next = next;
48         free(node);
49         return head == node ? next : head;
50 }
51
52 int list_length(list_t *node)
53 {
54         int len = 0;
55         for (; node; node = node->next)
56                 len++;
57         return len;
58 }
59
60 list_t *list_last(list_t *list)
61 {
62         while (list && list->next)
63                 list = list->next;
64         return list;
65 }
66
67 list_t *list_find(list_t *list, void *data)
68 {
69         for (list_t *cur = list; cur; cur = cur->next)
70                 if (cur->data == data)
71                         return cur;
72         return NULL;
73 }
74
75 /* Misc */
76 int error(char *fmt, ...)
77 {
78         va_list ap;
79         va_start(ap, fmt);
80         fprintf(stderr, "Error: ");
81         vfprintf(stderr, fmt, ap);
82         fprintf(stderr, "\n");
83         va_end(ap);
84         exit(1);
85         return 0;
86 }