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