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 * http://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 * @since 1.3
028 * @NotThreadSafe
029 */
030public class CountingInputStream extends FilterInputStream {
031    private long bytesRead;
032
033    public CountingInputStream(final InputStream in) {
034        super(in);
035    }
036
037    @Override
038    public int read() throws IOException {
039        final int r = in.read();
040        if (r >= 0) {
041            count(1);
042        }
043        return r;
044    }
045
046    @Override
047    public int read(final byte[] b) throws IOException {
048        return read(b, 0, b.length);
049    }
050
051    @Override
052    public int read(final byte[] b, final int off, final int len) throws IOException {
053        if (len == 0) {
054            return 0;
055        }
056        final int r = in.read(b, off, len);
057        if (r >= 0) {
058            count(r);
059        }
060        return r;
061    }
062
063    /**
064     * Increments the counter of already read bytes.
065     * Doesn't increment if the EOF has been hit (read == -1)
066     *
067     * @param read the number of bytes read
068     */
069    protected final void count(final long read) {
070        if (read != -1) {
071            bytesRead += read;
072        }
073    }
074
075    /**
076     * Returns the current number of bytes read from this stream.
077     * @return the number of read bytes
078     */
079    public long getBytesRead() {
080        return bytesRead;
081    }
082}