01: package antlr;
02:
03: /* ANTLR Translator Generator
04: * Project led by Terence Parr at http://www.cs.usfca.edu
05: * Software rights: http://www.antlr.org/license.html
06: */
07:
08: /** A circular buffer object used by CharBuffer */
09: public class CharQueue {
10: /** Physical circular buffer of tokens */
11: protected char[] buffer;
12: /** buffer.length-1 for quick modulos */
13: private int sizeLessOne;
14: /** physical index of front token */
15: private int offset;
16: /** number of tokens in the queue */
17: protected int nbrEntries;
18:
19: public CharQueue(int minSize) {
20: // Find first power of 2 >= to requested size
21: int size;
22: if (minSize < 0) {
23: init(16); // pick some value for them
24: return;
25: }
26: // check for overflow
27: if (minSize >= (Integer.MAX_VALUE / 2)) {
28: init(Integer.MAX_VALUE); // wow that's big.
29: return;
30: }
31: for (size = 2; size < minSize; size *= 2) {
32: }
33: init(size);
34: }
35:
36: /** Add token to end of the queue
37: * @param tok The token to add
38: */
39: public final void append(char tok) {
40: if (nbrEntries == buffer.length) {
41: expand();
42: }
43: buffer[(offset + nbrEntries) & sizeLessOne] = tok;
44: nbrEntries++;
45: }
46:
47: /** Fetch a token from the queue by index
48: * @param idx The index of the token to fetch, where zero is the token at the front of the queue
49: */
50: public final char elementAt(int idx) {
51: return buffer[(offset + idx) & sizeLessOne];
52: }
53:
54: /** Expand the token buffer by doubling its capacity */
55: private final void expand() {
56: char[] newBuffer = new char[buffer.length * 2];
57: // Copy the contents to the new buffer
58: // Note that this will store the first logical item in the
59: // first physical array element.
60: for (int i = 0; i < buffer.length; i++) {
61: newBuffer[i] = elementAt(i);
62: }
63: // Re-initialize with new contents, keep old nbrEntries
64: buffer = newBuffer;
65: sizeLessOne = buffer.length - 1;
66: offset = 0;
67: }
68:
69: /** Initialize the queue.
70: * @param size The initial size of the queue
71: */
72: public void init(int size) {
73: // Allocate buffer
74: buffer = new char[size];
75: // Other initialization
76: sizeLessOne = size - 1;
77: offset = 0;
78: nbrEntries = 0;
79: }
80:
81: /** Clear the queue. Leaving the previous buffer alone.
82: */
83: public final void reset() {
84: offset = 0;
85: nbrEntries = 0;
86: }
87:
88: /** Remove char from front of queue */
89: public final void removeFirst() {
90: offset = (offset + 1) & sizeLessOne;
91: nbrEntries--;
92: }
93: }
|