1 // Copyright 2000-2007 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
8 /** package-private class */
9 class CharBufReader extends Reader {
11 private Reader reader;
12 private char[] buf = new char[8192];
13 private int start = 0;
16 public CharBufReader(Reader r) { this.reader = r; }
18 public boolean ready() throws IOException { return bufSize()>0; }
19 private int bufSize() { if (end==start) { end=start=0; } return end-start; }
20 private int fillBufIfEmpty() {
22 if (bufSize() > 0) return bufSize();
25 end = reader.read(buf, 0, buf.length);
27 if (end == -1) { end = 0; return -1; }
29 } catch (IOException e) { Stream.ioe(e); return -1; }
32 public int available() { return end-start; }
35 if (reader != null) reader.close();
36 } catch (IOException e) { Stream.ioe(e); }
39 public int read(char[] c, int pos, int len) {
40 if (fillBufIfEmpty() == -1) return -1;
41 if (len > end - start) len = end - start;
42 System.arraycopy(buf, start, c, pos, len);
47 public char getc(boolean peek) {
48 if (fillBufIfEmpty() <= 0) throw new Stream.EOF();
49 return peek ? buf[start] : buf[start++];
52 private StringBuffer lineReaderStringBuffer = new StringBuffer();
53 public String readln() {
54 lineReaderStringBuffer.setLength(0);
55 boolean readsome = false;
57 if (fillBufIfEmpty() <= 0) break;
59 for(int i=start; i<end; i++)
61 // this should (in theory) handle CR, LF,
62 // CRLF, and LFCR properly, assuming that the
63 // file consistently uses the same ending
68 if (buf[begin] == '\r') { begin++; len--; }
69 while (len > 0 && buf[begin+len-1] == '\r') { len--; }
70 lineReaderStringBuffer.append(buf, begin, len);
73 lineReaderStringBuffer.append(buf, start, end-start);
76 if (!readsome) return null;
77 String ret = lineReaderStringBuffer.toString();
78 lineReaderStringBuffer.setLength(0);
82 public void unbuffer(Writer writer) {
83 if (bufSize()<=0) return;
85 writer.write(buf, start, end-start);
88 } catch (IOException e) {