Another file compiles
[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 SlotBuffer::~SlotBuffer() {
17         delete array;
18 }
19
20 int SlotBuffer::size() {
21         if (head >= tail)
22                 return head - tail;
23         return (array->length() + head) - tail;
24 }
25
26 int SlotBuffer::capacity() {
27         return array->length() - 1;
28 }
29
30 void SlotBuffer::resize(int newsize) {
31         if (newsize == (array->length() - 1))
32                 return;
33
34         Array<Slot *> *newarray = new Array<Slot *>(newsize + 1);
35         int currsize = size();
36         int index = tail;
37         for (int i = 0; i < currsize; i++) {
38                 newarray->set(i, array->get(index));
39                 if ((++index) == array->length())
40                         index = 0;
41         }
42         array = newarray;
43         tail = 0;
44         head = currsize;
45 }
46
47 void SlotBuffer::incrementHead() {
48         head++;
49         if (head >= array->length())
50                 head = 0;
51 }
52
53 void SlotBuffer::incrementTail() {
54         tail++;
55         if (tail >= array->length())
56                 tail = 0;
57 }
58
59 void SlotBuffer::putSlot(Slot *s) {
60         int64_t checkNum = (getNewestSeqNum() + 1);
61
62         if (checkNum != s->getSequenceNumber()) {
63                 oldestseqn = s->getSequenceNumber();
64                 tail = 0;
65                 head = 1;
66                 array->set(0, s);
67                 return;
68         }
69
70         array->set(head, s);
71         incrementHead();
72
73         if (oldestseqn == 0) {
74                 oldestseqn = s->getSequenceNumber();
75         }
76
77         if (head == tail) {
78                 incrementTail();
79                 oldestseqn++;
80         }
81 }
82
83 Slot *SlotBuffer::getSlot(int64_t seqnum) {
84         int32_t diff = (int32_t) (seqnum - oldestseqn);
85         int32_t index = diff + tail;
86
87         if (index < 0) {
88                 return NULL;
89         }
90
91         if (index >= array->length()) {
92                 if (head >= tail) {
93                         return NULL;
94                 }
95                 index -= array->length();
96         }
97
98         if (index >= array->length()) {
99                 return NULL;
100         }
101
102         if (head >= tail && index >= head) {
103                 return NULL;
104         }
105
106         return array->get(index);
107 }