more bugs
[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         void putSlot(Slot s) {
44                 array[head]=s;
45                 head++;
46                 if (head >= array.length)
47                         head=0;
48                 
49                 if (oldestseqn==0)
50                         oldestseqn = s.getSequenceNumber();
51
52                 if (head==tail) {
53                         tail++;
54                         if (tail >= array.length)
55                                 tail=0;
56                         
57                         oldestseqn++;
58                 }
59         }
60
61         Slot getSlot(long seqnum) {
62                 int diff=(int) (seqnum-oldestseqn);
63                 int index=diff + tail;
64                 if (index > array.length) {
65                         if (head >= tail)
66                                 return null;
67                         index-= array.length;
68                 }
69
70                 if (index >= array.length ||
71                                 index >= head)
72                         return null;
73                 if (index < 0) {
74                         System.out.println("seqnum="+seqnum);
75                         System.out.println("olestseqn="+oldestseqn);
76                         System.out.println("diff="+diff);
77                         System.out.println("tail="+tail);
78
79
80                 }
81                 
82                 return array[index];
83         }
84
85         long getOldestSeqNum() {
86                 return oldestseqn;
87         }
88
89         long getNewestSeqNum() {
90                 return oldestseqn + size() - 1;
91         }
92 }