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