update LineReader to use Baskets
[org.ibex.util.git] / src / org / ibex / util / LineReader.java
1 // Copyright 2000-2005 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.
4
5 package org.ibex.util;
6
7 import java.io.Reader;
8 import java.io.IOException;
9
10 /** @author adam@ibex.org */
11 public class LineReader {
12
13     private int MAXBUF = 1024 * 16;
14
15     private final Basket.Stack pushback = new Basket.Array();
16
17     private char[] buf = new char[MAXBUF];
18     private int buflen = 0;
19     private Reader r;
20
21     public LineReader(Reader r) { this.r = r; }
22
23     public void pushback(String s) { pushback.push(s); }
24
25     public String readLine() throws IOException {
26         while(true) {
27             if (pushback.size() > 0) return (String)pushback.pop();
28             for(int i=0; i<buflen; i++) {
29                 if (buf[i] == '\n') {
30                     String ret;
31                     if (buf[i-1] == '\r') ret = new String(buf, 0, i-1);
32                     else ret = new String(buf, 0, i);
33                     System.arraycopy(buf, i+1, buf, 0, buflen - (i+1));
34                     buflen -= i+1;
35                     return ret;
36                 }
37             }
38             if (buflen == MAXBUF) {
39                 char[] buf2 = new char[MAXBUF*2];
40                 System.arraycopy(buf, 0, buf2, 0, buflen);
41                 buf = buf2;
42                 MAXBUF *= 2;
43             }
44             int numread = r.read(buf, buflen, MAXBUF - buflen);
45             if (numread == -1) {
46                 if (buflen == 0) return null;
47                 String ret = new String(buf, 0, buflen);
48                 buflen = 0;
49                 return ret;
50             } else {
51                 buflen += numread;
52             }
53         }
54     }
55 }