-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUSBQueue.h
113 lines (99 loc) · 2.3 KB
/
USBQueue.h
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
109
110
111
112
113
#ifndef USBQUEUE
#define USBQUEUE
#include <stdlib.h>
#include <assert.h>
#include "USBMessage.h"
#ifndef true
#define true 1
#endif
#ifndef false
#define false 0
#endif
#ifndef bool
#define bool int
#endif
typedef struct _USBQueueNode {
struct _USBQueueNode *next;
USBMessage *message;
} USBQueueNode;
typedef struct _USBQueue {
USBQueueNode *head;
USBQueueNode *tail;
int length;
} USBQueue;
void USBQueue_Init(USBQueue *q);
void USBQueue_Destroy(USBQueue *q);
bool USBQueue_IsEmpty(USBQueue *q);
int USBQueue_Length(USBQueue *q);
void USBQueue_Enqueue(USBQueue *q, USBMessage *m);
USBMessage * USBQueue_Dequeue(USBQueue *q);
void USBQueue_Init(USBQueue *q) {
assert(q != NULL);
q->head = NULL;
q->tail = NULL;
q->length = 0;
}
void USBQueue_Destroy(USBQueue *q) {
assert(q != NULL);
while (!USBQueue_IsEmpty(q)) {
USBMessage *m = USBQueue_Dequeue(q);
free(m);
}
}
bool USBQueue_IsEmpty(USBQueue *q) {
assert(q != NULL);
if (q->head == NULL) {
assert(q->tail == NULL);
return true;
}
assert(q->tail != NULL);
return false;
}
int USBQueue_Length(USBQueue *q) {
assert(q != NULL);
return q->length;
}
void USBQueue_Enqueue(USBQueue *q, USBMessage *m) {
assert(q != NULL);
if (USBQueue_IsEmpty(q)) {
assert(q->head == NULL);
assert(q->tail == NULL);
USBQueueNode *n = (USBQueueNode *) malloc(sizeof(USBQueueNode));
n->next = NULL;
n->message = m;
q->head = n;
q->tail = n;
}
else {
assert(q->head != NULL);
assert(q->tail != NULL);
USBQueueNode *n = (USBQueueNode *) malloc(sizeof(USBQueueNode));
n->next = NULL;
n->message = m;
q->head->next = n;
q->head = n;
}
q->length += 1;
}
USBMessage * USBQueue_Dequeue(USBQueue *q) {
assert(q != NULL);
assert(!USBQueue_IsEmpty(q));
if (q->head == q->tail) {
USBQueueNode *n = q->tail;
q->tail = NULL;
q->head = NULL;
USBMessage *m = n->message;
free(n);
q->length -= 1;
return m;
}
else {
USBQueueNode *n = q->tail;
q->tail = q->tail->next;
USBMessage *m = n->message;
free(n);
q->length -= 1;
return m;
}
}
#endif /* USBQUEUE */