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 abstract class ByteBufInputStream extends InputStream {
11 private InputStream is;
12 public InputStream next;
13 private byte[] buf = new byte[8192];
14 private int start = 0;
17 public ByteBufInputStream(InputStream is) {
21 private int bufSize() { if (end==start) { end = start = 0; } return end-start; }
22 private int fillBufIfEmpty() {
24 if (bufSize() > 0) return bufSize();
27 end = is.read(buf, 0, buf.length);
28 if (end == -1 && next != null) {
34 if (end == -1) { end = 0; return -1; }
36 } catch (IOException e) { Stream.ioe(e); return -1; }
39 public int available() { return end-start; }
42 if (is != null) is.close();
43 if (next != null) next.close();
44 } catch (IOException e) { Stream.ioe(e); }
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;
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);
63 public void pushback(byte[] b, int off, int len) {
66 /* FIXME, this allocates too often */
67 byte[] newbuf = new byte[len+(end-start)];
68 System.arraycopy(buf, start, newbuf, len, (end-start));
70 end = len + (end-start);
73 System.arraycopy(b, off, buf, start-len, len);