package anastore.util;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * A filtering output stream that passes data through untouched, but
 * counts the number of bytes written to it.
 */
public class CountingOutputStream extends FilterOutputStream
{
    private final StreamStatistics _stats;

    /**
     * Construct an output stream that writes through to the given
     * output stream.
     */
    public CountingOutputStream(OutputStream out, StreamStatistics stats)
    {
        super(out);
        _stats = stats;
    }

    @Override
    public void write(int b)
        throws IOException
    {
        out.write(b);
        _stats.addToBytesSent(1);
    }

    @Override
    public void write(byte[] b)
        throws IOException 
    {
        out.write(b);
        _stats.addToBytesSent(b.length);
    }

    @Override
    public void write(byte[] b,
                      int off,
                      int len)
        throws IOException 
    {
        out.write(b, off, len);
        _stats.addToBytesSent(len);
    }
}
