mostly intert changes, cleanup of Stream
[org.ibex.io.git] / src / org / ibex / io / Stream.java
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.
4
5 package org.ibex.io;
6
7 import java.io.*;
8 import java.net.*;
9 import java.util.*;
10 import java.util.zip.*;
11 import org.ibex.util.*;
12
13 // Features:
14 //   - automatically flush writer before reading on linked read/write pairs
15 //   - no checked exceptions thrown
16 //   - unified write(char), print(char), and write(byte)
17 //   - unreading/peeking
18 //   - transcribe
19 //   - append (daisy-chaining)
20 //   - automatically closes input streams when end reached
21
22 /** plays the role of InputStream, OutputStream, Reader and Writer, with logging and unchecked exceptions */
23 public class Stream {
24
25     protected final In in;
26     protected final Out out;
27     private         String newLine = "\r\n";
28     private         Stream in_next = null;
29
30     public  Stream(byte[] b, int off, int len) { this.in = new Stream.In(new ByteArrayInputStream(b, off, len)); this.out=null; }
31     public  Stream(InputStream in)                   { this.in = new Stream.In(in); this.out = null; }
32     public  Stream(                OutputStream out) { this.in = null;              this.out = new Stream.Out(out); }
33     public  Stream(InputStream in, OutputStream out) { this.in = new Stream.In(in); this.out = new Stream.Out(out); }
34     public  Stream(String s)                         { this(new ByteArrayInputStream(s.getBytes())); }
35     public  Stream(File f)                           {
36         try { this.in = new Stream.In(new FileInputStream(f)); } catch (IOException e) { ioe(e); throw new Error(); }
37         this.out = null;
38     }
39     public  Stream(Socket s) {
40         try { this.in = new Stream.In(s.getInputStream());    } catch (IOException e) { ioe(e); throw new Error(); }
41         try { this.out = new Stream.Out(s.getOutputStream()); } catch (IOException e) { ioe(e); throw new Error(); }
42     }
43
44     // Main API //////////////////////////////////////////////////////////////////////////////
45
46     public char   peekc()                          { flush(); return in.getc(true); }
47     public char   getc()                           { flush(); return in.getc(false); }
48     public String readln()                         { flush(); return in.readln(); }
49     public void   print(String s)                  { out.write(s); flush(); }
50     public void   println(String s)                { print(s); print(newLine); }
51     public void   flush()                          { if (out != null) out.flushWriter(); }
52     public int    read(byte[] b, int off, int len) { flush(); return in.readBytes(b, off, len); }
53     public int    read(char[] c, int off, int len) { flush(); return in.read(c, off, len); }
54     public void   unread(String s)                 { in.unread(s); }
55     public void   close()                          { try { if (in!=null) in.close(); } finally { if (out!=null) out.close(); } }
56     public void   setNewline(String s)             { newLine = s; }
57
58     private static class Out extends BufferedOutputStream {
59         private Writer writer = new OutputStreamWriter(this);
60         public Out(OutputStream out) { super(out); }
61         public  void close() { try { super.close(); } catch (Exception e) { Log.error(this, e); } }
62         public  void write(String s) { try { writer.write(s); } catch (IOException e) { ioe(e); } }
63         private void flushWriter() { try { writer.flush(); } catch (IOException e) { ioe(e); } }
64         public  void flush() {
65             writer.flush();
66             super.flush();
67         }
68     }
69
70     private class In extends InputStream {
71         public  final Reader reader   = new InputStreamReader(this);
72         private final Writer unreader = new OutputStreamWriter(new UnReaderStream());
73         private /*final*/ InputStream orig;
74         public In(InputStream in) { orig = in; }
75
76         char[] cbuf = new char[8192];
77         int cstart = 0;
78         int cend = 0;
79
80         byte[] buf = new byte[8192];
81         int start = 0;
82         int end = 0;
83
84         boolean flushing = false;
85
86         public int available() { return flushing ? 0 : (end - start); }
87         public void close() { try {
88             if (orig!=null)      orig.close(); 
89             if (in_next != null) in_next.close();
90         } catch (Exception e) { Log.error(this, e); } }
91
92         public char getc(boolean peek) { try {
93             if (cstart == cend) {
94                 cstart = 0;
95                 cend = reader.read(cbuf, 0, cbuf.length);
96                 if (cend == -1) {
97                     cend = cstart;
98                     if (in_next == null) throw new EOF();
99                     return getc(peek);
100                 }
101             }
102             return peek ? cbuf[cstart] : cbuf[cstart++];
103         } catch (IOException e) { return (char)ioe(e); } }
104
105         public String readln() { try {
106             while(true) {
107                 for(int i=cstart; i<cend; i++)
108                     if (cbuf[i] == '\n') {
109                         // this should (in theory) handle CR, LF,
110                         // CRLF, and LFCR properly, assuming that the
111                         // file consistently uses the same ending
112                         // throughout.
113                         int begin = cstart;
114                         int len = i-cstart;
115                         cstart = i+1;
116                         if (cbuf[begin] == '\r') { begin++; len--; }
117                         while (len > 0 && cbuf[begin+len-1] == '\r') { len--; }
118                         return new String(cbuf, begin, len);
119                     }
120                 ensurec(256);
121                 int numread = reader.read(cbuf, cend, cbuf.length - cend);
122                 if (numread == -1) {
123                     reader.close();
124                     if (cstart == cend) return null;
125                     String ret = new String(cbuf, cstart, cend-cstart);
126                     cstart = cend = 0;
127                     return ret;
128                 }
129                 cend += numread;
130             }
131         } catch (IOException e) { ioe(e); return null; } }
132
133         public int read(char[] c, int pos, int len) { try {
134             if (cstart == cend) {
135                 cstart = 0;
136                 cend = reader.read(cbuf, 0, cbuf.length);
137                 if (cend == -1) { reader.close(); cend = cstart; return -1; }
138             }
139             if (len > cend - cstart) len = cend - cstart;
140             System.arraycopy(cbuf, cstart, c, pos, len);
141             cstart += len;
142             return len;
143         } catch (IOException e) { ioe(e); return -1; } }
144
145         public int readBytes(byte[] b, int pos, int len) { flushchars(); return read(b, pos, len); }
146         public int read() { byte[] b = new byte[1]; if (read(b, 0, 1) == -1) return -1; return (int)b[0]; } 
147         public int read(byte[] b, int pos, int len) { try {
148             if (start == end) {
149                 start = 0;
150                 end = orig.read(buf, 0, buf.length);
151                 if (end == -1) {
152                     orig.close();
153                     end = start;
154                     if (in_next==null) return -1;
155                     return in_next.read(b, pos, len);
156                 }
157             }
158             if (len > end - start) len = end - start;
159             System.arraycopy(buf, start, b, pos, len);
160             start += len;
161             return len;
162         } catch (IOException e) { ioe(e); return -1; } }
163
164         private void growc(int s){char[] cbuf2=new char[cbuf.length+s*2];System.arraycopy(cbuf,0,cbuf2,0,cbuf.length);cbuf=cbuf2; }
165         private void shiftc() {
166             char[] cbuf2 = new char[cbuf.length];
167             System.arraycopy(cbuf, cstart, cbuf2, 0, cend-cstart);
168             cend -= cstart;
169             cstart = 0;
170             cbuf = cbuf2;
171         }
172         private void ensurec(int space) { if (cend-cstart+space>cbuf.length) growc(space); if (cend+space>cbuf.length) shiftc(); }
173
174         private void growb(int s) { byte[] buf2 = new byte[buf.length+s*2]; System.arraycopy(buf,0,buf2,0,buf.length); buf=buf2; }
175         private void shiftb() { System.arraycopy(buf, start, buf, 0, end-start); end -= start; start = 0; }
176         private void ensureb(int space) { if (end-start+space>buf.length) growb(space); if (end+space>buf.length) shiftb(); }
177         private void ensureb2(int space) { if (end-start+space>buf.length) growb(space); if (start<space) unshiftb(); }
178         private void unshiftb() {
179             System.arraycopy(buf,start,buf,buf.length-(end-start),end-start);start=buf.length-(end-start);end=buf.length; }
180
181         public  void unread(String s) { ensurec(s.length()); s.getChars(0, s.length(), cbuf, cend); cend += s.length(); }
182
183         private void flushchars() {
184             try {
185                 flushing = true;
186                 for(; reader.ready(); reader.read(cbuf, cend++, 1)) ensurec(10);
187                 if (cend>cstart)
188                     unreader.write(cbuf, cstart, cend-cstart);
189                 cstart = cend = 0;
190                 unreader.flush();
191             } catch (IOException e) { ioe(e);
192             } finally { flushing = false; }
193         }
194
195         private class UnReaderStream extends OutputStream {
196             public void close() { }
197             public void write(int i) throws IOException { byte[] b = new byte[1]; b[0] = (byte)i; write(b, 0, 1); }
198             public void write(byte[] b) throws IOException { write(b, 0, b.length); }
199             public void write(byte[] b, int p, int l) {
200                 ensureb2(l);
201                 System.arraycopy(b, p, buf, start-l, l);
202                 start -= l;
203             }
204         }
205     }
206
207     // Utilities: append() and transcribe() //////////////////////////////////////////////////////////////////////////////
208
209     public Stream append(String in_next) { return appendStream(new Stream(in_next)); }
210     public Stream appendStream(Stream in_next) {
211         if (this.in_next != null)
212             this.in_next.appendStream(in_next);
213         else
214             this.in_next = in_next;
215         return this;
216     }
217
218     public void transcribe(Stream out) { transcribe(out, false); }
219     public void transcribe(Stream out, boolean close) {
220         try {
221             byte[] buf = new byte[1024];
222             while(true) {
223                 int numread = in.read(buf, 0, buf.length);
224                 if (numread==-1) { in.close(); break; }
225                 out.out.write(buf, 0, numread);
226             }
227             if (close) out.close();
228         } catch (IOException ioe) { ioe(ioe); }
229     }
230
231     public void transcribe(StringBuffer out) {
232         char[] buf = new char[1024];
233         while(true) {
234             int numread = in.read(buf, 0, buf.length);
235             if (numread==-1) { in.close(); return; }
236             out.append(buf, 0, numread);
237         }
238     }
239
240     public static int countLines(Stream s) {
241         int ret = 0;
242         while(s.readln() != null) ret++;
243         s.close();
244         return ret;
245     }
246
247     // Exceptions //////////////////////////////////////////////////////////////////////////////
248
249     static int ioe(IOException e) {
250         if (e instanceof SocketException && e.toString().indexOf("Connection reset")!=-1)
251             throw new Closed(e.getMessage());
252         throw new StreamException(e);
253     }
254     public static class StreamException extends RuntimeException {
255         public StreamException(Exception e) { super(e); }
256         public StreamException(String s)    { super(s); }
257     }
258     public static class EOF             extends StreamException  { public EOF() { super("End of stream"); } }
259     public static class Closed          extends StreamException  { public Closed(String s) { super(s); } }
260 }