licensing update to APSL 2.0
[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 import java.io.*;
7
8 public class LineReader {
9
10     private int MAXBUF = 1024 * 16;
11     char[] buf = new char[MAXBUF];
12     int buflen = 0;
13     Reader r;
14     Vec pushback = new Vec();
15
16     public LineReader(Reader r) { this.r = r; }
17
18     public void pushback(String s) { pushback.push(s); }
19
20     public String readLine() throws IOException {
21         while(true) {
22             if (pushback.size() > 0) return (String)pushback.pop();
23             for(int i=0; i<buflen; i++) {
24                 if (buf[i] == '\n') {
25                     String ret;
26                     if (buf[i-1] == '\r') ret = new String(buf, 0, i-1);
27                     else ret = new String(buf, 0, i);
28                     System.arraycopy(buf, i+1, buf, 0, buflen - (i+1));
29                     buflen -= i+1;
30                     return ret;
31                 }
32             }
33             if (buflen == MAXBUF) {
34                 char[] buf2 = new char[MAXBUF*2];
35                 System.arraycopy(buf, 0, buf2, 0, buflen);
36                 buf = buf2;
37                 MAXBUF *= 2;
38             }
39             int numread = r.read(buf, buflen, MAXBUF - buflen);
40             if (numread == -1) {
41                 if (buflen == 0) return null;
42                 String ret = new String(buf, 0, buflen);
43                 buflen = 0;
44                 return ret;
45             } else {
46                 buflen += numread;
47             }
48         }
49     }
50 }