-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathQueue.cpp
More file actions
147 lines (132 loc) · 3.1 KB
/
Queue.cpp
File metadata and controls
147 lines (132 loc) · 3.1 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include "Queue.h"
Queue::Queue()
{
_itemsInQueue = 0;
_queueStart = 0;
_queueEnd = 0;
}
int Queue::scheduleFunction(queuedFunction func, const char * id, unsigned long initialRun, unsigned long recur)
{
int rv = 0;
if(strlen(id) > 7)
{
rv = -1;
} else {
queueItem newItem;
newItem.fPtr = func;
memset(newItem.itemName, 0, 8);
memcpy(newItem.itemName, id, strlen(id));
newItem.recur = recur;
newItem.next = initialRun;
rv = _addToQueue(newItem);
}
return rv;
}
int Queue::scheduleRemoveFunction(const char * id)
{
queueItem target;
int rv = -1;
for (int i = 0; i < _itemsInQueue; ++i)
{
if(_queueGetTop(target) == 0)
{
if(strcmp(target.itemName, id) == 0)
{
rv = 0;
} else {
_addToQueue(target);
}
} else {
rv = -1;
break;
}
}
return rv;
}
int Queue::scheduleChangeFunction(const char * id, unsigned long nextRunTime, unsigned long newRecur)
{
queueItem target;
int rv = -1;
for (int i = 0; i < _itemsInQueue; ++i)
{
if(_queueGetTop(target) == 0)
{
if(strcmp(target.itemName, id) == 0)
{
target.next = nextRunTime;
target.recur = newRecur;
rv = 0;
}
_addToQueue(target);
} else {
rv = -1;
break;
}
}
return rv;
}
int Queue::Run(unsigned long now)
{
queueItem target;
int rv = 0;
if(_itemsInQueue == 0)
{
rv = -1;
}
for (int i = 0; i < _itemsInQueue; ++i)
{
if(_queueGetTop(target)==0)
{
if(target.next <= now)
{
int tRv;
tRv = (target.fPtr)(now);
if(tRv == 0)
{
rv++;
}
if(target.recur != 0)
{
target.next = now + target.recur;
_addToQueue(target);
}
} else {
_addToQueue(target);
}
} else {
rv = -1;
break;
}
}
return rv;
}
int Queue::_queueGetTop(queueItem &item)
{
int rv = 0;
//Remove the top item, stuff it into item
if (_queueEnd != _queueStart) {
queueItem tempQueueItem = _schedule[_queueStart];
//This Algorithm also from Wikipedia.
_queueStart = (_queueStart + 1) % QueueScheduleSize;
item = tempQueueItem;
_itemsInQueue--;
} else {
//if the buffer is empty, return an error code
rv = -1;
}
return rv;
}
int Queue::_addToQueue(queueItem item)
{
//This is just a circular buffer, and this algorithm is stolen from wikipedia
int rv = 0;
if ((_queueEnd + 1) % QueueScheduleSize != _queueStart) {
_schedule[_queueEnd] = item;
_queueEnd = (_queueEnd + 1) % QueueScheduleSize;
_itemsInQueue++;
} else {
//if buffer is full, error
rv = -1;
}
return rv;
}