-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengi_queue.c
109 lines (77 loc) · 1.47 KB
/
engi_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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stddef.h>
#include <errno.h>
#include "engi_queue.h"
int engi_queue_init(engi_queue_t *self)
{
self->enqueue = engi_queue_enqueue;
self->dequeue = engi_queue_dequeue;
self->back = NULL;
self->front = NULL;
self->size = 0;
return 0;
}
int engi_queue_destroy(engi_queue_t *self)
{
void *ret = NULL;
self->enqueue = NULL;
while(likely((ret = self->dequeue(self, NULL)) != NULL));
self->dequeue = NULL;
return 0;
}
void * engi_queue_enqueue(void *self, void *data)
{
engi_queue_t *queue = (engi_queue_t *)self;
engi_queue_cont_t *new = calloc(1, sizeof(engi_queue_cont_t));
if(unlikely(new == NULL))
{
errno = ENOMEM;
return NULL;
}
new->data = data;
if(unlikely(queue->back == NULL))
{
queue->back = new;
queue->front = new;
goto SKIP;
}
queue->back->prev = new;
SKIP:
new->next = queue->back;
queue->back = new;
queue->size++;
return NULL;
}
void * engi_queue_dequeue(void *self, void *data)
{
engi_queue_t *queue = (engi_queue_t *)self;
engi_queue_cont_t *old = queue->front;
if(unlikely(old == NULL))
{
queue->size--;
errno = EFAULT;
return NULL;
}
engi_queue_cont_t *prev = old->prev;
if(unlikely(prev == NULL))
{
queue->front = NULL;
queue->back = NULL;
errno = EFAULT;
goto END;
}
prev->next = NULL;
queue->front = prev;
if(unlikely(old->prev != NULL))
{
old->prev = NULL;
}
if(data != NULL)
{
data = old->data;
}
END:;
void *ret = old->data;
queue->size--;
free(old);
return ret;
}