More Java Code
[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         }
14
15         int size() {
16                 if (head >= tail)
17                         return head - tail;
18                 return (array.length + head) - tail;
19         }
20         
21         void resize(int newsize) {
22                 if (newsize == (array.length-1))
23                         return;
24                 Slot[] newarray = new Slot[newsize+1];
25                 int currsize = size();
26                 int index = tail;
27                 for(int i=0; i < currsize; i++) {
28                         newarray[i] = array[index];
29                         if ((++index) == array.length)
30                                 index = 0;
31                 }
32                 array = newarray;
33                 tail = currsize;
34                 head = 0;
35         }
36
37         void putSlot(Slot s) {
38                 array[head]=s;
39                 head++;
40                 if (oldestseqn==0)
41                         oldestseqn = s.getSequenceNumber();
42
43                 if (head==tail) {
44                         tail++;
45                         oldestseqn++;
46                 }
47         }
48
49         Slot getSlot(long seqnum) {
50                 int diff=(int) (seqnum-oldestseqn);
51                 int index=diff + tail;
52                 if (index > array.length) {
53                         if (head >= tail)
54                                 return null;
55                         index-= array.length;
56                 }
57                 
58                 if (index >= array.length ||
59                                 index >= head)
60                         return null;
61                 
62                 return array[index];
63         }
64
65         long getOldestSeqNum() {
66                 return oldestseqn;
67         }
68
69         long getNewestSeqNum() {
70                 return oldestseqn + size();
71         }
72 }