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.
7 import org.ibex.crypto.*;
9 /** package-private class */
10 abstract class ByteBufInputStream extends InputStream {
12 private InputStream is;
13 public Stream next = null;
14 private byte[] buf = new byte[8192];
15 private int start = 0;
17 public int limit = -1;
18 public Digest digest = null;
20 public ByteBufInputStream(InputStream is) {
24 public void appendStream(Stream next) {
25 if (this.next == null) this.next = next;
26 else this.next.appendStream(next);
28 public void setLimit(int limit) { this.limit = limit; }
29 private int bufSize() { if (end==start) { end = start = 0; } return end-start; }
30 private int fillBufIfEmpty() {
32 if (bufSize() > 0) return bufSize();
33 if (is == null) return -1;
34 if (prereading) return -1;
37 if (limit == 0) end = -1;
38 else if (limit == -1) end = is.read(buf, 0, buf.length);
39 else end = is.read(buf, 0, Math.min(buf.length, limit));
44 // FIXME: append to a stream that has already run out?
45 is = next.getInputStream();
51 if (limit >= 0) limit = Math.max(0, limit-end);
52 if (digest != null) digest.update(buf, 0, end);
55 if (end == -1) { end = 0; return -1; }
57 } catch (IOException e) { Stream.ioe(e); return -1; }
60 public int available() { return end-start; }
63 if (is != null) is.close();
64 if (next != null) next.close();
65 } catch (IOException e) { Stream.ioe(e); }
68 private boolean prereading = false;
69 public abstract void preread();
70 public int read() { byte[] b = new byte[0]; if (read(b, 0, 1)<=0) return -1; return b[0] & 0xff; }
71 public int skip(int len) {
73 return read(null, 0, len);
75 public int read(byte[] c, int pos, int len) {
76 if (prereading) return -1;
80 } finally { prereading = false; }
81 if (fillBufIfEmpty() == -1) return -1;
82 if (len > end - start) len = end - start;
83 if (c!=null) System.arraycopy(buf, start, c, pos, len);
88 public void pushback(byte[] b, int off, int len) {
91 /* FIXME, this allocates too often */
92 byte[] newbuf = new byte[len+(end-start)];
93 System.arraycopy(buf, start, newbuf, len, (end-start));
95 end = len + (end-start);
98 System.arraycopy(b, off, buf, start-len, len);