LimitedLengthInputStream.java revision ceb1b0bfaea56251796b08c07b963de7403d84eb
1package android.content.pm;
2
3import java.io.FilterInputStream;
4import java.io.IOException;
5import java.io.InputStream;
6
7/**
8 * A class that limits the amount of data that is read from an InputStream. When
9 * the specified length is reached, the stream returns an EOF even if the
10 * underlying stream still has more data.
11 *
12 * @hide
13 */
14public class LimitedLengthInputStream extends FilterInputStream {
15    /**
16     * The end of the stream where we don't want to allow more data to be read.
17     */
18    private final int mEnd;
19
20    /**
21     * Current offset in the stream.
22     */
23    private int mOffset;
24
25    /**
26     * @param in underlying stream to wrap
27     * @param offset offset into stream where data starts
28     * @param length length of data at offset
29     * @throws IOException if an error occured with the underlying stream
30     */
31    public LimitedLengthInputStream(InputStream in, int offset, int length) throws IOException {
32        super(in);
33
34        if (in == null) {
35            throw new IOException("in == null");
36        }
37
38        if (offset < 0) {
39            throw new IOException("offset == " + offset);
40        }
41
42        if (length < 0) {
43            throw new IOException("length must be non-negative; is " + length);
44        }
45
46        mEnd = offset + length;
47
48        skip(offset);
49        mOffset = offset;
50    }
51
52    @Override
53    public synchronized int read() throws IOException {
54        if (mOffset >= mEnd) {
55            return -1;
56        }
57
58        mOffset++;
59        return super.read();
60    }
61
62    @Override
63    public int read(byte[] buffer, int offset, int byteCount) throws IOException {
64        if (mOffset >= mEnd) {
65            return -1;
66        }
67
68        if (mOffset + byteCount > mEnd) {
69            byteCount = mEnd - mOffset;
70        }
71
72        final int numRead = super.read(buffer, offset, byteCount);
73        mOffset += numRead;
74
75        return numRead;
76    }
77
78    @Override
79    public int read(byte[] buffer) throws IOException {
80        return read(buffer, 0, buffer.length);
81    }
82}
83