01: package org.antlr.runtime;
02:
03: import java.io.*;
04:
05: /** Vacuum all input from a Reader and then treat it like a StringStream.
06: * Manage the buffer manually to avoid unnecessary data copying.
07: *
08: * If you need encoding, use ANTLRInputStream.
09: */
10: public class ANTLRReaderStream extends ANTLRStringStream {
11: public static final int READ_BUFFER_SIZE = 1024;
12: public static final int INITIAL_BUFFER_SIZE = 1024;
13:
14: public ANTLRReaderStream() {
15: }
16:
17: public ANTLRReaderStream(Reader r) throws IOException {
18: this (r, INITIAL_BUFFER_SIZE, READ_BUFFER_SIZE);
19: }
20:
21: public ANTLRReaderStream(Reader r, int size) throws IOException {
22: this (r, size, READ_BUFFER_SIZE);
23: }
24:
25: public ANTLRReaderStream(Reader r, int size, int readChunkSize)
26: throws IOException {
27: load(r, size, readChunkSize);
28: }
29:
30: public void load(Reader r, int size, int readChunkSize)
31: throws IOException {
32: if (r == null) {
33: return;
34: }
35: if (size <= 0) {
36: size = INITIAL_BUFFER_SIZE;
37: }
38: if (readChunkSize <= 0) {
39: size = READ_BUFFER_SIZE;
40: }
41: // System.out.println("load "+size+" in chunks of "+readChunkSize);
42: try {
43: // alloc initial buffer size.
44: data = new char[size];
45: // read all the data in chunks of readChunkSize
46: int numRead = 0;
47: int p = 0;
48: do {
49: if (p + readChunkSize > data.length) { // overflow?
50: // System.out.println("### overflow p="+p+", data.length="+data.length);
51: char[] newdata = new char[data.length * 2]; // resize
52: System.arraycopy(data, 0, newdata, 0, data.length);
53: data = newdata;
54: }
55: numRead = r.read(data, p, readChunkSize);
56: // System.out.println("read "+numRead+" chars; p was "+p+" is now "+(p+numRead));
57: p += numRead;
58: } while (numRead != -1); // while not EOF
59: // set the actual size of the data available;
60: // EOF subtracted one above in p+=numRead; add one back
61: super .n = p + 1;
62: //System.out.println("n="+n);
63: } finally {
64: r.close();
65: }
66: }
67: }
|