# Source code

    001/*
    002 *  Licensed to the Apache Software Foundation (ASF) under one or more
    003 *  contributor license agreements.  See the NOTICE file distributed with
    004 *  this work for additional information regarding copyright ownership.
    005 *  The ASF licenses this file to You under the Apache License, Version 2.0
    006 *  (the "License"); you may not use this file except in compliance with
    007 *  the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 *  Unless required by applicable law or agreed to in writing, software
    012 *  distributed under the License is distributed on an "AS IS" BASIS,
    013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 *  See the License for the specific language governing permissions and
    015 *  limitations under the License.
    016 *
    017 */
    018package org.apache.commons.compress.utils;
    019
    020import java.io.IOException;
    021import java.io.InputStream;
    022
    023/**
    024 * A stream that limits reading from a wrapped stream to a given number of bytes.
    025 * @NotThreadSafe
    026 * @since 1.6
    027 */
    028public class BoundedInputStream extends InputStream {
    029    private final InputStream in;
    030    private long bytesRemaining;
    031
    032    /**
    033     * Creates the stream that will at most read the given amount of
    034     * bytes from the given stream.
    035     * @param in the stream to read from
    036     * @param size the maximum amount of bytes to read
    037     */
    038    public BoundedInputStream(final InputStream in, final long size) {
    039        this.in = in;
    040        bytesRemaining = size;
    041    }
    042
    043    @Override
    044    public int read() throws IOException {
    045        if (bytesRemaining > 0) {
    046            --bytesRemaining;
    047            return in.read();
    048        }
    049        return -1;
    050    }
    051
    052    @Override
    053    public int read(final byte[] b, final int off, final int len) throws IOException {
    054        if (bytesRemaining == 0) {
    055            return -1;
    056        }
    057        int bytesToRead = len;
    058        if (bytesToRead > bytesRemaining) {
    059            bytesToRead = (int) bytesRemaining;
    060        }
    061        final int bytesRead = in.read(b, off, bytesToRead);
    062        if (bytesRead >= 0) {
    063            bytesRemaining -= bytesRead;
    064        }
    065        return bytesRead;
    066    }
    067
    068    @Override
    069    public void close() {
    070        // there isn't anything to close in this stream and the nested
    071        // stream is controlled externally
    072    }
    073}