1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.email;
18
19import java.io.IOException;
20import java.io.InputStream;
21
22/**
23 * A filtering InputStream that stops allowing reads after the given length has been read. This
24 * is used to allow a client to read directly from an underlying protocol stream without reading
25 * past where the protocol handler intended the client to read.
26 */
27public class FixedLengthInputStream extends InputStream {
28    private final InputStream mIn;
29    private final int mLength;
30    private int mCount;
31
32    public FixedLengthInputStream(InputStream in, int length) {
33        this.mIn = in;
34        this.mLength = length;
35    }
36
37    @Override
38    public int available() throws IOException {
39        return mLength - mCount;
40    }
41
42    @Override
43    public int read() throws IOException {
44        if (mCount < mLength) {
45            mCount++;
46            return mIn.read();
47        } else {
48            return -1;
49        }
50    }
51
52    @Override
53    public int read(byte[] b, int offset, int length) throws IOException {
54        if (mCount < mLength) {
55            int d = mIn.read(b, offset, Math.min(mLength - mCount, length));
56            if (d == -1) {
57                return -1;
58            } else {
59                mCount += d;
60                return d;
61            }
62        } else {
63            return -1;
64        }
65    }
66
67    @Override
68    public int read(byte[] b) throws IOException {
69        return read(b, 0, b.length);
70    }
71
72    public int getLength() {
73        return mLength;
74    }
75
76    @Override
77    public String toString() {
78        return String.format("FixedLengthInputStream(in=%s, length=%d)", mIn.toString(), mLength);
79    }
80}
81