massive rewrite of io library
[org.ibex.io.git] / src / org / ibex / io / ByteBufInputStream.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 import java.io.*;
7
8 /** package-private class */
9 abstract class ByteBufInputStream extends InputStream {
10
11     private InputStream is;
12     public  InputStream next;
13     private byte[] buf = new byte[8192];
14     private int start = 0;
15     private int end = 0;
16     
17     public ByteBufInputStream(InputStream is) {
18         this.is = is;
19     }
20
21     private int bufSize() { if (end==start) { end = start = 0; } return end-start; }
22     private int fillBufIfEmpty() {
23         try {
24             if (bufSize() > 0) return bufSize();
25             start = 0;
26             do {
27                 end = is.read(buf, 0, buf.length);
28                 if (end == -1 && next != null) {
29                     is.close();
30                     is = next;
31                     continue;
32                 }
33             } while(end==0);
34             if (end == -1) { end = 0; return -1; }
35             return end;
36         } catch (IOException e) { Stream.ioe(e); return -1; }
37     }
38
39     public int available() { return end-start; }
40     public void close() {
41         try {
42             if (is != null) is.close();
43             if (next != null) next.close();
44         } catch (IOException e) { Stream.ioe(e); }
45     }
46
47     private boolean prereading = false;
48     public abstract void preread();
49     public int read() { byte[] b = new byte[0]; if (read(b, 0, 1)<=0) return -1; return b[0] & 0xff; }
50     public int read(byte[] c, int pos, int len) {
51         if (prereading) return -1;
52         prereading = true;
53         try {
54             preread();
55         } finally { prereading = false; }
56         if (fillBufIfEmpty() == -1) return -1;
57         if (len > end - start) len = end - start;
58         System.arraycopy(buf, start, c, pos, len);
59         start += len;
60         return len;
61     }
62
63     public void pushback(byte[] b, int off, int len) {
64         if (len <= 0) return;
65         if (start-len < 0) {
66             /* FIXME, this allocates too often */
67             byte[] newbuf = new byte[len+(end-start)];
68             System.arraycopy(buf, start, newbuf, len, (end-start));
69             buf = newbuf;
70             end = len + (end-start);
71             start = len;
72         }
73         System.arraycopy(b, off, buf, start-len, len);
74         start -= len;
75     }
76 }