package com.atlassian.stash.internal.web.util.web;

import javax.servlet.ServletInputStream;
import java.io.IOException;

/**
 * Counts the number of bytes read through this ServletInputStream
 *
 * @since 4.0
 */
public class CountingServletInputStream extends FilterServletInputStream {
    
    private long count;
    private long mark = -1;

    public CountingServletInputStream(ServletInputStream in) {
        super(in);
    }

    /**
     * Returns the number of bytes read.
     */
    public long getBytesRead() {
        return count;
    }

    @Override
    public void mark(int readlimit) {
        in.mark(readlimit);
        mark = count;
    }

    @Override
    public int read() throws IOException {
        int result = in.read();
        if (result != -1) {
            count++;
        }
        return result;
    }

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

    @Override
    public void reset() throws IOException {
        in.reset();
        count = mark;
    }

    @Override
    public long skip(long n) throws IOException {
        long result = in.skip(n);
        count += result;
        return result;
    }
}