1/* 2 * Copyright (C) 2007 The Guava Authors 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.google.common.io; 18 19import com.google.common.annotations.Beta; 20import com.google.common.base.Preconditions; 21 22import java.io.FilterInputStream; 23import java.io.IOException; 24import java.io.InputStream; 25 26/** 27 * An InputStream that limits the number of bytes which can be read. 28 * 29 * @author Charles Fry 30 * @since 1.0 31 */ 32@Beta 33public final class LimitInputStream extends FilterInputStream { 34 35 private long left; 36 private long mark = -1; 37 38 /** 39 * Wraps another input stream, limiting the number of bytes which can be read. 40 * 41 * @param in the input stream to be wrapped 42 * @param limit the maximum number of bytes to be read 43 */ 44 public LimitInputStream(InputStream in, long limit) { 45 super(in); 46 Preconditions.checkNotNull(in); 47 Preconditions.checkArgument(limit >= 0, "limit must be non-negative"); 48 left = limit; 49 } 50 51 @Override public int available() throws IOException { 52 return (int) Math.min(in.available(), left); 53 } 54 55 @Override public synchronized void mark(int readlimit) { 56 in.mark(readlimit); 57 mark = left; 58 // it's okay to mark even if mark isn't supported, as reset won't work 59 } 60 61 @Override public int read() throws IOException { 62 if (left == 0) { 63 return -1; 64 } 65 66 int result = in.read(); 67 if (result != -1) { 68 --left; 69 } 70 return result; 71 } 72 73 @Override public int read(byte[] b, int off, int len) throws IOException { 74 if (left == 0) { 75 return -1; 76 } 77 78 len = (int) Math.min(len, left); 79 int result = in.read(b, off, len); 80 if (result != -1) { 81 left -= result; 82 } 83 return result; 84 } 85 86 @Override public synchronized void reset() throws IOException { 87 if (!in.markSupported()) { 88 throw new IOException("Mark not supported"); 89 } 90 if (mark == -1) { 91 throw new IOException("Mark not set"); 92 } 93 94 in.reset(); 95 left = mark; 96 } 97 98 @Override public long skip(long n) throws IOException { 99 n = Math.min(n, left); 100 long skipped = in.skip(n); 101 left -= skipped; 102 return skipped; 103 } 104} 105