1/* 2 * Copyright (C) 2014 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.internal.util; 18 19import libcore.io.Streams; 20 21import java.io.IOException; 22import java.io.InputStream; 23 24/** 25 * Reads exact number of bytes from wrapped stream, returning EOF once those 26 * bytes have been read. 27 */ 28public class SizedInputStream extends InputStream { 29 private final InputStream mWrapped; 30 private long mLength; 31 32 public SizedInputStream(InputStream wrapped, long length) { 33 mWrapped = wrapped; 34 mLength = length; 35 } 36 37 @Override 38 public void close() throws IOException { 39 super.close(); 40 mWrapped.close(); 41 } 42 43 @Override 44 public int read() throws IOException { 45 return Streams.readSingleByte(this); 46 } 47 48 @Override 49 public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { 50 if (mLength <= 0) { 51 return -1; 52 } else if (byteCount > mLength) { 53 byteCount = (int) mLength; 54 } 55 56 final int n = mWrapped.read(buffer, byteOffset, byteCount); 57 if (n == -1) { 58 if (mLength > 0) { 59 throw new IOException("Unexpected EOF; expected " + mLength + " more bytes"); 60 } 61 } else { 62 mLength -= n; 63 } 64 return n; 65 } 66} 67