changes: now Inference engine works fine with the EyeTracking benchmark.
[IRC.git] / Robust / src / ClassLibrary / PushbackInputStream.java
1 public class PushbackInputStream {
2   // A pushback input stream lets you throw things
3   // back into the stream to be read again.  Read
4   // characters from a normal input stream, but keep
5   // them in a ring buffer also.  Then, when unread()
6   // is called, throw characters from the ring buffer
7   // onto a stack.  During read() first take characters
8   // off the stack if they are present, otherwise get
9   // them from the normal input stream.
10
11   private FileInputStream in;
12
13   private int max;
14
15   private int index;
16   private int[] ring;
17
18   private int top;
19   private int bottom;
20   private int[] stack;
21
22
23   public PushbackInputStream(FileInputStream fis) {
24     in = fis;
25     max = 1000;
26
27     index = 0;
28     ring = new int[max];
29
30     bottom = -1;
31     top = bottom;
32     stack = new int[max];
33   }
34
35
36   public int read() {
37     int v;
38
39     // get next value from stack or if empty
40     // then from the input stream
41     if( top > bottom ) {
42       v = stack[top];
43       --top;
44     } else {
45       v = in.read();
46     }
47
48     // put whatever it is in the ring buffer
49     ring[index] = v;
50
51     // keep ring buffer index
52     ++index;
53     if( index == max ) {
54       index = 0;
55     }
56
57     // user gets what they want
58     return v;
59   }
60
61
62   public void unread(int v) {
63     ++top;
64
65     // the unread stack can only get so high
66     if( top == max ) {
67       System.printString("PushbackInputStream: max reached");
68       System.exit(-1);
69     }
70
71     // put it on the unread stack
72     stack[top] = ring[index];
73   }
74 }