01: package org.bouncycastle.asn1;
02:
03: import java.io.EOFException;
04: import java.io.InputStream;
05: import java.io.IOException;
06:
07: class DefiniteLengthInputStream extends LimitedInputStream {
08: private int _length;
09:
10: DefiniteLengthInputStream(InputStream in, int length) {
11: super (in);
12:
13: if (length < 0) {
14: throw new IllegalArgumentException(
15: "negative lengths not allowed");
16: }
17:
18: this ._length = length;
19: }
20:
21: public int read() throws IOException {
22: if (_length > 0) {
23: int b = _in.read();
24:
25: if (b < 0) {
26: throw new EOFException();
27: }
28:
29: --_length;
30: return b;
31: }
32:
33: setParentEofDetect(true);
34:
35: return -1;
36: }
37:
38: public int read(byte[] buf, int off, int len) throws IOException {
39: if (_length > 0) {
40: int toRead = Math.min(len, _length);
41: int numRead = _in.read(buf, off, toRead);
42:
43: if (numRead < 0)
44: throw new EOFException();
45:
46: _length -= numRead;
47: return numRead;
48: }
49:
50: setParentEofDetect(true);
51:
52: return -1;
53: }
54:
55: byte[] toByteArray() throws IOException {
56: byte[] bytes = new byte[_length];
57:
58: if (_length > 0) {
59: int pos = 0;
60: do {
61: int read = _in.read(bytes, pos, _length - pos);
62:
63: if (read < 0) {
64: throw new EOFException();
65: }
66:
67: pos += read;
68: } while (pos < _length);
69:
70: _length = 0;
71: }
72:
73: setParentEofDetect(true);
74:
75: return bytes;
76: }
77: }
|