Home | History | Annotate | Download | only in mail
      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.voicemail.impl.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 is
     23  * used to allow a client to read directly from an underlying protocol stream without reading past
     24  * where the protocol handler intended the client to read.
     25  */
     26 public class FixedLengthInputStream extends InputStream {
     27   private final InputStream in;
     28   private final int length;
     29   private int count;
     30 
     31   public FixedLengthInputStream(InputStream in, int length) {
     32     this.in = in;
     33     this.length = length;
     34   }
     35 
     36   @Override
     37   public int available() throws IOException {
     38     return length - count;
     39   }
     40 
     41   @Override
     42   public int read() throws IOException {
     43     if (count < length) {
     44       count++;
     45       return in.read();
     46     } else {
     47       return -1;
     48     }
     49   }
     50 
     51   @Override
     52   public int read(byte[] b, int offset, int length) throws IOException {
     53     if (count < this.length) {
     54       int d = in.read(b, offset, Math.min(this.length - count, length));
     55       if (d == -1) {
     56         return -1;
     57       } else {
     58         count += d;
     59         return d;
     60       }
     61     } else {
     62       return -1;
     63     }
     64   }
     65 
     66   @Override
     67   public int read(byte[] b) throws IOException {
     68     return read(b, 0, b.length);
     69   }
     70 
     71   public int getLength() {
     72     return length;
     73   }
     74 
     75   @Override
     76   public String toString() {
     77     return String.format("FixedLengthInputStream(in=%s, length=%d)", in.toString(), length);
     78   }
     79 }
     80