ac9dee1540bd07dd172ec4a39406660dbb64acab
[iotcloud.git] / src / java / iotcloud / SlotBuffer.java
1 package iotcloud;
2
3 /**
4  * Buffer that holds the live set of slots.
5  * @author Brian Demsky
6  * @version 1.0
7  */
8
9 class SlotBuffer {
10         static final int DEFAULT_SIZE = 128;
11
12         private Slot[] array;
13         private int head;
14         private int tail;
15         private long oldestseqn;
16
17         SlotBuffer() {
18                 array=new Slot[DEFAULT_SIZE+1];
19                 head=tail=0;
20                 oldestseqn=0;
21         }
22
23         int size() {
24                 if (head >= tail)
25                         return head - tail;
26                 return (array.length + head) - tail;
27         }
28
29         int capacity() {
30                 return array.length - 1;
31         }
32
33         void resize(int newsize) {
34                 if (newsize == (array.length-1))
35                         return;
36                 Slot[] newarray = new Slot[newsize+1];
37                 int currsize = size();
38                 int index = tail;
39                 for(int i=0; i < currsize; i++) {
40                         newarray[i] = array[index];
41                         if ((++index) == array.length)
42                                 index = 0;
43                 }
44                 array = newarray;
45                 tail = 0;
46                 head = currsize;
47         }
48
49         private void incrementHead() {
50                 head++;
51                 if (head >= array.length)
52                         head=0;
53         }
54
55         private void incrementTail() {
56                 tail++;
57                 if (tail >= array.length)
58                         tail=0;
59         }
60
61         void putSlot(Slot s) {
62                 array[head]=s;
63                 incrementHead();
64
65                 if (oldestseqn==0)
66                         oldestseqn = s.getSequenceNumber();
67
68                 if (head==tail) {
69                         incrementTail();
70                         oldestseqn++;
71                 }
72         }
73
74         Slot getSlot(long seqnum) {
75                 int diff=(int) (seqnum-oldestseqn);
76                 int index=diff + tail;
77                 if (index >= array.length) {
78                         if (head >= tail)
79                                 return null;
80                         index-= array.length;
81                 }
82
83                 if (index >= array.length)
84                         return null;
85
86                 if (head >= tail && index >= head)
87                         return null;
88
89                 return array[index];
90         }
91
92         long getOldestSeqNum() {
93                 return oldestseqn;
94         }
95
96         long getNewestSeqNum() {
97                 return oldestseqn + size() - 1;
98         }
99 }