-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.c
94 lines (80 loc) · 1.61 KB
/
queue.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "queue.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int queue_size(layer *queue) {
int result = 0;
while (queue != NULL) {
result++;
queue = queue->next;
if (result > 4096) {
printf("whoops, big queue\n");
break;
}
}
return(result);
}
void queue_add(layer **queue, layer *new) {
int added = 0;
if (*queue == NULL) {
*queue = new;
added++;
}
else {
layer *tmp = *queue;
assert(tmp->prev == NULL);
int i =0;
while (1) {
if (tmp->when >= new->when && tmp->level > new->level) {
// insert in front of later event
new->next = tmp;
new->prev = tmp->prev;
if (new->prev != NULL) {
new->prev->next = new;
}
else {
*queue = new;
}
tmp->prev = new;
added++;
break;
}
if (tmp->next == NULL) {
// add to end of queue
tmp->next = new;
new->prev = tmp;
added++;
break;
}
++i;
tmp = tmp->next;
}
}
assert(added == 1);
}
void queue_remove(layer **queue, layer *old) {
if (old->prev == NULL) {
*queue = old->next;
if (*queue != NULL) {
(*queue)->prev = NULL;
}
}
else {
old->prev->next = old->next;
if (old->next) {
old->next->prev = old->prev;
}
}
old->state = UNUSED;
}
layer *queue_next(layer **queue, double now) {
layer *result = NULL;
if (*queue != NULL && (*queue)->when <= now) {
result = *queue;
*queue = (*queue)->next;
if ((*queue) != NULL) {
(*queue)->prev = NULL;
}
}
return(result);
}