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