1 /*
2  * Copyright (C) 2015 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 package com.android.phone.common.mail;
17 
18 import java.io.IOException;
19 import java.io.InputStream;
20 
21 /**
22  * A filtering InputStream that stops allowing reads after the given length has been read. This
23  * is used to allow a client to read directly from an underlying protocol stream without reading
24  * past where the protocol handler intended the client to read.
25  */
26 public class FixedLengthInputStream extends InputStream {
27     private final InputStream mIn;
28     private final int mLength;
29     private int mCount;
30 
FixedLengthInputStream(InputStream in, int length)31     public FixedLengthInputStream(InputStream in, int length) {
32         this.mIn = in;
33         this.mLength = length;
34     }
35 
36     @Override
available()37     public int available() throws IOException {
38         return mLength - mCount;
39     }
40 
41     @Override
read()42     public int read() throws IOException {
43         if (mCount < mLength) {
44             mCount++;
45             return mIn.read();
46         } else {
47             return -1;
48         }
49     }
50 
51     @Override
read(byte[] b, int offset, int length)52     public int read(byte[] b, int offset, int length) throws IOException {
53         if (mCount < mLength) {
54             int d = mIn.read(b, offset, Math.min(mLength - mCount, length));
55             if (d == -1) {
56                 return -1;
57             } else {
58                 mCount += d;
59                 return d;
60             }
61         } else {
62             return -1;
63         }
64     }
65 
66     @Override
read(byte[] b)67     public int read(byte[] b) throws IOException {
68         return read(b, 0, b.length);
69     }
70 
getLength()71     public int getLength() {
72         return mLength;
73     }
74 
75     @Override
toString()76     public String toString() {
77         return String.format("FixedLengthInputStream(in=%s, length=%d)", mIn.toString(), mLength);
78     }
79 }