001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.commons.compress.utils;
020
021import java.io.FilterInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024
025/**
026 * Input stream that tracks the number of bytes read.
027 *
028 * @since 1.3
029 * @NotThreadSafe
030 * @deprecated Use {@link org.apache.commons.io.input.CountingInputStream}.
031 */
032@Deprecated
033public class CountingInputStream extends FilterInputStream {
034    private long bytesRead;
035
036    /**
037     * Creates a {@code CountingInputStream} by assigning the argument {@code in} to the field {@code this.in} so as to remember it for later use.
038     *
039     * @param in the underlying input stream, or {@code null} if this instance is to be created without an underlying stream.
040     */
041    public CountingInputStream(final InputStream in) {
042        super(in);
043    }
044
045    /**
046     * Increments the counter of already read bytes. Doesn't increment if the EOF has been hit (read == -1)
047     *
048     * @param read the number of bytes read
049     */
050    protected final void count(final long read) {
051        if (read != -1) {
052            bytesRead += read;
053        }
054    }
055
056    /**
057     * Returns the current number of bytes read from this stream.
058     *
059     * @return the number of read bytes
060     */
061    public long getBytesRead() {
062        return bytesRead;
063    }
064
065    @Override
066    public int read() throws IOException {
067        final int r = in.read();
068        if (r >= 0) {
069            count(1);
070        }
071        return r;
072    }
073
074    @Override
075    public int read(final byte[] b) throws IOException {
076        return read(b, 0, b.length);
077    }
078
079    @Override
080    public int read(final byte[] b, final int off, final int len) throws IOException {
081        if (len == 0) {
082            return 0;
083        }
084        final int r = in.read(b, off, len);
085        if (r >= 0) {
086            count(r);
087        }
088        return r;
089    }
090}