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