package anastore.util;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * A filtering input stream that passes data through untouched, but
 * counts the number of bytes read from it.
 */
public class CountingInputStream extends FilterInputStream
{
    private final StreamStatistics _stats;

    /**
     * Construct an input stream that reads from the given input
     * stream.
     */
    public CountingInputStream(InputStream in, StreamStatistics stats)
    {
        super(in);
        _stats = stats;
    }

    @Override
    public int read()
        throws IOException
    {
        int res = in.read();
        if (res != -1)
            _stats.addToBytesReceived(1);
        return res;
    }

    @Override
    public int read(byte[] b)
        throws IOException 
    {
        int res = in.read(b);
        if (res != -1)
            _stats.addToBytesReceived(res);
        return res;
    }

    @Override
    public int read(byte[] b, int off, int len)
        throws IOException 
    {
        int res = in.read(b, off, len);
        if (res != -1)
            _stats.addToBytesReceived(res);
        return res;
    }
}
