]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/linkedlist.qh
LinkedList: delete method
[xonotic/xonotic-data.pk3dir.git] / qcsrc / lib / linkedlist.qh
1 #ifndef LINKEDLIST_H
2 #define LINKEDLIST_H
3
4 CLASS(LinkedListNode, Object)
5         ATTRIB(LinkedListNode, ll_data, entity, NULL)
6         ATTRIB(LinkedListNode, ll_prev, LinkedListNode, NULL)
7         ATTRIB(LinkedListNode, ll_next, LinkedListNode, NULL)
8 ENDCLASS(LinkedListNode)
9
10 CLASS(LinkedList, Object)
11         ATTRIB(LinkedList, ll_head, LinkedListNode, NULL);
12         ATTRIB(LinkedList, ll_tail, LinkedListNode, NULL);
13 ENDCLASS(LinkedList)
14
15 #define LL_NEW() NEW(LinkedList)
16
17 #define LL_EMPTY(ll) (ll.ll_head == NULL)
18
19 /**
20  * Push to tail
21  */
22 entity LL_PUSH(LinkedList this, entity e)
23 {
24         assert(this);
25         LinkedListNode n = NEW(LinkedListNode);
26         n.ll_data = e;
27         LinkedListNode tail = n.ll_prev = this.ll_tail;
28         this.ll_tail = (tail) ? tail.ll_next = n : this.ll_head = n;
29         return e;
30 }
31
32 /**
33  * Pop from tail
34  */
35 entity LL_POP(LinkedList this)
36 {
37         assert(this);
38         if (!this.ll_tail) return NULL;
39         LinkedListNode n = this.ll_tail;
40         entity e = n.ll_data;
41         LinkedListNode prev = n.ll_prev;
42         if (prev) (this.ll_tail = prev).ll_next = NULL;
43         else this.ll_head = this.ll_tail = NULL;
44         remove(n);
45         return e;
46 }
47
48 #define LL_DELETE(this) \
49         do \
50         { \
51                 LinkedList _ll = this; \
52                 assert(_ll); \
53                 while (_ll.ll_tail) \
54                 { \
55                         entity it = LL_POP(_ll); \
56                         if (it) remove(it); \
57                 } \
58                 this = NULL; \
59         } \
60         while (0)
61
62 #define LL_EACH(list, cond, body) \
63         do                                                                  \
64         {                                                                   \
65                 noref int i = 0;                                                \
66                 for (entity _it = list.ll_head; _it; (_it = _it.ll_next, ++i))  \
67                 {                                                               \
68                         noref entity it = _it.ll_data;                              \
69                         if (cond) { body }                                          \
70                 }                                                               \
71         }                                                                   \
72         while (0)
73
74 #endif