de4bbe0bc64a43f14851d46b2eb401dbeacbc409
[iotcloud.git] / version2 / src / C / SlotBuffer.cc
1 #include "SlotBuffer.h"
2 #include "Slot.h"
3 /**
4  * Circular buffer that holds the live set of slots.
5  * @author Brian Demsky
6  * @version 1.0
7  */
8
9 SlotBuffer::SlotBuffer() :
10         array(new Array<Slot *>(SlotBuffer_DEFAULT_SIZE + 1)),
11         head(0),
12         tail(0),
13         oldestseqn(0) {
14 }
15
16 int SlotBuffer::size() {
17         if (head >= tail)
18                 return head - tail;
19         return (array->length() + head) - tail;
20 }
21
22 int SlotBuffer::capacity() {
23         return array->length() - 1;
24 }
25
26 void SlotBuffer::resize(int newsize) {
27         if (newsize == (array->length() - 1))
28                 return;
29
30         Array<Slot *> *newarray = new Array<Slot *>(newsize + 1);
31         int currsize = size();
32         int index = tail;
33         for (int i = 0; i < currsize; i++) {
34                 newarray->set(i, array->get(index));
35                 if ((++index) == array->length())
36                         index = 0;
37         }
38         array = newarray;
39         tail = 0;
40         head = currsize;
41 }
42
43 void SlotBuffer::incrementHead() {
44         head++;
45         if (head >= array->length())
46                 head = 0;
47 }
48
49 void SlotBuffer::incrementTail() {
50         tail++;
51         if (tail >= array->length())
52                 tail = 0;
53 }
54
55 void SlotBuffer::putSlot(Slot *s) {
56         int64_t checkNum = (getNewestSeqNum() + 1);
57
58         if (checkNum != s->getSequenceNumber()) {
59                 // We have a gap so expunge all our slots
60                 oldestseqn = s->getSequenceNumber();
61                 tail = 0;
62                 head = 1;
63                 array->set(0, s);
64                 return;
65         }
66
67         array->set(head, s);
68         incrementHead();
69
70         if (oldestseqn == 0) {
71                 oldestseqn = s->getSequenceNumber();
72         }
73
74         if (head == tail) {
75                 incrementTail();
76                 oldestseqn++;
77         }
78 }
79
80 Slot *SlotBuffer::getSlot(int64_t seqnum) {
81         int32_t diff = (int32_t) (seqnum - oldestseqn);
82         int32_t index = diff + tail;
83
84         if (index < 0) {
85                 // Really old message so we dont have it anymore
86                 return NULL;
87         }
88
89         if (index >= array->length()) {
90                 if (head >= tail) {
91                         return NULL;
92                 }
93                 index -= array->length();
94         }
95
96         if (index >= array->length()) {
97
98                 return NULL;
99         }
100         if (head >= tail && index >= head) {
101                 return NULL;
102         }
103
104         return array->get(index);
105 }