Fix tabbing.... Please fix your editors so they do tabbing correctly!!! (Spaces...
[IRC.git] / Robust / src / Lex / FIFO.java
1 package Lex;
2
3 /** FIFO class.  This helps implement the lookahead we need for JSR-14.
4  * Copyright (C) 2002 C. Scott Ananian <cananian@alumni.princeton.edu>
5  * This program is released under the terms of the GPL; see the file
6  * COPYING for more details.  There is NO WARRANTY on this code.
7  */
8
9 class FIFO {
10   java_cup.runtime.Symbol[] backing = new java_cup.runtime.Symbol[10];
11   int start=0, end=0;
12   final Getter getter;
13   FIFO(Getter getter) {
14     this.getter = getter;
15   }
16   public boolean isEmpty() {
17     return start==end;
18   }
19   private boolean isFull() {
20     return start==end+1 || (start==0 && end==backing.length-1);
21   }
22   private int size() {
23     return ((end<start)?end+backing.length:end)-start;
24   }
25   public void put(java_cup.runtime.Symbol o) {
26     if (isFull()) {
27       java_cup.runtime.Symbol[] nbacking =
28         new java_cup.runtime.Symbol[backing.length*2];
29       System.arraycopy(backing, start, nbacking, 0, backing.length-start);
30       System.arraycopy(backing, 0, nbacking, backing.length-start, start);
31       start = 0;
32       end = backing.length-1;
33       backing = nbacking;
34     }
35     ASSERT(!isFull());
36     backing[end++] = o;
37     if (end == backing.length)
38       end = 0;
39     ASSERT(!isEmpty());
40   }
41   public java_cup.runtime.Symbol get() throws java.io.IOException {
42     if (isEmpty())
43       put(getter.next());
44     ASSERT(!isEmpty());
45     java_cup.runtime.Symbol o = backing[start++];
46     if (start == backing.length)
47       start = 0;
48     ASSERT(!isFull());
49     return o;
50   }
51   public java_cup.runtime.Symbol peek(int i) throws java.io.IOException {
52     while (i >= size())
53       put(getter.next());
54     int index = start+i;
55     if (index >= backing.length) index -= backing.length;
56     ASSERT(0<= index && index < backing.length);
57     return backing[index];
58   }
59   abstract static class Getter {
60     abstract java_cup.runtime.Symbol next()
61     throws java.io.IOException;
62   }
63   private static void ASSERT(boolean b) {
64     if (!b) throw new RuntimeException();
65   }
66 }
67
68