-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinst_queue.c
102 lines (94 loc) · 2.44 KB
/
inst_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
#include "inst_queue.h"
/************************************************************************/
/* Private functions prototypes */
/************************************************************************/
bool InstQ_Dequeue(InstQ *, command_row_t *);
bool InstQ_IsEmpty(InstQ *);
/************************************************************************/
/* Public functions declaration */
/************************************************************************/
InstQ* InstQ_ConstructQueue(int limit) {
InstQ* queue = (InstQ*) malloc(sizeof(InstQ));
if (!queue) {
return NULL;
}
queue->limit = limit;
queue->size = 0;
queue->head = NULL;
queue->tail = NULL;
return queue;
}
void InstQ_DestructQueue(InstQ* pQueue) {
command_row_t Instr;
while (!InstQ_IsEmpty(pQueue)) {
if (InstQ_Dequeue(pQueue, &Instr) == FAILURE) {
printf("[Error] Failed to dequeue\n");
}
}
free(pQueue);
}
bool InstQ_Enqueue(InstQ* pQueue, command_row_t Instr) {
/* Check parameter */
if ( (pQueue == NULL) || (pQueue->size >= pQueue->limit)) {
return FAILURE;
}
NODE* item = (NODE*) malloc(sizeof(NODE));
if (!item) {
return FAILURE;
}
item->m_Instr = Instr;
item->prev = NULL;
if (pQueue->size == 0) {
/* If the queue is empty */
pQueue->head = item;
pQueue->tail = item;
} else {
/* Else, Add item to the end of the queue */
pQueue->tail->prev = item;
pQueue->tail = item;
}
pQueue->size++;
return SUCCESS;
}
bool InstQ_Peek(InstQ* pQueue, command_row_t* pInstr) {
if (InstQ_IsEmpty(pQueue)) {
return FAILURE;
}
NODE* item = pQueue->head;
*pInstr = item->m_Instr;
return SUCCESS;
}
bool InstQ_Pop(InstQ* pQueue) {
if (InstQ_IsEmpty(pQueue)) { /* The queue is empty or bad param */
return FAILURE;
}
NODE* item = pQueue->head;
pQueue->head = (pQueue->head)->prev;
free(item);
pQueue->size--;
return SUCCESS;
}
/************************************************************************/
/* Private functions declaration */
/************************************************************************/
bool InstQ_Dequeue(InstQ* pQueue, command_row_t* pInstr) {
if (InstQ_IsEmpty(pQueue)) { /* The queue is empty or bad param */
return FAILURE;
}
NODE* item = pQueue->head;
*pInstr = item->m_Instr;
pQueue->head = (pQueue->head)->prev;
free(item);
pQueue->size--;
return SUCCESS;
}
bool InstQ_IsEmpty(InstQ* pQueue) {
if (pQueue == NULL) {
return false;
}
if (pQueue->size == 0) {
return true;
} else {
return false;
}
}