-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathqueue.c
102 lines (80 loc) · 1.81 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
95
96
97
98
99
100
101
102
/*
* File: queue.c
* Author: Chris Wailes <[email protected]>
* Author: Wei-Te Chen <[email protected]>
* Author: Andy Sayler <[email protected]>
* Project: CSCI 3753 Programming Assignment 2
* Create Date: 2010/02/12
* Modify Date: 2011/02/04
* Modify Date: 2012/02/01
* Description:
* This file contains an implementation of a simple FIFO queue.
*
*/
#include <stdlib.h>
#include "queue.h"
int queue_init(queue* q, int size){
int i;
/* user specified size or default */
if(size>0) {
q->maxSize = size;
}
else {
q->maxSize = QUEUEMAXSIZE;
}
/* malloc array */
q->array = malloc(sizeof(queue_node) * (q->maxSize));
if(!(q->array)){
perror("Error on queue Malloc");
return QUEUE_FAILURE;
}
/* Set to NULL */
for(i=0; i < q->maxSize; ++i){
q->array[i].payload = NULL;
}
/* setup circular buffer values */
q->front = 0;
q->rear = 0;
return q->maxSize;
}
int queue_is_empty(queue* q){
if((q->front == q->rear) && (q->array[q->front].payload == NULL)){
return 1;
}
else{
return 0;
}
}
int queue_is_full(queue* q){
if((q->front == q->rear) && (q->array[q->front].payload != NULL)){
return 1;
}
else{
return 0;
}
}
void* queue_pop(queue* q){
void* ret_payload;
if(queue_is_empty(q)){
return NULL;
}
ret_payload = q->array[q->front].payload;
q->array[q->front].payload = NULL;
q->front = ((q->front + 1) % q->maxSize);
return ret_payload;
}
int queue_push(queue* q, void* new_payload){
if(queue_is_full(q)){
return QUEUE_FAILURE;
}
q->array[q->rear].payload = new_payload;
q->rear = ((q->rear+1) % q->maxSize);
return QUEUE_SUCCESS;
}
void queue_cleanup(queue* q)
{
while(!queue_is_empty(q)){
queue_pop(q);
}
free(q->array);
}