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