01: package org.bouncycastle.asn1;
02:
03: import java.io.IOException;
04: import java.io.InputStream;
05:
06: class IndefiniteLengthInputStream extends LimitedInputStream {
07: private int _b1;
08: private int _b2;
09: private boolean _eofReached = false;
10: private boolean _eofOn00 = true;
11:
12: IndefiniteLengthInputStream(InputStream in) throws IOException {
13: super (in);
14:
15: _b1 = in.read();
16: _b2 = in.read();
17: _eofReached = (_b2 < 0);
18: }
19:
20: void setEofOn00(boolean eofOn00) {
21: _eofOn00 = eofOn00;
22: }
23:
24: boolean checkForEof() {
25: if (_eofOn00 && (_b1 == 0x00 && _b2 == 0x00)) {
26: _eofReached = true;
27: setParentEofDetect(true);
28: }
29: return _eofReached;
30: }
31:
32: public int read(byte[] b, int off, int len) throws IOException {
33: // Only use this optimisation if we aren't checking for 00
34: if (_eofOn00 || len < 3) {
35: return super .read(b, off, len);
36: }
37:
38: if (_eofReached) {
39: return -1;
40: }
41:
42: int numRead = _in.read(b, off + 2, len - 2);
43:
44: if (numRead < 0) {
45: // throw new EOFException();
46: _eofReached = true;
47: return -1;
48: }
49:
50: b[off] = (byte) _b1;
51: b[off + 1] = (byte) _b2;
52:
53: _b1 = _in.read();
54: _b2 = _in.read();
55:
56: if (_b2 < 0) {
57: // Corrupted stream
58: // throw new EOFException();
59: _eofReached = true;
60: // Just fall thru...
61: }
62:
63: return numRead + 2;
64: }
65:
66: public int read() throws IOException {
67: if (checkForEof()) {
68: return -1;
69: }
70:
71: int b = _in.read();
72:
73: //
74: // strictly speaking we should return b1 and b2, but if this happens the stream
75: // is corrupted so we are already in trouble.
76: //
77: if (b < 0) {
78: // Corrupted stream
79: // throw new EOFException();
80: _eofReached = true;
81:
82: return -1;
83: }
84:
85: int v = _b1;
86:
87: _b1 = _b2;
88: _b2 = b;
89:
90: return v;
91: }
92: }
|